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 static 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;
718 int *pack_fds = NULL;
720 TAILQ_INIT(&ignores);
722 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
723 switch (ch) {
724 case 'b':
725 branch_name = optarg;
726 break;
727 case 'm':
728 logmsg = strdup(optarg);
729 if (logmsg == NULL) {
730 error = got_error_from_errno("strdup");
731 goto done;
733 break;
734 case 'r':
735 repo_path = realpath(optarg, NULL);
736 if (repo_path == NULL) {
737 error = got_error_from_errno2("realpath",
738 optarg);
739 goto done;
741 break;
742 case 'I':
743 if (optarg[0] == '\0')
744 break;
745 error = got_pathlist_insert(&pe, &ignores, optarg,
746 NULL);
747 if (error)
748 goto done;
749 break;
750 default:
751 usage_import();
752 /* NOTREACHED */
756 argc -= optind;
757 argv += optind;
759 #ifndef PROFILE
760 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
761 "unveil",
762 NULL) == -1)
763 err(1, "pledge");
764 #endif
765 if (argc != 1)
766 usage_import();
768 if (repo_path == NULL) {
769 repo_path = getcwd(NULL, 0);
770 if (repo_path == NULL)
771 return got_error_from_errno("getcwd");
773 got_path_strip_trailing_slashes(repo_path);
774 error = get_gitconfig_path(&gitconfig_path);
775 if (error)
776 goto done;
777 error = got_repo_pack_fds_open(&pack_fds);
778 if (error != NULL)
779 goto done;
780 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
781 if (error)
782 goto done;
784 error = get_author(&author, repo, NULL);
785 if (error)
786 return error;
788 /*
789 * Don't let the user create a branch name with a leading '-'.
790 * While technically a valid reference name, this case is usually
791 * an unintended typo.
792 */
793 if (branch_name[0] == '-')
794 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
796 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
797 error = got_error_from_errno("asprintf");
798 goto done;
801 error = got_ref_open(&branch_ref, repo, refname, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF)
804 goto done;
805 } else {
806 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
807 "import target branch already exists");
808 goto done;
811 path_dir = realpath(argv[0], NULL);
812 if (path_dir == NULL) {
813 error = got_error_from_errno2("realpath", argv[0]);
814 goto done;
816 got_path_strip_trailing_slashes(path_dir);
818 /*
819 * unveil(2) traverses exec(2); if an editor is used we have
820 * to apply unveil after the log message has been written.
821 */
822 if (logmsg == NULL || strlen(logmsg) == 0) {
823 error = get_editor(&editor);
824 if (error)
825 goto done;
826 free(logmsg);
827 error = collect_import_msg(&logmsg, &logmsg_path, editor,
828 path_dir, refname);
829 if (error) {
830 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
831 logmsg_path != NULL)
832 preserve_logmsg = 1;
833 goto done;
837 if (unveil(path_dir, "r") != 0) {
838 error = got_error_from_errno2("unveil", path_dir);
839 if (logmsg_path)
840 preserve_logmsg = 1;
841 goto done;
844 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
845 if (error) {
846 if (logmsg_path)
847 preserve_logmsg = 1;
848 goto done;
851 error = got_repo_import(&new_commit_id, path_dir, logmsg,
852 author, &ignores, repo, import_progress, NULL);
853 if (error) {
854 if (logmsg_path)
855 preserve_logmsg = 1;
856 goto done;
859 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
860 if (error) {
861 if (logmsg_path)
862 preserve_logmsg = 1;
863 goto done;
866 error = got_ref_write(branch_ref, repo);
867 if (error) {
868 if (logmsg_path)
869 preserve_logmsg = 1;
870 goto done;
873 error = got_object_id_str(&id_str, new_commit_id);
874 if (error) {
875 if (logmsg_path)
876 preserve_logmsg = 1;
877 goto done;
880 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
881 if (error) {
882 if (error->code != GOT_ERR_NOT_REF) {
883 if (logmsg_path)
884 preserve_logmsg = 1;
885 goto done;
888 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
889 branch_ref);
890 if (error) {
891 if (logmsg_path)
892 preserve_logmsg = 1;
893 goto done;
896 error = got_ref_write(head_ref, repo);
897 if (error) {
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
904 printf("Created branch %s with commit %s\n",
905 got_ref_get_name(branch_ref), id_str);
906 done:
907 if (pack_fds) {
908 const struct got_error *pack_err =
909 got_repo_pack_fds_close(pack_fds);
910 if (error == NULL)
911 error = pack_err;
913 if (preserve_logmsg) {
914 fprintf(stderr, "%s: log message preserved in %s\n",
915 getprogname(), logmsg_path);
916 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
917 error = got_error_from_errno2("unlink", logmsg_path);
918 free(logmsg);
919 free(logmsg_path);
920 free(repo_path);
921 free(editor);
922 free(refname);
923 free(new_commit_id);
924 free(id_str);
925 free(author);
926 free(gitconfig_path);
927 if (branch_ref)
928 got_ref_close(branch_ref);
929 if (head_ref)
930 got_ref_close(head_ref);
931 return error;
934 __dead static void
935 usage_clone(void)
937 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
938 "[-R reference] repository-url [directory]\n", getprogname());
939 exit(1);
942 struct got_fetch_progress_arg {
943 char last_scaled_size[FMT_SCALED_STRSIZE];
944 int last_p_indexed;
945 int last_p_resolved;
946 int verbosity;
948 struct got_repository *repo;
950 int create_configs;
951 int configs_created;
952 struct {
953 struct got_pathlist_head *symrefs;
954 struct got_pathlist_head *wanted_branches;
955 struct got_pathlist_head *wanted_refs;
956 const char *proto;
957 const char *host;
958 const char *port;
959 const char *remote_repo_path;
960 const char *git_url;
961 int fetch_all_branches;
962 int mirror_references;
963 } config_info;
964 };
966 /* XXX forward declaration */
967 static const struct got_error *
968 create_config_files(const char *proto, const char *host, const char *port,
969 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
970 int mirror_references, struct got_pathlist_head *symrefs,
971 struct got_pathlist_head *wanted_branches,
972 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
974 static const struct got_error *
975 fetch_progress(void *arg, const char *message, off_t packfile_size,
976 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
978 const struct got_error *err = NULL;
979 struct got_fetch_progress_arg *a = arg;
980 char scaled_size[FMT_SCALED_STRSIZE];
981 int p_indexed, p_resolved;
982 int print_size = 0, print_indexed = 0, print_resolved = 0;
984 /*
985 * In order to allow a failed clone to be resumed with 'got fetch'
986 * we try to create configuration files as soon as possible.
987 * Once the server has sent information about its default branch
988 * we have all required information.
989 */
990 if (a->create_configs && !a->configs_created &&
991 !TAILQ_EMPTY(a->config_info.symrefs)) {
992 err = create_config_files(a->config_info.proto,
993 a->config_info.host, a->config_info.port,
994 a->config_info.remote_repo_path,
995 a->config_info.git_url,
996 a->config_info.fetch_all_branches,
997 a->config_info.mirror_references,
998 a->config_info.symrefs,
999 a->config_info.wanted_branches,
1000 a->config_info.wanted_refs, a->repo);
1001 if (err)
1002 return err;
1003 a->configs_created = 1;
1006 if (a->verbosity < 0)
1007 return NULL;
1009 if (message && message[0] != '\0') {
1010 printf("\rserver: %s", message);
1011 fflush(stdout);
1012 return NULL;
1015 if (packfile_size > 0 || nobj_indexed > 0) {
1016 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1017 (a->last_scaled_size[0] == '\0' ||
1018 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1019 print_size = 1;
1020 if (strlcpy(a->last_scaled_size, scaled_size,
1021 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1022 return got_error(GOT_ERR_NO_SPACE);
1024 if (nobj_indexed > 0) {
1025 p_indexed = (nobj_indexed * 100) / nobj_total;
1026 if (p_indexed != a->last_p_indexed) {
1027 a->last_p_indexed = p_indexed;
1028 print_indexed = 1;
1029 print_size = 1;
1032 if (nobj_resolved > 0) {
1033 p_resolved = (nobj_resolved * 100) /
1034 (nobj_total - nobj_loose);
1035 if (p_resolved != a->last_p_resolved) {
1036 a->last_p_resolved = p_resolved;
1037 print_resolved = 1;
1038 print_indexed = 1;
1039 print_size = 1;
1044 if (print_size || print_indexed || print_resolved)
1045 printf("\r");
1046 if (print_size)
1047 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1048 if (print_indexed)
1049 printf("; indexing %d%%", p_indexed);
1050 if (print_resolved)
1051 printf("; resolving deltas %d%%", p_resolved);
1052 if (print_size || print_indexed || print_resolved)
1053 fflush(stdout);
1055 return NULL;
1058 static const struct got_error *
1059 create_symref(const char *refname, struct got_reference *target_ref,
1060 int verbosity, struct got_repository *repo)
1062 const struct got_error *err;
1063 struct got_reference *head_symref;
1065 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1066 if (err)
1067 return err;
1069 err = got_ref_write(head_symref, repo);
1070 if (err == NULL && verbosity > 0) {
1071 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1072 got_ref_get_name(target_ref));
1074 got_ref_close(head_symref);
1075 return err;
1078 static const struct got_error *
1079 list_remote_refs(struct got_pathlist_head *symrefs,
1080 struct got_pathlist_head *refs)
1082 const struct got_error *err;
1083 struct got_pathlist_entry *pe;
1085 TAILQ_FOREACH(pe, symrefs, entry) {
1086 const char *refname = pe->path;
1087 const char *targetref = pe->data;
1089 printf("%s: %s\n", refname, targetref);
1092 TAILQ_FOREACH(pe, refs, entry) {
1093 const char *refname = pe->path;
1094 struct got_object_id *id = pe->data;
1095 char *id_str;
1097 err = got_object_id_str(&id_str, id);
1098 if (err)
1099 return err;
1100 printf("%s: %s\n", refname, id_str);
1101 free(id_str);
1104 return NULL;
1107 static const struct got_error *
1108 create_ref(const char *refname, struct got_object_id *id,
1109 int verbosity, struct got_repository *repo)
1111 const struct got_error *err = NULL;
1112 struct got_reference *ref;
1113 char *id_str;
1115 err = got_object_id_str(&id_str, id);
1116 if (err)
1117 return err;
1119 err = got_ref_alloc(&ref, refname, id);
1120 if (err)
1121 goto done;
1123 err = got_ref_write(ref, repo);
1124 got_ref_close(ref);
1126 if (err == NULL && verbosity >= 0)
1127 printf("Created reference %s: %s\n", refname, id_str);
1128 done:
1129 free(id_str);
1130 return err;
1133 static int
1134 match_wanted_ref(const char *refname, const char *wanted_ref)
1136 if (strncmp(refname, "refs/", 5) != 0)
1137 return 0;
1138 refname += 5;
1141 * Prevent fetching of references that won't make any
1142 * sense outside of the remote repository's context.
1144 if (strncmp(refname, "got/", 4) == 0)
1145 return 0;
1146 if (strncmp(refname, "remotes/", 8) == 0)
1147 return 0;
1149 if (strncmp(wanted_ref, "refs/", 5) == 0)
1150 wanted_ref += 5;
1152 /* Allow prefix match. */
1153 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1154 return 1;
1156 /* Allow exact match. */
1157 return (strcmp(refname, wanted_ref) == 0);
1160 static int
1161 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1163 struct got_pathlist_entry *pe;
1165 TAILQ_FOREACH(pe, wanted_refs, entry) {
1166 if (match_wanted_ref(refname, pe->path))
1167 return 1;
1170 return 0;
1173 static const struct got_error *
1174 create_wanted_ref(const char *refname, struct got_object_id *id,
1175 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1177 const struct got_error *err;
1178 char *remote_refname;
1180 if (strncmp("refs/", refname, 5) == 0)
1181 refname += 5;
1183 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1184 remote_repo_name, refname) == -1)
1185 return got_error_from_errno("asprintf");
1187 err = create_ref(remote_refname, id, verbosity, repo);
1188 free(remote_refname);
1189 return err;
1192 static const struct got_error *
1193 create_gotconfig(const char *proto, const char *host, const char *port,
1194 const char *remote_repo_path, const char *default_branch,
1195 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1196 struct got_pathlist_head *wanted_refs, int mirror_references,
1197 struct got_repository *repo)
1199 const struct got_error *err = NULL;
1200 char *gotconfig_path = NULL;
1201 char *gotconfig = NULL;
1202 FILE *gotconfig_file = NULL;
1203 const char *branchname = NULL;
1204 char *branches = NULL, *refs = NULL;
1205 ssize_t n;
1207 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1208 struct got_pathlist_entry *pe;
1209 TAILQ_FOREACH(pe, wanted_branches, entry) {
1210 char *s;
1211 branchname = pe->path;
1212 if (strncmp(branchname, "refs/heads/", 11) == 0)
1213 branchname += 11;
1214 if (asprintf(&s, "%s\"%s\" ",
1215 branches ? branches : "", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1219 free(branches);
1220 branches = s;
1222 } else if (!fetch_all_branches && default_branch) {
1223 branchname = default_branch;
1224 if (strncmp(branchname, "refs/heads/", 11) == 0)
1225 branchname += 11;
1226 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1227 err = got_error_from_errno("asprintf");
1228 goto done;
1231 if (!TAILQ_EMPTY(wanted_refs)) {
1232 struct got_pathlist_entry *pe;
1233 TAILQ_FOREACH(pe, wanted_refs, entry) {
1234 char *s;
1235 const char *refname = pe->path;
1236 if (strncmp(refname, "refs/", 5) == 0)
1237 branchname += 5;
1238 if (asprintf(&s, "%s\"%s\" ",
1239 refs ? refs : "", refname) == -1) {
1240 err = got_error_from_errno("asprintf");
1241 goto done;
1243 free(refs);
1244 refs = s;
1248 /* Create got.conf(5). */
1249 gotconfig_path = got_repo_get_path_gotconfig(repo);
1250 if (gotconfig_path == NULL) {
1251 err = got_error_from_errno("got_repo_get_path_gotconfig");
1252 goto done;
1254 gotconfig_file = fopen(gotconfig_path, "ae");
1255 if (gotconfig_file == NULL) {
1256 err = got_error_from_errno2("fopen", gotconfig_path);
1257 goto done;
1259 if (asprintf(&gotconfig,
1260 "remote \"%s\" {\n"
1261 "\tserver %s\n"
1262 "\tprotocol %s\n"
1263 "%s%s%s"
1264 "\trepository \"%s\"\n"
1265 "%s%s%s"
1266 "%s%s%s"
1267 "%s"
1268 "%s"
1269 "}\n",
1270 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1271 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1272 remote_repo_path, branches ? "\tbranch { " : "",
1273 branches ? branches : "", branches ? "}\n" : "",
1274 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1275 mirror_references ? "\tmirror-references yes\n" : "",
1276 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1277 err = got_error_from_errno("asprintf");
1278 goto done;
1280 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1281 if (n != strlen(gotconfig)) {
1282 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1283 goto done;
1286 done:
1287 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1288 err = got_error_from_errno2("fclose", gotconfig_path);
1289 free(gotconfig_path);
1290 free(branches);
1291 return err;
1294 static const struct got_error *
1295 create_gitconfig(const char *git_url, const char *default_branch,
1296 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1297 struct got_pathlist_head *wanted_refs, int mirror_references,
1298 struct got_repository *repo)
1300 const struct got_error *err = NULL;
1301 char *gitconfig_path = NULL;
1302 char *gitconfig = NULL;
1303 FILE *gitconfig_file = NULL;
1304 char *branches = NULL, *refs = NULL;
1305 const char *branchname;
1306 ssize_t n;
1308 /* Create a config file Git can understand. */
1309 gitconfig_path = got_repo_get_path_gitconfig(repo);
1310 if (gitconfig_path == NULL) {
1311 err = got_error_from_errno("got_repo_get_path_gitconfig");
1312 goto done;
1314 gitconfig_file = fopen(gitconfig_path, "ae");
1315 if (gitconfig_file == NULL) {
1316 err = got_error_from_errno2("fopen", gitconfig_path);
1317 goto done;
1319 if (fetch_all_branches) {
1320 if (mirror_references) {
1321 if (asprintf(&branches,
1322 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1323 err = got_error_from_errno("asprintf");
1324 goto done;
1326 } else if (asprintf(&branches,
1327 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1328 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 } else if (!TAILQ_EMPTY(wanted_branches)) {
1333 struct got_pathlist_entry *pe;
1334 TAILQ_FOREACH(pe, wanted_branches, entry) {
1335 char *s;
1336 branchname = pe->path;
1337 if (strncmp(branchname, "refs/heads/", 11) == 0)
1338 branchname += 11;
1339 if (mirror_references) {
1340 if (asprintf(&s,
1341 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1342 branches ? branches : "",
1343 branchname, branchname) == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 } else if (asprintf(&s,
1348 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1349 branches ? branches : "",
1350 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1351 branchname) == -1) {
1352 err = got_error_from_errno("asprintf");
1353 goto done;
1355 free(branches);
1356 branches = s;
1358 } else {
1360 * If the server specified a default branch, use just that one.
1361 * Otherwise fall back to fetching all branches on next fetch.
1363 if (default_branch) {
1364 branchname = default_branch;
1365 if (strncmp(branchname, "refs/heads/", 11) == 0)
1366 branchname += 11;
1367 } else
1368 branchname = "*"; /* fall back to all branches */
1369 if (mirror_references) {
1370 if (asprintf(&branches,
1371 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1372 branchname, branchname) == -1) {
1373 err = got_error_from_errno("asprintf");
1374 goto done;
1376 } else if (asprintf(&branches,
1377 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1378 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1379 branchname) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1384 if (!TAILQ_EMPTY(wanted_refs)) {
1385 struct got_pathlist_entry *pe;
1386 TAILQ_FOREACH(pe, wanted_refs, entry) {
1387 char *s;
1388 const char *refname = pe->path;
1389 if (strncmp(refname, "refs/", 5) == 0)
1390 refname += 5;
1391 if (mirror_references) {
1392 if (asprintf(&s,
1393 "%s\tfetch = refs/%s:refs/%s\n",
1394 refs ? refs : "", refname, refname) == -1) {
1395 err = got_error_from_errno("asprintf");
1396 goto done;
1398 } else if (asprintf(&s,
1399 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1400 refs ? refs : "",
1401 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1402 refname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 free(refs);
1407 refs = s;
1411 if (asprintf(&gitconfig,
1412 "[remote \"%s\"]\n"
1413 "\turl = %s\n"
1414 "%s"
1415 "%s"
1416 "\tfetch = refs/tags/*:refs/tags/*\n",
1417 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1418 refs ? refs : "") == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1423 if (n != strlen(gitconfig)) {
1424 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1425 goto done;
1427 done:
1428 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1429 err = got_error_from_errno2("fclose", gitconfig_path);
1430 free(gitconfig_path);
1431 free(branches);
1432 return err;
1435 static const struct got_error *
1436 create_config_files(const char *proto, const char *host, const char *port,
1437 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1438 int mirror_references, struct got_pathlist_head *symrefs,
1439 struct got_pathlist_head *wanted_branches,
1440 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1442 const struct got_error *err = NULL;
1443 const char *default_branch = NULL;
1444 struct got_pathlist_entry *pe;
1447 * If we asked for a set of wanted branches then use the first
1448 * one of those.
1450 if (!TAILQ_EMPTY(wanted_branches)) {
1451 pe = TAILQ_FIRST(wanted_branches);
1452 default_branch = pe->path;
1453 } else {
1454 /* First HEAD ref listed by server is the default branch. */
1455 TAILQ_FOREACH(pe, symrefs, entry) {
1456 const char *refname = pe->path;
1457 const char *target = pe->data;
1459 if (strcmp(refname, GOT_REF_HEAD) != 0)
1460 continue;
1462 default_branch = target;
1463 break;
1467 /* Create got.conf(5). */
1468 err = create_gotconfig(proto, host, port, remote_repo_path,
1469 default_branch, fetch_all_branches, wanted_branches,
1470 wanted_refs, mirror_references, repo);
1471 if (err)
1472 return err;
1474 /* Create a config file Git can understand. */
1475 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1476 wanted_branches, wanted_refs, mirror_references, repo);
1479 static const struct got_error *
1480 cmd_clone(int argc, char *argv[])
1482 const struct got_error *error = NULL;
1483 const char *uri, *dirname;
1484 char *proto, *host, *port, *repo_name, *server_path;
1485 char *default_destdir = NULL, *id_str = NULL;
1486 const char *repo_path;
1487 struct got_repository *repo = NULL;
1488 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1489 struct got_pathlist_entry *pe;
1490 struct got_object_id *pack_hash = NULL;
1491 int ch, fetchfd = -1, fetchstatus;
1492 pid_t fetchpid = -1;
1493 struct got_fetch_progress_arg fpa;
1494 char *git_url = NULL;
1495 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1496 int list_refs_only = 0;
1497 int *pack_fds = NULL;
1499 TAILQ_INIT(&refs);
1500 TAILQ_INIT(&symrefs);
1501 TAILQ_INIT(&wanted_branches);
1502 TAILQ_INIT(&wanted_refs);
1504 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1505 switch (ch) {
1506 case 'a':
1507 fetch_all_branches = 1;
1508 break;
1509 case 'b':
1510 error = got_pathlist_append(&wanted_branches,
1511 optarg, NULL);
1512 if (error)
1513 return error;
1514 break;
1515 case 'l':
1516 list_refs_only = 1;
1517 break;
1518 case 'm':
1519 mirror_references = 1;
1520 break;
1521 case 'v':
1522 if (verbosity < 0)
1523 verbosity = 0;
1524 else if (verbosity < 3)
1525 verbosity++;
1526 break;
1527 case 'q':
1528 verbosity = -1;
1529 break;
1530 case 'R':
1531 error = got_pathlist_append(&wanted_refs,
1532 optarg, NULL);
1533 if (error)
1534 return error;
1535 break;
1536 default:
1537 usage_clone();
1538 break;
1541 argc -= optind;
1542 argv += optind;
1544 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1545 option_conflict('a', 'b');
1546 if (list_refs_only) {
1547 if (!TAILQ_EMPTY(&wanted_branches))
1548 option_conflict('l', 'b');
1549 if (fetch_all_branches)
1550 option_conflict('l', 'a');
1551 if (mirror_references)
1552 option_conflict('l', 'm');
1553 if (!TAILQ_EMPTY(&wanted_refs))
1554 option_conflict('l', 'R');
1557 uri = argv[0];
1559 if (argc == 1)
1560 dirname = NULL;
1561 else if (argc == 2)
1562 dirname = argv[1];
1563 else
1564 usage_clone();
1566 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1567 &repo_name, uri);
1568 if (error)
1569 goto done;
1571 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1572 host, port ? ":" : "", port ? port : "",
1573 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1574 error = got_error_from_errno("asprintf");
1575 goto done;
1578 if (strcmp(proto, "git") == 0) {
1579 #ifndef PROFILE
1580 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1581 "sendfd dns inet unveil", NULL) == -1)
1582 err(1, "pledge");
1583 #endif
1584 } else if (strcmp(proto, "git+ssh") == 0 ||
1585 strcmp(proto, "ssh") == 0) {
1586 #ifndef PROFILE
1587 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1588 "sendfd unveil", NULL) == -1)
1589 err(1, "pledge");
1590 #endif
1591 } else if (strcmp(proto, "http") == 0 ||
1592 strcmp(proto, "git+http") == 0) {
1593 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1594 goto done;
1595 } else {
1596 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1597 goto done;
1599 if (dirname == NULL) {
1600 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1601 error = got_error_from_errno("asprintf");
1602 goto done;
1604 repo_path = default_destdir;
1605 } else
1606 repo_path = dirname;
1608 if (!list_refs_only) {
1609 error = got_path_mkdir(repo_path);
1610 if (error &&
1611 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1612 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1613 goto done;
1614 if (!got_path_dir_is_empty(repo_path)) {
1615 error = got_error_path(repo_path,
1616 GOT_ERR_DIR_NOT_EMPTY);
1617 goto done;
1621 error = got_dial_apply_unveil(proto);
1622 if (error)
1623 goto done;
1625 error = apply_unveil(repo_path, 0, NULL);
1626 if (error)
1627 goto done;
1629 if (verbosity >= 0)
1630 printf("Connecting to %s%s%s\n", host,
1631 port ? ":" : "", port ? port : "");
1633 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1634 server_path, verbosity);
1635 if (error)
1636 goto done;
1638 if (!list_refs_only) {
1639 error = got_repo_init(repo_path);
1640 if (error)
1641 goto done;
1642 error = got_repo_pack_fds_open(&pack_fds);
1643 if (error != NULL)
1644 goto done;
1645 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1646 if (error)
1647 goto done;
1650 fpa.last_scaled_size[0] = '\0';
1651 fpa.last_p_indexed = -1;
1652 fpa.last_p_resolved = -1;
1653 fpa.verbosity = verbosity;
1654 fpa.create_configs = 1;
1655 fpa.configs_created = 0;
1656 fpa.repo = repo;
1657 fpa.config_info.symrefs = &symrefs;
1658 fpa.config_info.wanted_branches = &wanted_branches;
1659 fpa.config_info.wanted_refs = &wanted_refs;
1660 fpa.config_info.proto = proto;
1661 fpa.config_info.host = host;
1662 fpa.config_info.port = port;
1663 fpa.config_info.remote_repo_path = server_path;
1664 fpa.config_info.git_url = git_url;
1665 fpa.config_info.fetch_all_branches = fetch_all_branches;
1666 fpa.config_info.mirror_references = mirror_references;
1667 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1668 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1669 fetch_all_branches, &wanted_branches, &wanted_refs,
1670 list_refs_only, verbosity, fetchfd, repo,
1671 fetch_progress, &fpa);
1672 if (error)
1673 goto done;
1675 if (list_refs_only) {
1676 error = list_remote_refs(&symrefs, &refs);
1677 goto done;
1680 if (pack_hash == NULL) {
1681 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1682 "server sent an empty pack file");
1683 goto done;
1685 error = got_object_id_str(&id_str, pack_hash);
1686 if (error)
1687 goto done;
1688 if (verbosity >= 0)
1689 printf("\nFetched %s.pack\n", id_str);
1690 free(id_str);
1692 /* Set up references provided with the pack file. */
1693 TAILQ_FOREACH(pe, &refs, entry) {
1694 const char *refname = pe->path;
1695 struct got_object_id *id = pe->data;
1696 char *remote_refname;
1698 if (is_wanted_ref(&wanted_refs, refname) &&
1699 !mirror_references) {
1700 error = create_wanted_ref(refname, id,
1701 GOT_FETCH_DEFAULT_REMOTE_NAME,
1702 verbosity - 1, repo);
1703 if (error)
1704 goto done;
1705 continue;
1708 error = create_ref(refname, id, verbosity - 1, repo);
1709 if (error)
1710 goto done;
1712 if (mirror_references)
1713 continue;
1715 if (strncmp("refs/heads/", refname, 11) != 0)
1716 continue;
1718 if (asprintf(&remote_refname,
1719 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1720 refname + 11) == -1) {
1721 error = got_error_from_errno("asprintf");
1722 goto done;
1724 error = create_ref(remote_refname, id, verbosity - 1, repo);
1725 free(remote_refname);
1726 if (error)
1727 goto done;
1730 /* Set the HEAD reference if the server provided one. */
1731 TAILQ_FOREACH(pe, &symrefs, entry) {
1732 struct got_reference *target_ref;
1733 const char *refname = pe->path;
1734 const char *target = pe->data;
1735 char *remote_refname = NULL, *remote_target = NULL;
1737 if (strcmp(refname, GOT_REF_HEAD) != 0)
1738 continue;
1740 error = got_ref_open(&target_ref, repo, target, 0);
1741 if (error) {
1742 if (error->code == GOT_ERR_NOT_REF) {
1743 error = NULL;
1744 continue;
1746 goto done;
1749 error = create_symref(refname, target_ref, verbosity, repo);
1750 got_ref_close(target_ref);
1751 if (error)
1752 goto done;
1754 if (mirror_references)
1755 continue;
1757 if (strncmp("refs/heads/", target, 11) != 0)
1758 continue;
1760 if (asprintf(&remote_refname,
1761 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1762 refname) == -1) {
1763 error = got_error_from_errno("asprintf");
1764 goto done;
1766 if (asprintf(&remote_target,
1767 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 target + 11) == -1) {
1769 error = got_error_from_errno("asprintf");
1770 free(remote_refname);
1771 goto done;
1773 error = got_ref_open(&target_ref, repo, remote_target, 0);
1774 if (error) {
1775 free(remote_refname);
1776 free(remote_target);
1777 if (error->code == GOT_ERR_NOT_REF) {
1778 error = NULL;
1779 continue;
1781 goto done;
1783 error = create_symref(remote_refname, target_ref,
1784 verbosity - 1, repo);
1785 free(remote_refname);
1786 free(remote_target);
1787 got_ref_close(target_ref);
1788 if (error)
1789 goto done;
1791 if (pe == NULL) {
1793 * We failed to set the HEAD reference. If we asked for
1794 * a set of wanted branches use the first of one of those
1795 * which could be fetched instead.
1797 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1798 const char *target = pe->path;
1799 struct got_reference *target_ref;
1801 error = got_ref_open(&target_ref, repo, target, 0);
1802 if (error) {
1803 if (error->code == GOT_ERR_NOT_REF) {
1804 error = NULL;
1805 continue;
1807 goto done;
1810 error = create_symref(GOT_REF_HEAD, target_ref,
1811 verbosity, repo);
1812 got_ref_close(target_ref);
1813 if (error)
1814 goto done;
1815 break;
1819 if (verbosity >= 0)
1820 printf("Created %s repository '%s'\n",
1821 mirror_references ? "mirrored" : "cloned", repo_path);
1822 done:
1823 if (pack_fds) {
1824 const struct got_error *pack_err =
1825 got_repo_pack_fds_close(pack_fds);
1826 if (error == NULL)
1827 error = pack_err;
1829 if (fetchpid > 0) {
1830 if (kill(fetchpid, SIGTERM) == -1)
1831 error = got_error_from_errno("kill");
1832 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1833 error = got_error_from_errno("waitpid");
1835 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1836 error = got_error_from_errno("close");
1837 if (repo) {
1838 const struct got_error *close_err = got_repo_close(repo);
1839 if (error == NULL)
1840 error = close_err;
1842 TAILQ_FOREACH(pe, &refs, entry) {
1843 free((void *)pe->path);
1844 free(pe->data);
1846 got_pathlist_free(&refs);
1847 TAILQ_FOREACH(pe, &symrefs, entry) {
1848 free((void *)pe->path);
1849 free(pe->data);
1851 got_pathlist_free(&symrefs);
1852 got_pathlist_free(&wanted_branches);
1853 got_pathlist_free(&wanted_refs);
1854 free(pack_hash);
1855 free(proto);
1856 free(host);
1857 free(port);
1858 free(server_path);
1859 free(repo_name);
1860 free(default_destdir);
1861 free(git_url);
1862 return error;
1865 static const struct got_error *
1866 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1867 int replace_tags, int verbosity, struct got_repository *repo)
1869 const struct got_error *err = NULL;
1870 char *new_id_str = NULL;
1871 struct got_object_id *old_id = NULL;
1873 err = got_object_id_str(&new_id_str, new_id);
1874 if (err)
1875 goto done;
1877 if (!replace_tags &&
1878 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1879 err = got_ref_resolve(&old_id, repo, ref);
1880 if (err)
1881 goto done;
1882 if (got_object_id_cmp(old_id, new_id) == 0)
1883 goto done;
1884 if (verbosity >= 0) {
1885 printf("Rejecting update of existing tag %s: %s\n",
1886 got_ref_get_name(ref), new_id_str);
1888 goto done;
1891 if (got_ref_is_symbolic(ref)) {
1892 if (verbosity >= 0) {
1893 printf("Replacing reference %s: %s\n",
1894 got_ref_get_name(ref),
1895 got_ref_get_symref_target(ref));
1897 err = got_ref_change_symref_to_ref(ref, new_id);
1898 if (err)
1899 goto done;
1900 err = got_ref_write(ref, repo);
1901 if (err)
1902 goto done;
1903 } else {
1904 err = got_ref_resolve(&old_id, repo, ref);
1905 if (err)
1906 goto done;
1907 if (got_object_id_cmp(old_id, new_id) == 0)
1908 goto done;
1910 err = got_ref_change_ref(ref, new_id);
1911 if (err)
1912 goto done;
1913 err = got_ref_write(ref, repo);
1914 if (err)
1915 goto done;
1918 if (verbosity >= 0)
1919 printf("Updated %s: %s\n", got_ref_get_name(ref),
1920 new_id_str);
1921 done:
1922 free(old_id);
1923 free(new_id_str);
1924 return err;
1927 static const struct got_error *
1928 update_symref(const char *refname, struct got_reference *target_ref,
1929 int verbosity, struct got_repository *repo)
1931 const struct got_error *err = NULL, *unlock_err;
1932 struct got_reference *symref;
1933 int symref_is_locked = 0;
1935 err = got_ref_open(&symref, repo, refname, 1);
1936 if (err) {
1937 if (err->code != GOT_ERR_NOT_REF)
1938 return err;
1939 err = got_ref_alloc_symref(&symref, refname, 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("Created reference %s: %s\n",
1949 got_ref_get_name(symref),
1950 got_ref_get_symref_target(symref));
1951 } else {
1952 symref_is_locked = 1;
1954 if (strcmp(got_ref_get_symref_target(symref),
1955 got_ref_get_name(target_ref)) == 0)
1956 goto done;
1958 err = got_ref_change_symref(symref,
1959 got_ref_get_name(target_ref));
1960 if (err)
1961 goto done;
1963 err = got_ref_write(symref, repo);
1964 if (err)
1965 goto done;
1967 if (verbosity >= 0)
1968 printf("Updated %s: %s\n", got_ref_get_name(symref),
1969 got_ref_get_symref_target(symref));
1972 done:
1973 if (symref_is_locked) {
1974 unlock_err = got_ref_unlock(symref);
1975 if (unlock_err && err == NULL)
1976 err = unlock_err;
1978 got_ref_close(symref);
1979 return err;
1982 __dead static void
1983 usage_fetch(void)
1985 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1986 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1987 "[remote-repository-name]\n",
1988 getprogname());
1989 exit(1);
1992 static const struct got_error *
1993 delete_missing_ref(struct got_reference *ref,
1994 int verbosity, struct got_repository *repo)
1996 const struct got_error *err = NULL;
1997 struct got_object_id *id = NULL;
1998 char *id_str = NULL;
2000 if (got_ref_is_symbolic(ref)) {
2001 err = got_ref_delete(ref, repo);
2002 if (err)
2003 return err;
2004 if (verbosity >= 0) {
2005 printf("Deleted %s: %s\n",
2006 got_ref_get_name(ref),
2007 got_ref_get_symref_target(ref));
2009 } else {
2010 err = got_ref_resolve(&id, repo, ref);
2011 if (err)
2012 return err;
2013 err = got_object_id_str(&id_str, id);
2014 if (err)
2015 goto done;
2017 err = got_ref_delete(ref, repo);
2018 if (err)
2019 goto done;
2020 if (verbosity >= 0) {
2021 printf("Deleted %s: %s\n",
2022 got_ref_get_name(ref), id_str);
2025 done:
2026 free(id);
2027 free(id_str);
2028 return NULL;
2031 static const struct got_error *
2032 delete_missing_refs(struct got_pathlist_head *their_refs,
2033 struct got_pathlist_head *their_symrefs,
2034 const struct got_remote_repo *remote,
2035 int verbosity, struct got_repository *repo)
2037 const struct got_error *err = NULL, *unlock_err;
2038 struct got_reflist_head my_refs;
2039 struct got_reflist_entry *re;
2040 struct got_pathlist_entry *pe;
2041 char *remote_namespace = NULL;
2042 char *local_refname = NULL;
2044 TAILQ_INIT(&my_refs);
2046 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2047 == -1)
2048 return got_error_from_errno("asprintf");
2050 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2051 if (err)
2052 goto done;
2054 TAILQ_FOREACH(re, &my_refs, entry) {
2055 const char *refname = got_ref_get_name(re->ref);
2056 const char *their_refname;
2058 if (remote->mirror_references) {
2059 their_refname = refname;
2060 } else {
2061 if (strncmp(refname, remote_namespace,
2062 strlen(remote_namespace)) == 0) {
2063 if (strcmp(refname + strlen(remote_namespace),
2064 GOT_REF_HEAD) == 0)
2065 continue;
2066 if (asprintf(&local_refname, "refs/heads/%s",
2067 refname + strlen(remote_namespace)) == -1) {
2068 err = got_error_from_errno("asprintf");
2069 goto done;
2071 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2072 continue;
2074 their_refname = local_refname;
2077 TAILQ_FOREACH(pe, their_refs, entry) {
2078 if (strcmp(their_refname, pe->path) == 0)
2079 break;
2081 if (pe != NULL)
2082 continue;
2084 TAILQ_FOREACH(pe, their_symrefs, entry) {
2085 if (strcmp(their_refname, pe->path) == 0)
2086 break;
2088 if (pe != NULL)
2089 continue;
2091 err = delete_missing_ref(re->ref, verbosity, repo);
2092 if (err)
2093 break;
2095 if (local_refname) {
2096 struct got_reference *ref;
2097 err = got_ref_open(&ref, repo, local_refname, 1);
2098 if (err) {
2099 if (err->code != GOT_ERR_NOT_REF)
2100 break;
2101 free(local_refname);
2102 local_refname = NULL;
2103 continue;
2105 err = delete_missing_ref(ref, verbosity, repo);
2106 if (err)
2107 break;
2108 unlock_err = got_ref_unlock(ref);
2109 got_ref_close(ref);
2110 if (unlock_err && err == NULL) {
2111 err = unlock_err;
2112 break;
2115 free(local_refname);
2116 local_refname = NULL;
2119 done:
2120 free(remote_namespace);
2121 free(local_refname);
2122 return err;
2125 static const struct got_error *
2126 update_wanted_ref(const char *refname, struct got_object_id *id,
2127 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2129 const struct got_error *err, *unlock_err;
2130 char *remote_refname;
2131 struct got_reference *ref;
2133 if (strncmp("refs/", refname, 5) == 0)
2134 refname += 5;
2136 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2137 remote_repo_name, refname) == -1)
2138 return got_error_from_errno("asprintf");
2140 err = got_ref_open(&ref, repo, remote_refname, 1);
2141 if (err) {
2142 if (err->code != GOT_ERR_NOT_REF)
2143 goto done;
2144 err = create_ref(remote_refname, id, verbosity, repo);
2145 } else {
2146 err = update_ref(ref, id, 0, verbosity, repo);
2147 unlock_err = got_ref_unlock(ref);
2148 if (unlock_err && err == NULL)
2149 err = unlock_err;
2150 got_ref_close(ref);
2152 done:
2153 free(remote_refname);
2154 return err;
2157 static const struct got_error *
2158 delete_ref(struct got_repository *repo, struct got_reference *ref)
2160 const struct got_error *err = NULL;
2161 struct got_object_id *id = NULL;
2162 char *id_str = NULL;
2163 const char *target;
2165 if (got_ref_is_symbolic(ref)) {
2166 target = got_ref_get_symref_target(ref);
2167 } else {
2168 err = got_ref_resolve(&id, repo, ref);
2169 if (err)
2170 goto done;
2171 err = got_object_id_str(&id_str, id);
2172 if (err)
2173 goto done;
2174 target = id_str;
2177 err = got_ref_delete(ref, repo);
2178 if (err)
2179 goto done;
2181 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2182 done:
2183 free(id);
2184 free(id_str);
2185 return err;
2188 static const struct got_error *
2189 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2191 const struct got_error *err = NULL;
2192 struct got_reflist_head refs;
2193 struct got_reflist_entry *re;
2194 char *prefix;
2196 TAILQ_INIT(&refs);
2198 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2199 err = got_error_from_errno("asprintf");
2200 goto done;
2202 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2203 if (err)
2204 goto done;
2206 TAILQ_FOREACH(re, &refs, entry)
2207 delete_ref(repo, re->ref);
2208 done:
2209 got_ref_list_free(&refs);
2210 return err;
2213 static const struct got_error *
2214 cmd_fetch(int argc, char *argv[])
2216 const struct got_error *error = NULL, *unlock_err;
2217 char *cwd = NULL, *repo_path = NULL;
2218 const char *remote_name;
2219 char *proto = NULL, *host = NULL, *port = NULL;
2220 char *repo_name = NULL, *server_path = NULL;
2221 const struct got_remote_repo *remotes, *remote = NULL;
2222 int nremotes;
2223 char *id_str = NULL;
2224 struct got_repository *repo = NULL;
2225 struct got_worktree *worktree = NULL;
2226 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2227 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2228 struct got_pathlist_entry *pe;
2229 struct got_object_id *pack_hash = NULL;
2230 int i, ch, fetchfd = -1, fetchstatus;
2231 pid_t fetchpid = -1;
2232 struct got_fetch_progress_arg fpa;
2233 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2234 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2235 int *pack_fds = NULL;
2237 TAILQ_INIT(&refs);
2238 TAILQ_INIT(&symrefs);
2239 TAILQ_INIT(&wanted_branches);
2240 TAILQ_INIT(&wanted_refs);
2242 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2243 switch (ch) {
2244 case 'a':
2245 fetch_all_branches = 1;
2246 break;
2247 case 'b':
2248 error = got_pathlist_append(&wanted_branches,
2249 optarg, NULL);
2250 if (error)
2251 return error;
2252 break;
2253 case 'd':
2254 delete_refs = 1;
2255 break;
2256 case 'l':
2257 list_refs_only = 1;
2258 break;
2259 case 'r':
2260 repo_path = realpath(optarg, NULL);
2261 if (repo_path == NULL)
2262 return got_error_from_errno2("realpath",
2263 optarg);
2264 got_path_strip_trailing_slashes(repo_path);
2265 break;
2266 case 't':
2267 replace_tags = 1;
2268 break;
2269 case 'v':
2270 if (verbosity < 0)
2271 verbosity = 0;
2272 else if (verbosity < 3)
2273 verbosity++;
2274 break;
2275 case 'q':
2276 verbosity = -1;
2277 break;
2278 case 'R':
2279 error = got_pathlist_append(&wanted_refs,
2280 optarg, NULL);
2281 if (error)
2282 return error;
2283 break;
2284 case 'X':
2285 delete_remote = 1;
2286 break;
2287 default:
2288 usage_fetch();
2289 break;
2292 argc -= optind;
2293 argv += optind;
2295 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2296 option_conflict('a', 'b');
2297 if (list_refs_only) {
2298 if (!TAILQ_EMPTY(&wanted_branches))
2299 option_conflict('l', 'b');
2300 if (fetch_all_branches)
2301 option_conflict('l', 'a');
2302 if (delete_refs)
2303 option_conflict('l', 'd');
2304 if (delete_remote)
2305 option_conflict('l', 'X');
2307 if (delete_remote) {
2308 if (fetch_all_branches)
2309 option_conflict('X', 'a');
2310 if (!TAILQ_EMPTY(&wanted_branches))
2311 option_conflict('X', 'b');
2312 if (delete_refs)
2313 option_conflict('X', 'd');
2314 if (replace_tags)
2315 option_conflict('X', 't');
2316 if (!TAILQ_EMPTY(&wanted_refs))
2317 option_conflict('X', 'R');
2320 if (argc == 0) {
2321 if (delete_remote)
2322 errx(1, "-X option requires a remote name");
2323 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2324 } else if (argc == 1)
2325 remote_name = argv[0];
2326 else
2327 usage_fetch();
2329 cwd = getcwd(NULL, 0);
2330 if (cwd == NULL) {
2331 error = got_error_from_errno("getcwd");
2332 goto done;
2335 error = got_repo_pack_fds_open(&pack_fds);
2336 if (error != NULL)
2337 goto done;
2339 if (repo_path == NULL) {
2340 error = got_worktree_open(&worktree, cwd);
2341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2342 goto done;
2343 else
2344 error = NULL;
2345 if (worktree) {
2346 repo_path =
2347 strdup(got_worktree_get_repo_path(worktree));
2348 if (repo_path == NULL)
2349 error = got_error_from_errno("strdup");
2350 if (error)
2351 goto done;
2352 } else {
2353 repo_path = strdup(cwd);
2354 if (repo_path == NULL) {
2355 error = got_error_from_errno("strdup");
2356 goto done;
2361 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2362 if (error)
2363 goto done;
2365 if (delete_remote) {
2366 error = delete_refs_for_remote(repo, remote_name);
2367 goto done; /* nothing else to do */
2370 if (worktree) {
2371 worktree_conf = got_worktree_get_gotconfig(worktree);
2372 if (worktree_conf) {
2373 got_gotconfig_get_remotes(&nremotes, &remotes,
2374 worktree_conf);
2375 for (i = 0; i < nremotes; i++) {
2376 if (strcmp(remotes[i].name, remote_name) == 0) {
2377 remote = &remotes[i];
2378 break;
2383 if (remote == NULL) {
2384 repo_conf = got_repo_get_gotconfig(repo);
2385 if (repo_conf) {
2386 got_gotconfig_get_remotes(&nremotes, &remotes,
2387 repo_conf);
2388 for (i = 0; i < nremotes; i++) {
2389 if (strcmp(remotes[i].name, remote_name) == 0) {
2390 remote = &remotes[i];
2391 break;
2396 if (remote == NULL) {
2397 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2398 for (i = 0; i < nremotes; i++) {
2399 if (strcmp(remotes[i].name, remote_name) == 0) {
2400 remote = &remotes[i];
2401 break;
2405 if (remote == NULL) {
2406 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2407 goto done;
2410 if (TAILQ_EMPTY(&wanted_branches)) {
2411 if (!fetch_all_branches)
2412 fetch_all_branches = remote->fetch_all_branches;
2413 for (i = 0; i < remote->nfetch_branches; i++) {
2414 got_pathlist_append(&wanted_branches,
2415 remote->fetch_branches[i], NULL);
2418 if (TAILQ_EMPTY(&wanted_refs)) {
2419 for (i = 0; i < remote->nfetch_refs; i++) {
2420 got_pathlist_append(&wanted_refs,
2421 remote->fetch_refs[i], NULL);
2425 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2426 &repo_name, remote->fetch_url);
2427 if (error)
2428 goto done;
2430 if (strcmp(proto, "git") == 0) {
2431 #ifndef PROFILE
2432 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2433 "sendfd dns inet unveil", NULL) == -1)
2434 err(1, "pledge");
2435 #endif
2436 } else if (strcmp(proto, "git+ssh") == 0 ||
2437 strcmp(proto, "ssh") == 0) {
2438 #ifndef PROFILE
2439 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2440 "sendfd unveil", NULL) == -1)
2441 err(1, "pledge");
2442 #endif
2443 } else if (strcmp(proto, "http") == 0 ||
2444 strcmp(proto, "git+http") == 0) {
2445 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2446 goto done;
2447 } else {
2448 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2449 goto done;
2452 error = got_dial_apply_unveil(proto);
2453 if (error)
2454 goto done;
2456 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2457 if (error)
2458 goto done;
2460 if (verbosity >= 0)
2461 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2462 port ? ":" : "", port ? port : "");
2464 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2465 server_path, verbosity);
2466 if (error)
2467 goto done;
2469 fpa.last_scaled_size[0] = '\0';
2470 fpa.last_p_indexed = -1;
2471 fpa.last_p_resolved = -1;
2472 fpa.verbosity = verbosity;
2473 fpa.repo = repo;
2474 fpa.create_configs = 0;
2475 fpa.configs_created = 0;
2476 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2477 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2478 remote->mirror_references, fetch_all_branches, &wanted_branches,
2479 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2480 fetch_progress, &fpa);
2481 if (error)
2482 goto done;
2484 if (list_refs_only) {
2485 error = list_remote_refs(&symrefs, &refs);
2486 goto done;
2489 if (pack_hash == NULL) {
2490 if (verbosity >= 0)
2491 printf("Already up-to-date\n");
2492 } else if (verbosity >= 0) {
2493 error = got_object_id_str(&id_str, pack_hash);
2494 if (error)
2495 goto done;
2496 printf("\nFetched %s.pack\n", id_str);
2497 free(id_str);
2498 id_str = NULL;
2501 /* Update references provided with the pack file. */
2502 TAILQ_FOREACH(pe, &refs, entry) {
2503 const char *refname = pe->path;
2504 struct got_object_id *id = pe->data;
2505 struct got_reference *ref;
2506 char *remote_refname;
2508 if (is_wanted_ref(&wanted_refs, refname) &&
2509 !remote->mirror_references) {
2510 error = update_wanted_ref(refname, id,
2511 remote->name, verbosity, repo);
2512 if (error)
2513 goto done;
2514 continue;
2517 if (remote->mirror_references ||
2518 strncmp("refs/tags/", refname, 10) == 0) {
2519 error = got_ref_open(&ref, repo, refname, 1);
2520 if (error) {
2521 if (error->code != GOT_ERR_NOT_REF)
2522 goto done;
2523 error = create_ref(refname, id, verbosity,
2524 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;
2537 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2538 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2539 remote_name, refname + 11) == -1) {
2540 error = got_error_from_errno("asprintf");
2541 goto done;
2544 error = got_ref_open(&ref, repo, remote_refname, 1);
2545 if (error) {
2546 if (error->code != GOT_ERR_NOT_REF)
2547 goto done;
2548 error = create_ref(remote_refname, id,
2549 verbosity, repo);
2550 if (error)
2551 goto done;
2552 } else {
2553 error = update_ref(ref, id, replace_tags,
2554 verbosity, repo);
2555 unlock_err = got_ref_unlock(ref);
2556 if (unlock_err && error == NULL)
2557 error = unlock_err;
2558 got_ref_close(ref);
2559 if (error)
2560 goto done;
2563 /* Also create a local branch if none exists yet. */
2564 error = got_ref_open(&ref, repo, refname, 1);
2565 if (error) {
2566 if (error->code != GOT_ERR_NOT_REF)
2567 goto done;
2568 error = create_ref(refname, id, verbosity,
2569 repo);
2570 if (error)
2571 goto done;
2572 } else {
2573 unlock_err = got_ref_unlock(ref);
2574 if (unlock_err && error == NULL)
2575 error = unlock_err;
2576 got_ref_close(ref);
2580 if (delete_refs) {
2581 error = delete_missing_refs(&refs, &symrefs, remote,
2582 verbosity, repo);
2583 if (error)
2584 goto done;
2587 if (!remote->mirror_references) {
2588 /* Update remote HEAD reference if the server provided one. */
2589 TAILQ_FOREACH(pe, &symrefs, entry) {
2590 struct got_reference *target_ref;
2591 const char *refname = pe->path;
2592 const char *target = pe->data;
2593 char *remote_refname = NULL, *remote_target = NULL;
2595 if (strcmp(refname, GOT_REF_HEAD) != 0)
2596 continue;
2598 if (strncmp("refs/heads/", target, 11) != 0)
2599 continue;
2601 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2602 remote->name, refname) == -1) {
2603 error = got_error_from_errno("asprintf");
2604 goto done;
2606 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2607 remote->name, target + 11) == -1) {
2608 error = got_error_from_errno("asprintf");
2609 free(remote_refname);
2610 goto done;
2613 error = got_ref_open(&target_ref, repo, remote_target,
2614 0);
2615 if (error) {
2616 free(remote_refname);
2617 free(remote_target);
2618 if (error->code == GOT_ERR_NOT_REF) {
2619 error = NULL;
2620 continue;
2622 goto done;
2624 error = update_symref(remote_refname, target_ref,
2625 verbosity, repo);
2626 free(remote_refname);
2627 free(remote_target);
2628 got_ref_close(target_ref);
2629 if (error)
2630 goto done;
2633 done:
2634 if (fetchpid > 0) {
2635 if (kill(fetchpid, SIGTERM) == -1)
2636 error = got_error_from_errno("kill");
2637 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2638 error = got_error_from_errno("waitpid");
2640 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2641 error = got_error_from_errno("close");
2642 if (repo) {
2643 const struct got_error *close_err = got_repo_close(repo);
2644 if (error == NULL)
2645 error = close_err;
2647 if (worktree)
2648 got_worktree_close(worktree);
2649 if (pack_fds) {
2650 const struct got_error *pack_err =
2651 got_repo_pack_fds_close(pack_fds);
2652 if (error == NULL)
2653 error = pack_err;
2655 TAILQ_FOREACH(pe, &refs, entry) {
2656 free((void *)pe->path);
2657 free(pe->data);
2659 got_pathlist_free(&refs);
2660 TAILQ_FOREACH(pe, &symrefs, entry) {
2661 free((void *)pe->path);
2662 free(pe->data);
2664 got_pathlist_free(&symrefs);
2665 got_pathlist_free(&wanted_branches);
2666 got_pathlist_free(&wanted_refs);
2667 free(id_str);
2668 free(cwd);
2669 free(repo_path);
2670 free(pack_hash);
2671 free(proto);
2672 free(host);
2673 free(port);
2674 free(server_path);
2675 free(repo_name);
2676 return error;
2680 __dead static void
2681 usage_checkout(void)
2683 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2684 "[-p prefix] [-q] repository-path [worktree-path]\n",
2685 getprogname());
2686 exit(1);
2689 static void
2690 show_worktree_base_ref_warning(void)
2692 fprintf(stderr, "%s: warning: could not create a reference "
2693 "to the work tree's base commit; the commit could be "
2694 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2695 "repository writable and running 'got update' will prevent this\n",
2696 getprogname());
2699 struct got_checkout_progress_arg {
2700 const char *worktree_path;
2701 int had_base_commit_ref_error;
2702 int verbosity;
2705 static const struct got_error *
2706 checkout_progress(void *arg, unsigned char status, const char *path)
2708 struct got_checkout_progress_arg *a = arg;
2710 /* Base commit bump happens silently. */
2711 if (status == GOT_STATUS_BUMP_BASE)
2712 return NULL;
2714 if (status == GOT_STATUS_BASE_REF_ERR) {
2715 a->had_base_commit_ref_error = 1;
2716 return NULL;
2719 while (path[0] == '/')
2720 path++;
2722 if (a->verbosity >= 0)
2723 printf("%c %s/%s\n", status, a->worktree_path, path);
2725 return NULL;
2728 static const struct got_error *
2729 check_cancelled(void *arg)
2731 if (sigint_received || sigpipe_received)
2732 return got_error(GOT_ERR_CANCELLED);
2733 return NULL;
2736 static const struct got_error *
2737 check_linear_ancestry(struct got_object_id *commit_id,
2738 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2739 struct got_repository *repo)
2741 const struct got_error *err = NULL;
2742 struct got_object_id *yca_id;
2744 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2745 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2746 if (err)
2747 return err;
2749 if (yca_id == NULL)
2750 return got_error(GOT_ERR_ANCESTRY);
2753 * Require a straight line of history between the target commit
2754 * and the work tree's base commit.
2756 * Non-linear situations such as this require a rebase:
2758 * (commit) D F (base_commit)
2759 * \ /
2760 * C E
2761 * \ /
2762 * B (yca)
2763 * |
2764 * A
2766 * 'got update' only handles linear cases:
2767 * Update forwards in time: A (base/yca) - B - C - D (commit)
2768 * Update backwards in time: D (base) - C - B - A (commit/yca)
2770 if (allow_forwards_in_time_only) {
2771 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2772 return got_error(GOT_ERR_ANCESTRY);
2773 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2774 got_object_id_cmp(base_commit_id, yca_id) != 0)
2775 return got_error(GOT_ERR_ANCESTRY);
2777 free(yca_id);
2778 return NULL;
2781 static const struct got_error *
2782 check_same_branch(struct got_object_id *commit_id,
2783 struct got_reference *head_ref, struct got_object_id *yca_id,
2784 struct got_repository *repo)
2786 const struct got_error *err = NULL;
2787 struct got_commit_graph *graph = NULL;
2788 struct got_object_id *head_commit_id = NULL;
2789 int is_same_branch = 0;
2791 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2792 if (err)
2793 goto done;
2795 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2796 is_same_branch = 1;
2797 goto done;
2799 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2800 is_same_branch = 1;
2801 goto done;
2804 err = got_commit_graph_open(&graph, "/", 1);
2805 if (err)
2806 goto done;
2808 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2809 check_cancelled, NULL);
2810 if (err)
2811 goto done;
2813 for (;;) {
2814 struct got_object_id *id;
2815 err = got_commit_graph_iter_next(&id, graph, repo,
2816 check_cancelled, NULL);
2817 if (err) {
2818 if (err->code == GOT_ERR_ITER_COMPLETED)
2819 err = NULL;
2820 break;
2823 if (id) {
2824 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2825 break;
2826 if (got_object_id_cmp(id, commit_id) == 0) {
2827 is_same_branch = 1;
2828 break;
2832 done:
2833 if (graph)
2834 got_commit_graph_close(graph);
2835 free(head_commit_id);
2836 if (!err && !is_same_branch)
2837 err = got_error(GOT_ERR_ANCESTRY);
2838 return err;
2841 static const struct got_error *
2842 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2844 static char msg[512];
2845 const char *branch_name;
2847 if (got_ref_is_symbolic(ref))
2848 branch_name = got_ref_get_symref_target(ref);
2849 else
2850 branch_name = got_ref_get_name(ref);
2852 if (strncmp("refs/heads/", branch_name, 11) == 0)
2853 branch_name += 11;
2855 snprintf(msg, sizeof(msg),
2856 "target commit is not contained in branch '%s'; "
2857 "the branch to use must be specified with -b; "
2858 "if necessary a new branch can be created for "
2859 "this commit with 'got branch -c %s BRANCH_NAME'",
2860 branch_name, commit_id_str);
2862 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2865 static const struct got_error *
2866 cmd_checkout(int argc, char *argv[])
2868 const struct got_error *error = NULL;
2869 struct got_repository *repo = NULL;
2870 struct got_reference *head_ref = NULL, *ref = NULL;
2871 struct got_worktree *worktree = NULL;
2872 char *repo_path = NULL;
2873 char *worktree_path = NULL;
2874 const char *path_prefix = "";
2875 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2876 char *commit_id_str = NULL;
2877 struct got_object_id *commit_id = NULL;
2878 char *cwd = NULL;
2879 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2880 struct got_pathlist_head paths;
2881 struct got_checkout_progress_arg cpa;
2882 int *pack_fds = NULL;
2884 TAILQ_INIT(&paths);
2886 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2887 switch (ch) {
2888 case 'b':
2889 branch_name = optarg;
2890 break;
2891 case 'c':
2892 commit_id_str = strdup(optarg);
2893 if (commit_id_str == NULL)
2894 return got_error_from_errno("strdup");
2895 break;
2896 case 'E':
2897 allow_nonempty = 1;
2898 break;
2899 case 'p':
2900 path_prefix = optarg;
2901 break;
2902 case 'q':
2903 verbosity = -1;
2904 break;
2905 default:
2906 usage_checkout();
2907 /* NOTREACHED */
2911 argc -= optind;
2912 argv += optind;
2914 #ifndef PROFILE
2915 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2916 "unveil", NULL) == -1)
2917 err(1, "pledge");
2918 #endif
2919 if (argc == 1) {
2920 char *base, *dotgit;
2921 const char *path;
2922 repo_path = realpath(argv[0], NULL);
2923 if (repo_path == NULL)
2924 return got_error_from_errno2("realpath", argv[0]);
2925 cwd = getcwd(NULL, 0);
2926 if (cwd == NULL) {
2927 error = got_error_from_errno("getcwd");
2928 goto done;
2930 if (path_prefix[0])
2931 path = path_prefix;
2932 else
2933 path = repo_path;
2934 error = got_path_basename(&base, path);
2935 if (error)
2936 goto done;
2937 dotgit = strstr(base, ".git");
2938 if (dotgit)
2939 *dotgit = '\0';
2940 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2941 error = got_error_from_errno("asprintf");
2942 free(base);
2943 goto done;
2945 free(base);
2946 } else if (argc == 2) {
2947 repo_path = realpath(argv[0], NULL);
2948 if (repo_path == NULL) {
2949 error = got_error_from_errno2("realpath", argv[0]);
2950 goto done;
2952 worktree_path = realpath(argv[1], NULL);
2953 if (worktree_path == NULL) {
2954 if (errno != ENOENT) {
2955 error = got_error_from_errno2("realpath",
2956 argv[1]);
2957 goto done;
2959 worktree_path = strdup(argv[1]);
2960 if (worktree_path == NULL) {
2961 error = got_error_from_errno("strdup");
2962 goto done;
2965 } else
2966 usage_checkout();
2968 got_path_strip_trailing_slashes(repo_path);
2969 got_path_strip_trailing_slashes(worktree_path);
2971 error = got_repo_pack_fds_open(&pack_fds);
2972 if (error != NULL)
2973 goto done;
2975 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2976 if (error != NULL)
2977 goto done;
2979 /* Pre-create work tree path for unveil(2) */
2980 error = got_path_mkdir(worktree_path);
2981 if (error) {
2982 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2983 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2984 goto done;
2985 if (!allow_nonempty &&
2986 !got_path_dir_is_empty(worktree_path)) {
2987 error = got_error_path(worktree_path,
2988 GOT_ERR_DIR_NOT_EMPTY);
2989 goto done;
2993 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2994 if (error)
2995 goto done;
2997 error = got_ref_open(&head_ref, repo, branch_name, 0);
2998 if (error != NULL)
2999 goto done;
3001 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3002 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3003 goto done;
3005 error = got_worktree_open(&worktree, worktree_path);
3006 if (error != NULL)
3007 goto done;
3009 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3010 path_prefix);
3011 if (error != NULL)
3012 goto done;
3013 if (!same_path_prefix) {
3014 error = got_error(GOT_ERR_PATH_PREFIX);
3015 goto done;
3018 if (commit_id_str) {
3019 struct got_reflist_head refs;
3020 TAILQ_INIT(&refs);
3021 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3022 NULL);
3023 if (error)
3024 goto done;
3025 error = got_repo_match_object_id(&commit_id, NULL,
3026 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3027 got_ref_list_free(&refs);
3028 if (error)
3029 goto done;
3030 error = check_linear_ancestry(commit_id,
3031 got_worktree_get_base_commit_id(worktree), 0, repo);
3032 if (error != NULL) {
3033 if (error->code == GOT_ERR_ANCESTRY) {
3034 error = checkout_ancestry_error(
3035 head_ref, commit_id_str);
3037 goto done;
3039 error = check_same_branch(commit_id, head_ref, NULL, repo);
3040 if (error) {
3041 if (error->code == GOT_ERR_ANCESTRY) {
3042 error = checkout_ancestry_error(
3043 head_ref, commit_id_str);
3045 goto done;
3047 error = got_worktree_set_base_commit_id(worktree, repo,
3048 commit_id);
3049 if (error)
3050 goto done;
3051 /* Expand potentially abbreviated commit ID string. */
3052 free(commit_id_str);
3053 error = got_object_id_str(&commit_id_str, commit_id);
3054 if (error)
3055 goto done;
3056 } else {
3057 commit_id = got_object_id_dup(
3058 got_worktree_get_base_commit_id(worktree));
3059 if (commit_id == NULL) {
3060 error = got_error_from_errno("got_object_id_dup");
3061 goto done;
3063 error = got_object_id_str(&commit_id_str, commit_id);
3064 if (error)
3065 goto done;
3068 error = got_pathlist_append(&paths, "", NULL);
3069 if (error)
3070 goto done;
3071 cpa.worktree_path = worktree_path;
3072 cpa.had_base_commit_ref_error = 0;
3073 cpa.verbosity = verbosity;
3074 error = got_worktree_checkout_files(worktree, &paths, repo,
3075 checkout_progress, &cpa, check_cancelled, NULL);
3076 if (error != NULL)
3077 goto done;
3079 if (got_ref_is_symbolic(head_ref)) {
3080 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3081 if (error)
3082 goto done;
3083 refname = got_ref_get_name(ref);
3084 } else
3085 refname = got_ref_get_name(head_ref);
3086 printf("Checked out %s: %s\n", refname, commit_id_str);
3087 printf("Now shut up and hack\n");
3088 if (cpa.had_base_commit_ref_error)
3089 show_worktree_base_ref_warning();
3090 done:
3091 if (pack_fds) {
3092 const struct got_error *pack_err =
3093 got_repo_pack_fds_close(pack_fds);
3094 if (error == NULL)
3095 error = pack_err;
3097 if (head_ref)
3098 got_ref_close(head_ref);
3099 if (ref)
3100 got_ref_close(ref);
3101 got_pathlist_free(&paths);
3102 free(commit_id_str);
3103 free(commit_id);
3104 free(repo_path);
3105 free(worktree_path);
3106 free(cwd);
3107 return error;
3110 struct got_update_progress_arg {
3111 int did_something;
3112 int conflicts;
3113 int obstructed;
3114 int not_updated;
3115 int missing;
3116 int not_deleted;
3117 int unversioned;
3118 int verbosity;
3121 static void
3122 print_update_progress_stats(struct got_update_progress_arg *upa)
3124 if (!upa->did_something)
3125 return;
3127 if (upa->conflicts > 0)
3128 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3129 if (upa->obstructed > 0)
3130 printf("File paths obstructed by a non-regular file: %d\n",
3131 upa->obstructed);
3132 if (upa->not_updated > 0)
3133 printf("Files not updated because of existing merge "
3134 "conflicts: %d\n", upa->not_updated);
3138 * The meaning of some status codes differs between merge-style operations and
3139 * update operations. For example, the ! status code means "file was missing"
3140 * if changes were merged into the work tree, and "missing file was restored"
3141 * if the work tree was updated. This function should be used by any operation
3142 * which merges changes into the work tree without updating the work tree.
3144 static void
3145 print_merge_progress_stats(struct got_update_progress_arg *upa)
3147 if (!upa->did_something)
3148 return;
3150 if (upa->conflicts > 0)
3151 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3152 if (upa->obstructed > 0)
3153 printf("File paths obstructed by a non-regular file: %d\n",
3154 upa->obstructed);
3155 if (upa->missing > 0)
3156 printf("Files which had incoming changes but could not be "
3157 "found in the work tree: %d\n", upa->missing);
3158 if (upa->not_deleted > 0)
3159 printf("Files not deleted due to differences in deleted "
3160 "content: %d\n", upa->not_deleted);
3161 if (upa->unversioned > 0)
3162 printf("Files not merged because an unversioned file was "
3163 "found in the work tree: %d\n", upa->unversioned);
3166 __dead static void
3167 usage_update(void)
3169 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3170 "[path ...]\n",
3171 getprogname());
3172 exit(1);
3175 static const struct got_error *
3176 update_progress(void *arg, unsigned char status, const char *path)
3178 struct got_update_progress_arg *upa = arg;
3180 if (status == GOT_STATUS_EXISTS ||
3181 status == GOT_STATUS_BASE_REF_ERR)
3182 return NULL;
3184 upa->did_something = 1;
3186 /* Base commit bump happens silently. */
3187 if (status == GOT_STATUS_BUMP_BASE)
3188 return NULL;
3190 if (status == GOT_STATUS_CONFLICT)
3191 upa->conflicts++;
3192 if (status == GOT_STATUS_OBSTRUCTED)
3193 upa->obstructed++;
3194 if (status == GOT_STATUS_CANNOT_UPDATE)
3195 upa->not_updated++;
3196 if (status == GOT_STATUS_MISSING)
3197 upa->missing++;
3198 if (status == GOT_STATUS_CANNOT_DELETE)
3199 upa->not_deleted++;
3200 if (status == GOT_STATUS_UNVERSIONED)
3201 upa->unversioned++;
3203 while (path[0] == '/')
3204 path++;
3205 if (upa->verbosity >= 0)
3206 printf("%c %s\n", status, path);
3208 return NULL;
3211 static const struct got_error *
3212 switch_head_ref(struct got_reference *head_ref,
3213 struct got_object_id *commit_id, struct got_worktree *worktree,
3214 struct got_repository *repo)
3216 const struct got_error *err = NULL;
3217 char *base_id_str;
3218 int ref_has_moved = 0;
3220 /* Trivial case: switching between two different references. */
3221 if (strcmp(got_ref_get_name(head_ref),
3222 got_worktree_get_head_ref_name(worktree)) != 0) {
3223 printf("Switching work tree from %s to %s\n",
3224 got_worktree_get_head_ref_name(worktree),
3225 got_ref_get_name(head_ref));
3226 return got_worktree_set_head_ref(worktree, head_ref);
3229 err = check_linear_ancestry(commit_id,
3230 got_worktree_get_base_commit_id(worktree), 0, repo);
3231 if (err) {
3232 if (err->code != GOT_ERR_ANCESTRY)
3233 return err;
3234 ref_has_moved = 1;
3236 if (!ref_has_moved)
3237 return NULL;
3239 /* Switching to a rebased branch with the same reference name. */
3240 err = got_object_id_str(&base_id_str,
3241 got_worktree_get_base_commit_id(worktree));
3242 if (err)
3243 return err;
3244 printf("Reference %s now points at a different branch\n",
3245 got_worktree_get_head_ref_name(worktree));
3246 printf("Switching work tree from %s to %s\n", base_id_str,
3247 got_worktree_get_head_ref_name(worktree));
3248 return NULL;
3251 static const struct got_error *
3252 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3254 const struct got_error *err;
3255 int in_progress;
3257 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3258 if (err)
3259 return err;
3260 if (in_progress)
3261 return got_error(GOT_ERR_REBASING);
3263 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3264 if (err)
3265 return err;
3266 if (in_progress)
3267 return got_error(GOT_ERR_HISTEDIT_BUSY);
3269 return NULL;
3272 static const struct got_error *
3273 check_merge_in_progress(struct got_worktree *worktree,
3274 struct got_repository *repo)
3276 const struct got_error *err;
3277 int in_progress;
3279 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3280 if (err)
3281 return err;
3282 if (in_progress)
3283 return got_error(GOT_ERR_MERGE_BUSY);
3285 return NULL;
3288 static const struct got_error *
3289 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3290 char *argv[], struct got_worktree *worktree)
3292 const struct got_error *err = NULL;
3293 char *path;
3294 struct got_pathlist_entry *new;
3295 int i;
3297 if (argc == 0) {
3298 path = strdup("");
3299 if (path == NULL)
3300 return got_error_from_errno("strdup");
3301 return got_pathlist_append(paths, path, NULL);
3304 for (i = 0; i < argc; i++) {
3305 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3306 if (err)
3307 break;
3308 err = got_pathlist_insert(&new, paths, path, NULL);
3309 if (err || new == NULL /* duplicate */) {
3310 free(path);
3311 if (err)
3312 break;
3316 return err;
3319 static const struct got_error *
3320 wrap_not_worktree_error(const struct got_error *orig_err,
3321 const char *cmdname, const char *path)
3323 const struct got_error *err;
3324 struct got_repository *repo;
3325 static char msg[512];
3326 int *pack_fds = NULL;
3328 err = got_repo_pack_fds_open(&pack_fds);
3329 if (err)
3330 return err;
3332 err = got_repo_open(&repo, path, NULL, pack_fds);
3333 if (err)
3334 return orig_err;
3336 snprintf(msg, sizeof(msg),
3337 "'got %s' needs a work tree in addition to a git repository\n"
3338 "Work trees can be checked out from this Git repository with "
3339 "'got checkout'.\n"
3340 "The got(1) manual page contains more information.", cmdname);
3341 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3342 got_repo_close(repo);
3343 if (pack_fds) {
3344 const struct got_error *pack_err =
3345 got_repo_pack_fds_close(pack_fds);
3346 if (err == NULL)
3347 err = pack_err;
3349 return err;
3352 static const struct got_error *
3353 cmd_update(int argc, char *argv[])
3355 const struct got_error *error = NULL;
3356 struct got_repository *repo = NULL;
3357 struct got_worktree *worktree = NULL;
3358 char *worktree_path = NULL;
3359 struct got_object_id *commit_id = NULL;
3360 char *commit_id_str = NULL;
3361 const char *branch_name = NULL;
3362 struct got_reference *head_ref = NULL;
3363 struct got_pathlist_head paths;
3364 struct got_pathlist_entry *pe;
3365 int ch, verbosity = 0;
3366 struct got_update_progress_arg upa;
3367 int *pack_fds = NULL;
3369 TAILQ_INIT(&paths);
3371 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3372 switch (ch) {
3373 case 'b':
3374 branch_name = optarg;
3375 break;
3376 case 'c':
3377 commit_id_str = strdup(optarg);
3378 if (commit_id_str == NULL)
3379 return got_error_from_errno("strdup");
3380 break;
3381 case 'q':
3382 verbosity = -1;
3383 break;
3384 default:
3385 usage_update();
3386 /* NOTREACHED */
3390 argc -= optind;
3391 argv += optind;
3393 #ifndef PROFILE
3394 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3395 "unveil", NULL) == -1)
3396 err(1, "pledge");
3397 #endif
3398 worktree_path = getcwd(NULL, 0);
3399 if (worktree_path == NULL) {
3400 error = got_error_from_errno("getcwd");
3401 goto done;
3404 error = got_repo_pack_fds_open(&pack_fds);
3405 if (error != NULL)
3406 goto done;
3408 error = got_worktree_open(&worktree, worktree_path);
3409 if (error) {
3410 if (error->code == GOT_ERR_NOT_WORKTREE)
3411 error = wrap_not_worktree_error(error, "update",
3412 worktree_path);
3413 goto done;
3416 error = check_rebase_or_histedit_in_progress(worktree);
3417 if (error)
3418 goto done;
3420 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3421 NULL, pack_fds);
3422 if (error != NULL)
3423 goto done;
3425 error = apply_unveil(got_repo_get_path(repo), 0,
3426 got_worktree_get_root_path(worktree));
3427 if (error)
3428 goto done;
3430 error = check_merge_in_progress(worktree, repo);
3431 if (error)
3432 goto done;
3434 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3435 if (error)
3436 goto done;
3438 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3439 got_worktree_get_head_ref_name(worktree), 0);
3440 if (error != NULL)
3441 goto done;
3442 if (commit_id_str == NULL) {
3443 error = got_ref_resolve(&commit_id, repo, head_ref);
3444 if (error != NULL)
3445 goto done;
3446 error = got_object_id_str(&commit_id_str, commit_id);
3447 if (error != NULL)
3448 goto done;
3449 } else {
3450 struct got_reflist_head refs;
3451 TAILQ_INIT(&refs);
3452 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3453 NULL);
3454 if (error)
3455 goto done;
3456 error = got_repo_match_object_id(&commit_id, NULL,
3457 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3458 got_ref_list_free(&refs);
3459 free(commit_id_str);
3460 commit_id_str = NULL;
3461 if (error)
3462 goto done;
3463 error = got_object_id_str(&commit_id_str, commit_id);
3464 if (error)
3465 goto done;
3468 if (branch_name) {
3469 struct got_object_id *head_commit_id;
3470 TAILQ_FOREACH(pe, &paths, entry) {
3471 if (pe->path_len == 0)
3472 continue;
3473 error = got_error_msg(GOT_ERR_BAD_PATH,
3474 "switching between branches requires that "
3475 "the entire work tree gets updated");
3476 goto done;
3478 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3479 if (error)
3480 goto done;
3481 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3482 repo);
3483 free(head_commit_id);
3484 if (error != NULL)
3485 goto done;
3486 error = check_same_branch(commit_id, head_ref, NULL, repo);
3487 if (error)
3488 goto done;
3489 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3490 if (error)
3491 goto done;
3492 } else {
3493 error = check_linear_ancestry(commit_id,
3494 got_worktree_get_base_commit_id(worktree), 0, repo);
3495 if (error != NULL) {
3496 if (error->code == GOT_ERR_ANCESTRY)
3497 error = got_error(GOT_ERR_BRANCH_MOVED);
3498 goto done;
3500 error = check_same_branch(commit_id, head_ref, NULL, repo);
3501 if (error)
3502 goto done;
3505 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3506 commit_id) != 0) {
3507 error = got_worktree_set_base_commit_id(worktree, repo,
3508 commit_id);
3509 if (error)
3510 goto done;
3513 memset(&upa, 0, sizeof(upa));
3514 upa.verbosity = verbosity;
3515 error = got_worktree_checkout_files(worktree, &paths, repo,
3516 update_progress, &upa, check_cancelled, NULL);
3517 if (error != NULL)
3518 goto done;
3520 if (upa.did_something) {
3521 printf("Updated to %s: %s\n",
3522 got_worktree_get_head_ref_name(worktree), commit_id_str);
3523 } else
3524 printf("Already up-to-date\n");
3526 print_update_progress_stats(&upa);
3527 done:
3528 if (pack_fds) {
3529 const struct got_error *pack_err =
3530 got_repo_pack_fds_close(pack_fds);
3531 if (error == NULL)
3532 error = pack_err;
3534 free(worktree_path);
3535 TAILQ_FOREACH(pe, &paths, entry)
3536 free((char *)pe->path);
3537 got_pathlist_free(&paths);
3538 free(commit_id);
3539 free(commit_id_str);
3540 return error;
3543 static const struct got_error *
3544 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3545 const char *path, int diff_context, int ignore_whitespace,
3546 int force_text_diff, struct got_repository *repo, FILE *outfile)
3548 const struct got_error *err = NULL;
3549 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3550 FILE *f1 = NULL, *f2 = NULL;
3551 int fd1 = -1, fd2 = -1;
3553 fd1 = got_opentempfd();
3554 if (fd1 == -1)
3555 return got_error_from_errno("got_opentempfd");
3556 fd2 = got_opentempfd();
3557 if (fd2 == -1) {
3558 err = got_error_from_errno("got_opentempfd");
3559 goto done;
3562 if (blob_id1) {
3563 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3564 fd1);
3565 if (err)
3566 goto done;
3567 f1 = got_opentemp();
3568 if (f1 == NULL) {
3569 err = got_error_from_errno("got_opentemp");
3570 goto done;
3574 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3575 if (err)
3576 goto done;
3578 f2 = got_opentemp();
3579 if (f2 == NULL) {
3580 err = got_error_from_errno("got_opentemp");
3581 goto done;
3584 while (path[0] == '/')
3585 path++;
3586 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3587 diff_context, ignore_whitespace, force_text_diff, outfile);
3588 done:
3589 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3590 err = got_error_from_errno("close");
3591 if (blob1)
3592 got_object_blob_close(blob1);
3593 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3594 err = got_error_from_errno("close");
3595 got_object_blob_close(blob2);
3596 if (f1 && fclose(f1) == EOF && err == NULL)
3597 err = got_error_from_errno("fclose");
3598 if (f2 && fclose(f2) == EOF && err == NULL)
3599 err = got_error_from_errno("fclose");
3600 return err;
3603 static const struct got_error *
3604 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3605 const char *path, int diff_context, int ignore_whitespace,
3606 int force_text_diff, struct got_repository *repo, FILE *outfile)
3608 const struct got_error *err = NULL;
3609 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3610 struct got_diff_blob_output_unidiff_arg arg;
3611 FILE *f1 = NULL, *f2 = NULL;
3613 if (tree_id1) {
3614 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3615 if (err)
3616 goto done;
3617 f1 = got_opentemp();
3618 if (f1 == NULL) {
3619 err = got_error_from_errno("got_opentemp");
3620 goto done;
3624 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3625 if (err)
3626 goto done;
3628 f2 = got_opentemp();
3629 if (f2 == NULL) {
3630 err = got_error_from_errno("got_opentemp");
3631 goto done;
3634 arg.diff_context = diff_context;
3635 arg.ignore_whitespace = ignore_whitespace;
3636 arg.force_text_diff = force_text_diff;
3637 arg.outfile = outfile;
3638 arg.line_offsets = NULL;
3639 arg.nlines = 0;
3640 while (path[0] == '/')
3641 path++;
3642 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3643 got_diff_blob_output_unidiff, &arg, 1);
3644 done:
3645 if (tree1)
3646 got_object_tree_close(tree1);
3647 if (tree2)
3648 got_object_tree_close(tree2);
3649 if (f1 && fclose(f1) == EOF && err == NULL)
3650 err = got_error_from_errno("fclose");
3651 if (f2 && fclose(f2) == EOF && err == NULL)
3652 err = got_error_from_errno("fclose");
3653 return err;
3656 static const struct got_error *
3657 get_changed_paths(struct got_pathlist_head *paths,
3658 struct got_commit_object *commit, struct got_repository *repo)
3660 const struct got_error *err = NULL;
3661 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3662 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3663 struct got_object_qid *qid;
3665 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3666 if (qid != NULL) {
3667 struct got_commit_object *pcommit;
3668 err = got_object_open_as_commit(&pcommit, repo,
3669 &qid->id);
3670 if (err)
3671 return err;
3673 tree_id1 = got_object_id_dup(
3674 got_object_commit_get_tree_id(pcommit));
3675 if (tree_id1 == NULL) {
3676 got_object_commit_close(pcommit);
3677 return got_error_from_errno("got_object_id_dup");
3679 got_object_commit_close(pcommit);
3683 if (tree_id1) {
3684 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3685 if (err)
3686 goto done;
3689 tree_id2 = got_object_commit_get_tree_id(commit);
3690 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3691 if (err)
3692 goto done;
3694 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3695 got_diff_tree_collect_changed_paths, paths, 0);
3696 done:
3697 if (tree1)
3698 got_object_tree_close(tree1);
3699 if (tree2)
3700 got_object_tree_close(tree2);
3701 free(tree_id1);
3702 return err;
3705 static const struct got_error *
3706 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3707 const char *path, int diff_context, struct got_repository *repo,
3708 FILE *outfile)
3710 const struct got_error *err = NULL;
3711 struct got_commit_object *pcommit = NULL;
3712 char *id_str1 = NULL, *id_str2 = NULL;
3713 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3714 struct got_object_qid *qid;
3716 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3717 if (qid != NULL) {
3718 err = got_object_open_as_commit(&pcommit, repo,
3719 &qid->id);
3720 if (err)
3721 return err;
3722 err = got_object_id_str(&id_str1, &qid->id);
3723 if (err)
3724 goto done;
3727 err = got_object_id_str(&id_str2, id);
3728 if (err)
3729 goto done;
3731 if (path && path[0] != '\0') {
3732 int obj_type;
3733 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3734 if (err)
3735 goto done;
3736 if (pcommit) {
3737 err = got_object_id_by_path(&obj_id1, repo,
3738 pcommit, path);
3739 if (err) {
3740 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3741 free(obj_id2);
3742 goto done;
3746 err = got_object_get_type(&obj_type, repo, obj_id2);
3747 if (err) {
3748 free(obj_id2);
3749 goto done;
3751 fprintf(outfile,
3752 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3753 fprintf(outfile, "commit - %s\n",
3754 id_str1 ? id_str1 : "/dev/null");
3755 fprintf(outfile, "commit + %s\n", id_str2);
3756 switch (obj_type) {
3757 case GOT_OBJ_TYPE_BLOB:
3758 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3759 0, 0, repo, outfile);
3760 break;
3761 case GOT_OBJ_TYPE_TREE:
3762 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3763 0, 0, repo, outfile);
3764 break;
3765 default:
3766 err = got_error(GOT_ERR_OBJ_TYPE);
3767 break;
3769 free(obj_id1);
3770 free(obj_id2);
3771 } else {
3772 obj_id2 = got_object_commit_get_tree_id(commit);
3773 if (pcommit)
3774 obj_id1 = got_object_commit_get_tree_id(pcommit);
3775 fprintf(outfile,
3776 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3777 fprintf(outfile, "commit - %s\n",
3778 id_str1 ? id_str1 : "/dev/null");
3779 fprintf(outfile, "commit + %s\n", id_str2);
3780 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3781 repo, outfile);
3783 done:
3784 free(id_str1);
3785 free(id_str2);
3786 if (pcommit)
3787 got_object_commit_close(pcommit);
3788 return err;
3791 static char *
3792 get_datestr(time_t *time, char *datebuf)
3794 struct tm mytm, *tm;
3795 char *p, *s;
3797 tm = gmtime_r(time, &mytm);
3798 if (tm == NULL)
3799 return NULL;
3800 s = asctime_r(tm, datebuf);
3801 if (s == NULL)
3802 return NULL;
3803 p = strchr(s, '\n');
3804 if (p)
3805 *p = '\0';
3806 return s;
3809 static const struct got_error *
3810 match_commit(int *have_match, struct got_object_id *id,
3811 struct got_commit_object *commit, regex_t *regex)
3813 const struct got_error *err = NULL;
3814 regmatch_t regmatch;
3815 char *id_str = NULL, *logmsg = NULL;
3817 *have_match = 0;
3819 err = got_object_id_str(&id_str, id);
3820 if (err)
3821 return err;
3823 err = got_object_commit_get_logmsg(&logmsg, commit);
3824 if (err)
3825 goto done;
3827 if (regexec(regex, got_object_commit_get_author(commit), 1,
3828 &regmatch, 0) == 0 ||
3829 regexec(regex, got_object_commit_get_committer(commit), 1,
3830 &regmatch, 0) == 0 ||
3831 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3832 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3833 *have_match = 1;
3834 done:
3835 free(id_str);
3836 free(logmsg);
3837 return err;
3840 static void
3841 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3842 regex_t *regex)
3844 regmatch_t regmatch;
3845 struct got_pathlist_entry *pe;
3847 *have_match = 0;
3849 TAILQ_FOREACH(pe, changed_paths, entry) {
3850 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3851 *have_match = 1;
3852 break;
3857 static const struct got_error *
3858 match_patch(int *have_match, struct got_commit_object *commit,
3859 struct got_object_id *id, const char *path, int diff_context,
3860 struct got_repository *repo, regex_t *regex, FILE *f)
3862 const struct got_error *err = NULL;
3863 char *line = NULL;
3864 size_t linesize = 0;
3865 ssize_t linelen;
3866 regmatch_t regmatch;
3868 *have_match = 0;
3870 err = got_opentemp_truncate(f);
3871 if (err)
3872 return err;
3874 err = print_patch(commit, id, path, diff_context, repo, f);
3875 if (err)
3876 goto done;
3878 if (fseeko(f, 0L, SEEK_SET) == -1) {
3879 err = got_error_from_errno("fseeko");
3880 goto done;
3883 while ((linelen = getline(&line, &linesize, f)) != -1) {
3884 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3885 *have_match = 1;
3886 break;
3889 done:
3890 free(line);
3891 return err;
3894 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3896 static const struct got_error*
3897 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3898 struct got_object_id *id, struct got_repository *repo,
3899 int local_only)
3901 static const struct got_error *err = NULL;
3902 struct got_reflist_entry *re;
3903 char *s;
3904 const char *name;
3906 *refs_str = NULL;
3908 TAILQ_FOREACH(re, refs, entry) {
3909 struct got_tag_object *tag = NULL;
3910 struct got_object_id *ref_id;
3911 int cmp;
3913 name = got_ref_get_name(re->ref);
3914 if (strcmp(name, GOT_REF_HEAD) == 0)
3915 continue;
3916 if (strncmp(name, "refs/", 5) == 0)
3917 name += 5;
3918 if (strncmp(name, "got/", 4) == 0)
3919 continue;
3920 if (strncmp(name, "heads/", 6) == 0)
3921 name += 6;
3922 if (strncmp(name, "remotes/", 8) == 0) {
3923 if (local_only)
3924 continue;
3925 name += 8;
3926 s = strstr(name, "/" GOT_REF_HEAD);
3927 if (s != NULL && s[strlen(s)] == '\0')
3928 continue;
3930 err = got_ref_resolve(&ref_id, repo, re->ref);
3931 if (err)
3932 break;
3933 if (strncmp(name, "tags/", 5) == 0) {
3934 err = got_object_open_as_tag(&tag, repo, ref_id);
3935 if (err) {
3936 if (err->code != GOT_ERR_OBJ_TYPE) {
3937 free(ref_id);
3938 break;
3940 /* Ref points at something other than a tag. */
3941 err = NULL;
3942 tag = NULL;
3945 cmp = got_object_id_cmp(tag ?
3946 got_object_tag_get_object_id(tag) : ref_id, id);
3947 free(ref_id);
3948 if (tag)
3949 got_object_tag_close(tag);
3950 if (cmp != 0)
3951 continue;
3952 s = *refs_str;
3953 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3954 s ? ", " : "", name) == -1) {
3955 err = got_error_from_errno("asprintf");
3956 free(s);
3957 *refs_str = NULL;
3958 break;
3960 free(s);
3963 return err;
3966 static const struct got_error *
3967 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3968 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3970 const struct got_error *err = NULL;
3971 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3972 char *comma, *s, *nl;
3973 struct got_reflist_head *refs;
3974 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3975 struct tm tm;
3976 time_t committer_time;
3978 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3979 if (refs) {
3980 err = build_refs_str(&ref_str, refs, id, repo, 1);
3981 if (err)
3982 return err;
3984 /* Display the first matching ref only. */
3985 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3986 *comma = '\0';
3989 if (ref_str == NULL) {
3990 err = got_object_id_str(&id_str, id);
3991 if (err)
3992 return err;
3995 committer_time = got_object_commit_get_committer_time(commit);
3996 if (gmtime_r(&committer_time, &tm) == NULL) {
3997 err = got_error_from_errno("gmtime_r");
3998 goto done;
4000 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4001 err = got_error(GOT_ERR_NO_SPACE);
4002 goto done;
4005 err = got_object_commit_get_logmsg(&logmsg0, commit);
4006 if (err)
4007 goto done;
4009 s = logmsg0;
4010 while (isspace((unsigned char)s[0]))
4011 s++;
4013 nl = strchr(s, '\n');
4014 if (nl) {
4015 *nl = '\0';
4018 if (ref_str)
4019 printf("%s%-7s %s\n", datebuf, ref_str, s);
4020 else
4021 printf("%s%.7s %s\n", datebuf, id_str, s);
4023 if (fflush(stdout) != 0 && err == NULL)
4024 err = got_error_from_errno("fflush");
4025 done:
4026 free(id_str);
4027 free(ref_str);
4028 free(logmsg0);
4029 return err;
4032 static const struct got_error *
4033 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4034 struct got_repository *repo, const char *path,
4035 struct got_pathlist_head *changed_paths, int show_patch,
4036 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4037 const char *custom_refs_str)
4039 const struct got_error *err = NULL;
4040 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4041 char datebuf[26];
4042 time_t committer_time;
4043 const char *author, *committer;
4044 char *refs_str = NULL;
4046 err = got_object_id_str(&id_str, id);
4047 if (err)
4048 return err;
4050 if (custom_refs_str == NULL) {
4051 struct got_reflist_head *refs;
4052 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4053 if (refs) {
4054 err = build_refs_str(&refs_str, refs, id, repo, 0);
4055 if (err)
4056 goto done;
4060 printf(GOT_COMMIT_SEP_STR);
4061 if (custom_refs_str)
4062 printf("commit %s (%s)\n", id_str, custom_refs_str);
4063 else
4064 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4065 refs_str ? refs_str : "", refs_str ? ")" : "");
4066 free(id_str);
4067 id_str = NULL;
4068 free(refs_str);
4069 refs_str = NULL;
4070 printf("from: %s\n", got_object_commit_get_author(commit));
4071 committer_time = got_object_commit_get_committer_time(commit);
4072 datestr = get_datestr(&committer_time, datebuf);
4073 if (datestr)
4074 printf("date: %s UTC\n", datestr);
4075 author = got_object_commit_get_author(commit);
4076 committer = got_object_commit_get_committer(commit);
4077 if (strcmp(author, committer) != 0)
4078 printf("via: %s\n", committer);
4079 if (got_object_commit_get_nparents(commit) > 1) {
4080 const struct got_object_id_queue *parent_ids;
4081 struct got_object_qid *qid;
4082 int n = 1;
4083 parent_ids = got_object_commit_get_parent_ids(commit);
4084 STAILQ_FOREACH(qid, parent_ids, entry) {
4085 err = got_object_id_str(&id_str, &qid->id);
4086 if (err)
4087 goto done;
4088 printf("parent %d: %s\n", n++, id_str);
4089 free(id_str);
4090 id_str = NULL;
4094 err = got_object_commit_get_logmsg(&logmsg0, commit);
4095 if (err)
4096 goto done;
4098 logmsg = logmsg0;
4099 do {
4100 line = strsep(&logmsg, "\n");
4101 if (line)
4102 printf(" %s\n", line);
4103 } while (line);
4104 free(logmsg0);
4106 if (changed_paths) {
4107 struct got_pathlist_entry *pe;
4108 TAILQ_FOREACH(pe, changed_paths, entry) {
4109 struct got_diff_changed_path *cp = pe->data;
4110 printf(" %c %s\n", cp->status, pe->path);
4112 printf("\n");
4114 if (show_patch) {
4115 err = print_patch(commit, id, path, diff_context, repo, stdout);
4116 if (err == 0)
4117 printf("\n");
4120 if (fflush(stdout) != 0 && err == NULL)
4121 err = got_error_from_errno("fflush");
4122 done:
4123 free(id_str);
4124 free(refs_str);
4125 return err;
4128 static const struct got_error *
4129 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4130 struct got_repository *repo, const char *path, int show_changed_paths,
4131 int show_patch, const char *search_pattern, int diff_context, int limit,
4132 int log_branches, int reverse_display_order,
4133 struct got_reflist_object_id_map *refs_idmap, int one_line,
4134 FILE *tmpfile)
4136 const struct got_error *err;
4137 struct got_commit_graph *graph;
4138 regex_t regex;
4139 int have_match;
4140 struct got_object_id_queue reversed_commits;
4141 struct got_object_qid *qid;
4142 struct got_commit_object *commit;
4143 struct got_pathlist_head changed_paths;
4144 struct got_pathlist_entry *pe;
4146 STAILQ_INIT(&reversed_commits);
4147 TAILQ_INIT(&changed_paths);
4149 if (search_pattern && regcomp(&regex, search_pattern,
4150 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4151 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4153 err = got_commit_graph_open(&graph, path, !log_branches);
4154 if (err)
4155 return err;
4156 err = got_commit_graph_iter_start(graph, root_id, repo,
4157 check_cancelled, NULL);
4158 if (err)
4159 goto done;
4160 for (;;) {
4161 struct got_object_id *id;
4163 if (sigint_received || sigpipe_received)
4164 break;
4166 err = got_commit_graph_iter_next(&id, graph, repo,
4167 check_cancelled, NULL);
4168 if (err) {
4169 if (err->code == GOT_ERR_ITER_COMPLETED)
4170 err = NULL;
4171 break;
4173 if (id == NULL)
4174 break;
4176 err = got_object_open_as_commit(&commit, repo, id);
4177 if (err)
4178 break;
4180 if (show_changed_paths && !reverse_display_order) {
4181 err = get_changed_paths(&changed_paths, commit, repo);
4182 if (err)
4183 break;
4186 if (search_pattern) {
4187 err = match_commit(&have_match, id, commit, &regex);
4188 if (err) {
4189 got_object_commit_close(commit);
4190 break;
4192 if (have_match == 0 && show_changed_paths)
4193 match_changed_paths(&have_match,
4194 &changed_paths, &regex);
4195 if (have_match == 0 && show_patch) {
4196 err = match_patch(&have_match, commit, id,
4197 path, diff_context, repo, &regex,
4198 tmpfile);
4199 if (err)
4200 break;
4202 if (have_match == 0) {
4203 got_object_commit_close(commit);
4204 TAILQ_FOREACH(pe, &changed_paths, entry) {
4205 free((char *)pe->path);
4206 free(pe->data);
4208 got_pathlist_free(&changed_paths);
4209 continue;
4213 if (reverse_display_order) {
4214 err = got_object_qid_alloc(&qid, id);
4215 if (err)
4216 break;
4217 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4218 got_object_commit_close(commit);
4219 } else {
4220 if (one_line)
4221 err = print_commit_oneline(commit, id,
4222 repo, refs_idmap);
4223 else
4224 err = print_commit(commit, id, repo, path,
4225 show_changed_paths ? &changed_paths : NULL,
4226 show_patch, diff_context, refs_idmap, NULL);
4227 got_object_commit_close(commit);
4228 if (err)
4229 break;
4231 if ((limit && --limit == 0) ||
4232 (end_id && got_object_id_cmp(id, end_id) == 0))
4233 break;
4235 TAILQ_FOREACH(pe, &changed_paths, entry) {
4236 free((char *)pe->path);
4237 free(pe->data);
4239 got_pathlist_free(&changed_paths);
4241 if (reverse_display_order) {
4242 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4243 err = got_object_open_as_commit(&commit, repo,
4244 &qid->id);
4245 if (err)
4246 break;
4247 if (show_changed_paths) {
4248 err = get_changed_paths(&changed_paths,
4249 commit, repo);
4250 if (err)
4251 break;
4253 if (one_line)
4254 err = print_commit_oneline(commit, &qid->id,
4255 repo, refs_idmap);
4256 else
4257 err = print_commit(commit, &qid->id, repo, path,
4258 show_changed_paths ? &changed_paths : NULL,
4259 show_patch, diff_context, refs_idmap, NULL);
4260 got_object_commit_close(commit);
4261 if (err)
4262 break;
4263 TAILQ_FOREACH(pe, &changed_paths, entry) {
4264 free((char *)pe->path);
4265 free(pe->data);
4267 got_pathlist_free(&changed_paths);
4270 done:
4271 while (!STAILQ_EMPTY(&reversed_commits)) {
4272 qid = STAILQ_FIRST(&reversed_commits);
4273 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4274 got_object_qid_free(qid);
4276 TAILQ_FOREACH(pe, &changed_paths, entry) {
4277 free((char *)pe->path);
4278 free(pe->data);
4280 got_pathlist_free(&changed_paths);
4281 if (search_pattern)
4282 regfree(&regex);
4283 got_commit_graph_close(graph);
4284 return err;
4287 __dead static void
4288 usage_log(void)
4290 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4291 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4292 "[-r repository-path] [-R] [path]\n", getprogname());
4293 exit(1);
4296 static int
4297 get_default_log_limit(void)
4299 const char *got_default_log_limit;
4300 long long n;
4301 const char *errstr;
4303 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4304 if (got_default_log_limit == NULL)
4305 return 0;
4306 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4307 if (errstr != NULL)
4308 return 0;
4309 return n;
4312 static const struct got_error *
4313 cmd_log(int argc, char *argv[])
4315 const struct got_error *error;
4316 struct got_repository *repo = NULL;
4317 struct got_worktree *worktree = NULL;
4318 struct got_object_id *start_id = NULL, *end_id = NULL;
4319 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4320 const char *start_commit = NULL, *end_commit = NULL;
4321 const char *search_pattern = NULL;
4322 int diff_context = -1, ch;
4323 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4324 int reverse_display_order = 0, one_line = 0;
4325 const char *errstr;
4326 struct got_reflist_head refs;
4327 struct got_reflist_object_id_map *refs_idmap = NULL;
4328 FILE *tmpfile = NULL;
4329 int *pack_fds = NULL;
4331 TAILQ_INIT(&refs);
4333 #ifndef PROFILE
4334 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4335 NULL)
4336 == -1)
4337 err(1, "pledge");
4338 #endif
4340 limit = get_default_log_limit();
4342 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4343 switch (ch) {
4344 case 'p':
4345 show_patch = 1;
4346 break;
4347 case 'P':
4348 show_changed_paths = 1;
4349 break;
4350 case 'c':
4351 start_commit = optarg;
4352 break;
4353 case 'C':
4354 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4355 &errstr);
4356 if (errstr != NULL)
4357 errx(1, "number of context lines is %s: %s",
4358 errstr, optarg);
4359 break;
4360 case 'l':
4361 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4362 if (errstr != NULL)
4363 errx(1, "number of commits is %s: %s",
4364 errstr, optarg);
4365 break;
4366 case 'b':
4367 log_branches = 1;
4368 break;
4369 case 'r':
4370 repo_path = realpath(optarg, NULL);
4371 if (repo_path == NULL)
4372 return got_error_from_errno2("realpath",
4373 optarg);
4374 got_path_strip_trailing_slashes(repo_path);
4375 break;
4376 case 'R':
4377 reverse_display_order = 1;
4378 break;
4379 case 's':
4380 one_line = 1;
4381 break;
4382 case 'S':
4383 search_pattern = optarg;
4384 break;
4385 case 'x':
4386 end_commit = optarg;
4387 break;
4388 default:
4389 usage_log();
4390 /* NOTREACHED */
4394 argc -= optind;
4395 argv += optind;
4397 if (diff_context == -1)
4398 diff_context = 3;
4399 else if (!show_patch)
4400 errx(1, "-C requires -p");
4402 if (one_line && (show_patch || show_changed_paths))
4403 errx(1, "cannot use -s with -p or -P");
4405 cwd = getcwd(NULL, 0);
4406 if (cwd == NULL) {
4407 error = got_error_from_errno("getcwd");
4408 goto done;
4411 error = got_repo_pack_fds_open(&pack_fds);
4412 if (error != NULL)
4413 goto done;
4415 if (repo_path == NULL) {
4416 error = got_worktree_open(&worktree, cwd);
4417 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4418 goto done;
4419 error = NULL;
4422 if (argc == 1) {
4423 if (worktree) {
4424 error = got_worktree_resolve_path(&path, worktree,
4425 argv[0]);
4426 if (error)
4427 goto done;
4428 } else {
4429 path = strdup(argv[0]);
4430 if (path == NULL) {
4431 error = got_error_from_errno("strdup");
4432 goto done;
4435 } else if (argc != 0)
4436 usage_log();
4438 if (repo_path == NULL) {
4439 repo_path = worktree ?
4440 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4442 if (repo_path == NULL) {
4443 error = got_error_from_errno("strdup");
4444 goto done;
4447 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4448 if (error != NULL)
4449 goto done;
4451 error = apply_unveil(got_repo_get_path(repo), 1,
4452 worktree ? got_worktree_get_root_path(worktree) : NULL);
4453 if (error)
4454 goto done;
4456 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4457 if (error)
4458 goto done;
4460 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4461 if (error)
4462 goto done;
4464 if (start_commit == NULL) {
4465 struct got_reference *head_ref;
4466 struct got_commit_object *commit = NULL;
4467 error = got_ref_open(&head_ref, repo,
4468 worktree ? got_worktree_get_head_ref_name(worktree)
4469 : GOT_REF_HEAD, 0);
4470 if (error != NULL)
4471 goto done;
4472 error = got_ref_resolve(&start_id, repo, head_ref);
4473 got_ref_close(head_ref);
4474 if (error != NULL)
4475 goto done;
4476 error = got_object_open_as_commit(&commit, repo,
4477 start_id);
4478 if (error != NULL)
4479 goto done;
4480 got_object_commit_close(commit);
4481 } else {
4482 error = got_repo_match_object_id(&start_id, NULL,
4483 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4484 if (error != NULL)
4485 goto done;
4487 if (end_commit != NULL) {
4488 error = got_repo_match_object_id(&end_id, NULL,
4489 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4490 if (error != NULL)
4491 goto done;
4494 if (worktree) {
4496 * If a path was specified on the command line it was resolved
4497 * to a path in the work tree above. Prepend the work tree's
4498 * path prefix to obtain the corresponding in-repository path.
4500 if (path) {
4501 const char *prefix;
4502 prefix = got_worktree_get_path_prefix(worktree);
4503 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4504 (path[0] != '\0') ? "/" : "", path) == -1) {
4505 error = got_error_from_errno("asprintf");
4506 goto done;
4509 } else
4510 error = got_repo_map_path(&in_repo_path, repo,
4511 path ? path : "");
4512 if (error != NULL)
4513 goto done;
4514 if (in_repo_path) {
4515 free(path);
4516 path = in_repo_path;
4519 if (worktree) {
4520 /* Release work tree lock. */
4521 got_worktree_close(worktree);
4522 worktree = NULL;
4525 if (search_pattern && show_patch) {
4526 tmpfile = got_opentemp();
4527 if (tmpfile == NULL) {
4528 error = got_error_from_errno("got_opentemp");
4529 goto done;
4533 error = print_commits(start_id, end_id, repo, path ? path : "",
4534 show_changed_paths, show_patch, search_pattern, diff_context,
4535 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4536 tmpfile);
4537 done:
4538 free(path);
4539 free(repo_path);
4540 free(cwd);
4541 if (worktree)
4542 got_worktree_close(worktree);
4543 if (repo) {
4544 const struct got_error *close_err = got_repo_close(repo);
4545 if (error == NULL)
4546 error = close_err;
4548 if (pack_fds) {
4549 const struct got_error *pack_err =
4550 got_repo_pack_fds_close(pack_fds);
4551 if (error == NULL)
4552 error = pack_err;
4554 if (refs_idmap)
4555 got_reflist_object_id_map_free(refs_idmap);
4556 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4557 error = got_error_from_errno("fclose");
4558 got_ref_list_free(&refs);
4559 return error;
4562 __dead static void
4563 usage_diff(void)
4565 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4566 "[-r repository-path] [-s] [-w] [-P] "
4567 "[object1 object2 | path ...]\n", getprogname());
4568 exit(1);
4571 struct print_diff_arg {
4572 struct got_repository *repo;
4573 struct got_worktree *worktree;
4574 int diff_context;
4575 const char *id_str;
4576 int header_shown;
4577 int diff_staged;
4578 int ignore_whitespace;
4579 int force_text_diff;
4583 * Create a file which contains the target path of a symlink so we can feed
4584 * it as content to the diff engine.
4586 static const struct got_error *
4587 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4588 const char *abspath)
4590 const struct got_error *err = NULL;
4591 char target_path[PATH_MAX];
4592 ssize_t target_len, outlen;
4594 *fd = -1;
4596 if (dirfd != -1) {
4597 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4598 if (target_len == -1)
4599 return got_error_from_errno2("readlinkat", abspath);
4600 } else {
4601 target_len = readlink(abspath, target_path, PATH_MAX);
4602 if (target_len == -1)
4603 return got_error_from_errno2("readlink", abspath);
4606 *fd = got_opentempfd();
4607 if (*fd == -1)
4608 return got_error_from_errno("got_opentempfd");
4610 outlen = write(*fd, target_path, target_len);
4611 if (outlen == -1) {
4612 err = got_error_from_errno("got_opentempfd");
4613 goto done;
4616 if (lseek(*fd, 0, SEEK_SET) == -1) {
4617 err = got_error_from_errno2("lseek", abspath);
4618 goto done;
4620 done:
4621 if (err) {
4622 close(*fd);
4623 *fd = -1;
4625 return err;
4628 static const struct got_error *
4629 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4630 const char *path, struct got_object_id *blob_id,
4631 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4632 int dirfd, const char *de_name)
4634 struct print_diff_arg *a = arg;
4635 const struct got_error *err = NULL;
4636 struct got_blob_object *blob1 = NULL;
4637 int fd = -1, fd1 = -1;
4638 FILE *f1 = NULL, *f2 = NULL;
4639 char *abspath = NULL, *label1 = NULL;
4640 struct stat sb;
4641 off_t size1 = 0;
4643 if (a->diff_staged) {
4644 if (staged_status != GOT_STATUS_MODIFY &&
4645 staged_status != GOT_STATUS_ADD &&
4646 staged_status != GOT_STATUS_DELETE)
4647 return NULL;
4648 } else {
4649 if (staged_status == GOT_STATUS_DELETE)
4650 return NULL;
4651 if (status == GOT_STATUS_NONEXISTENT)
4652 return got_error_set_errno(ENOENT, path);
4653 if (status != GOT_STATUS_MODIFY &&
4654 status != GOT_STATUS_ADD &&
4655 status != GOT_STATUS_DELETE &&
4656 status != GOT_STATUS_CONFLICT)
4657 return NULL;
4660 if (!a->header_shown) {
4661 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4662 got_worktree_get_root_path(a->worktree));
4663 printf("commit - %s\n", a->id_str);
4664 printf("path + %s%s\n",
4665 got_worktree_get_root_path(a->worktree),
4666 a->diff_staged ? " (staged changes)" : "");
4667 a->header_shown = 1;
4670 if (a->diff_staged) {
4671 const char *label1 = NULL, *label2 = NULL;
4672 switch (staged_status) {
4673 case GOT_STATUS_MODIFY:
4674 label1 = path;
4675 label2 = path;
4676 break;
4677 case GOT_STATUS_ADD:
4678 label2 = path;
4679 break;
4680 case GOT_STATUS_DELETE:
4681 label1 = path;
4682 break;
4683 default:
4684 return got_error(GOT_ERR_FILE_STATUS);
4686 f1 = got_opentemp();
4687 if (f1 == NULL) {
4688 err = got_error_from_errno("got_opentemp");
4689 goto done;
4691 f2 = got_opentemp();
4692 if (f2 == NULL) {
4693 err = got_error_from_errno("got_opentemp");
4694 goto done;
4696 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4697 blob_id, staged_blob_id, label1, label2, a->diff_context,
4698 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4699 goto done;
4702 fd1 = got_opentempfd();
4703 if (fd1 == -1) {
4704 err = got_error_from_errno("got_opentempfd");
4705 goto done;
4708 if (staged_status == GOT_STATUS_ADD ||
4709 staged_status == GOT_STATUS_MODIFY) {
4710 char *id_str;
4711 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4712 8192, fd1);
4713 if (err)
4714 goto done;
4715 err = got_object_id_str(&id_str, staged_blob_id);
4716 if (err)
4717 goto done;
4718 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4719 err = got_error_from_errno("asprintf");
4720 free(id_str);
4721 goto done;
4723 free(id_str);
4724 } else if (status != GOT_STATUS_ADD) {
4725 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4726 fd1);
4727 if (err)
4728 goto done;
4731 if (status != GOT_STATUS_DELETE) {
4732 if (asprintf(&abspath, "%s/%s",
4733 got_worktree_get_root_path(a->worktree), path) == -1) {
4734 err = got_error_from_errno("asprintf");
4735 goto done;
4738 if (dirfd != -1) {
4739 fd = openat(dirfd, de_name,
4740 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4741 if (fd == -1) {
4742 if (!got_err_open_nofollow_on_symlink()) {
4743 err = got_error_from_errno2("openat",
4744 abspath);
4745 goto done;
4747 err = get_symlink_target_file(&fd, dirfd,
4748 de_name, abspath);
4749 if (err)
4750 goto done;
4752 } else {
4753 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4754 if (fd == -1) {
4755 if (!got_err_open_nofollow_on_symlink()) {
4756 err = got_error_from_errno2("open",
4757 abspath);
4758 goto done;
4760 err = get_symlink_target_file(&fd, dirfd,
4761 de_name, abspath);
4762 if (err)
4763 goto done;
4766 if (fstat(fd, &sb) == -1) {
4767 err = got_error_from_errno2("fstat", abspath);
4768 goto done;
4770 f2 = fdopen(fd, "r");
4771 if (f2 == NULL) {
4772 err = got_error_from_errno2("fdopen", abspath);
4773 goto done;
4775 fd = -1;
4776 } else
4777 sb.st_size = 0;
4779 if (blob1) {
4780 f1 = got_opentemp();
4781 if (f1 == NULL) {
4782 err = got_error_from_errno("got_opentemp");
4783 goto done;
4785 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4786 blob1);
4787 if (err)
4788 goto done;
4791 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4792 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4793 stdout);
4794 done:
4795 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4796 err = got_error_from_errno("close");
4797 if (blob1)
4798 got_object_blob_close(blob1);
4799 if (f1 && fclose(f1) == EOF && err == NULL)
4800 err = got_error_from_errno("fclose");
4801 if (f2 && fclose(f2) == EOF && err == NULL)
4802 err = got_error_from_errno("fclose");
4803 if (fd != -1 && close(fd) == -1 && err == NULL)
4804 err = got_error_from_errno("close");
4805 free(abspath);
4806 return err;
4809 static const struct got_error *
4810 cmd_diff(int argc, char *argv[])
4812 const struct got_error *error;
4813 struct got_repository *repo = NULL;
4814 struct got_worktree *worktree = NULL;
4815 char *cwd = NULL, *repo_path = NULL;
4816 const char *commit_args[2] = { NULL, NULL };
4817 int ncommit_args = 0;
4818 struct got_object_id *ids[2] = { NULL, NULL };
4819 char *labels[2] = { NULL, NULL };
4820 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4821 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4822 int force_text_diff = 0, force_path = 0, rflag = 0;
4823 const char *errstr;
4824 struct got_reflist_head refs;
4825 struct got_pathlist_head paths;
4826 struct got_pathlist_entry *pe;
4827 FILE *f1 = NULL, *f2 = NULL;
4828 int *pack_fds = NULL;
4830 TAILQ_INIT(&refs);
4831 TAILQ_INIT(&paths);
4833 #ifndef PROFILE
4834 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4835 NULL) == -1)
4836 err(1, "pledge");
4837 #endif
4839 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4840 switch (ch) {
4841 case 'a':
4842 force_text_diff = 1;
4843 break;
4844 case 'c':
4845 if (ncommit_args >= 2)
4846 errx(1, "too many -c options used");
4847 commit_args[ncommit_args++] = optarg;
4848 break;
4849 case 'C':
4850 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4851 &errstr);
4852 if (errstr != NULL)
4853 errx(1, "number of context lines is %s: %s",
4854 errstr, optarg);
4855 break;
4856 case 'r':
4857 repo_path = realpath(optarg, NULL);
4858 if (repo_path == NULL)
4859 return got_error_from_errno2("realpath",
4860 optarg);
4861 got_path_strip_trailing_slashes(repo_path);
4862 rflag = 1;
4863 break;
4864 case 's':
4865 diff_staged = 1;
4866 break;
4867 case 'w':
4868 ignore_whitespace = 1;
4869 break;
4870 case 'P':
4871 force_path = 1;
4872 break;
4873 default:
4874 usage_diff();
4875 /* NOTREACHED */
4879 argc -= optind;
4880 argv += optind;
4882 cwd = getcwd(NULL, 0);
4883 if (cwd == NULL) {
4884 error = got_error_from_errno("getcwd");
4885 goto done;
4888 error = got_repo_pack_fds_open(&pack_fds);
4889 if (error != NULL)
4890 goto done;
4892 if (repo_path == NULL) {
4893 error = got_worktree_open(&worktree, cwd);
4894 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4895 goto done;
4896 else
4897 error = NULL;
4898 if (worktree) {
4899 repo_path =
4900 strdup(got_worktree_get_repo_path(worktree));
4901 if (repo_path == NULL) {
4902 error = got_error_from_errno("strdup");
4903 goto done;
4905 } else {
4906 repo_path = strdup(cwd);
4907 if (repo_path == NULL) {
4908 error = got_error_from_errno("strdup");
4909 goto done;
4914 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4915 free(repo_path);
4916 if (error != NULL)
4917 goto done;
4919 if (rflag || worktree == NULL || ncommit_args > 0) {
4920 if (force_path) {
4921 error = got_error_msg(GOT_ERR_NOT_IMPL,
4922 "-P option can only be used when diffing "
4923 "a work tree");
4924 goto done;
4926 if (diff_staged) {
4927 error = got_error_msg(GOT_ERR_NOT_IMPL,
4928 "-s option can only be used when diffing "
4929 "a work tree");
4930 goto done;
4934 error = apply_unveil(got_repo_get_path(repo), 1,
4935 worktree ? got_worktree_get_root_path(worktree) : NULL);
4936 if (error)
4937 goto done;
4939 if ((!force_path && argc == 2) || ncommit_args > 0) {
4940 int obj_type = (ncommit_args > 0 ?
4941 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4942 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4943 NULL);
4944 if (error)
4945 goto done;
4946 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4947 const char *arg;
4948 if (ncommit_args > 0)
4949 arg = commit_args[i];
4950 else
4951 arg = argv[i];
4952 error = got_repo_match_object_id(&ids[i], &labels[i],
4953 arg, obj_type, &refs, repo);
4954 if (error) {
4955 if (error->code != GOT_ERR_NOT_REF &&
4956 error->code != GOT_ERR_NO_OBJ)
4957 goto done;
4958 if (ncommit_args > 0)
4959 goto done;
4960 error = NULL;
4961 break;
4966 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4967 struct print_diff_arg arg;
4968 char *id_str;
4970 if (worktree == NULL) {
4971 if (argc == 2 && ids[0] == NULL) {
4972 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4973 goto done;
4974 } else if (argc == 2 && ids[1] == NULL) {
4975 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4976 goto done;
4977 } else if (argc > 0) {
4978 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4979 "%s", "specified paths cannot be resolved");
4980 goto done;
4981 } else {
4982 error = got_error(GOT_ERR_NOT_WORKTREE);
4983 goto done;
4987 error = get_worktree_paths_from_argv(&paths, argc, argv,
4988 worktree);
4989 if (error)
4990 goto done;
4992 error = got_object_id_str(&id_str,
4993 got_worktree_get_base_commit_id(worktree));
4994 if (error)
4995 goto done;
4996 arg.repo = repo;
4997 arg.worktree = worktree;
4998 arg.diff_context = diff_context;
4999 arg.id_str = id_str;
5000 arg.header_shown = 0;
5001 arg.diff_staged = diff_staged;
5002 arg.ignore_whitespace = ignore_whitespace;
5003 arg.force_text_diff = force_text_diff;
5005 error = got_worktree_status(worktree, &paths, repo, 0,
5006 print_diff, &arg, check_cancelled, NULL);
5007 free(id_str);
5008 goto done;
5011 if (ncommit_args == 1) {
5012 struct got_commit_object *commit;
5013 error = got_object_open_as_commit(&commit, repo, ids[0]);
5014 if (error)
5015 goto done;
5017 labels[1] = labels[0];
5018 ids[1] = ids[0];
5019 if (got_object_commit_get_nparents(commit) > 0) {
5020 const struct got_object_id_queue *pids;
5021 struct got_object_qid *pid;
5022 pids = got_object_commit_get_parent_ids(commit);
5023 pid = STAILQ_FIRST(pids);
5024 ids[0] = got_object_id_dup(&pid->id);
5025 if (ids[0] == NULL) {
5026 error = got_error_from_errno(
5027 "got_object_id_dup");
5028 got_object_commit_close(commit);
5029 goto done;
5031 error = got_object_id_str(&labels[0], ids[0]);
5032 if (error) {
5033 got_object_commit_close(commit);
5034 goto done;
5036 } else {
5037 ids[0] = NULL;
5038 labels[0] = strdup("/dev/null");
5039 if (labels[0] == NULL) {
5040 error = got_error_from_errno("strdup");
5041 got_object_commit_close(commit);
5042 goto done;
5046 got_object_commit_close(commit);
5049 if (ncommit_args == 0 && argc > 2) {
5050 error = got_error_msg(GOT_ERR_BAD_PATH,
5051 "path arguments cannot be used when diffing two objects");
5052 goto done;
5055 if (ids[0]) {
5056 error = got_object_get_type(&type1, repo, ids[0]);
5057 if (error)
5058 goto done;
5061 error = got_object_get_type(&type2, repo, ids[1]);
5062 if (error)
5063 goto done;
5064 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5065 error = got_error(GOT_ERR_OBJ_TYPE);
5066 goto done;
5068 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5069 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5070 "path arguments cannot be used when diffing blobs");
5071 goto done;
5074 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5075 char *in_repo_path;
5076 struct got_pathlist_entry *new;
5077 if (worktree) {
5078 const char *prefix;
5079 char *p;
5080 error = got_worktree_resolve_path(&p, worktree,
5081 argv[i]);
5082 if (error)
5083 goto done;
5084 prefix = got_worktree_get_path_prefix(worktree);
5085 while (prefix[0] == '/')
5086 prefix++;
5087 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5088 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5089 p) == -1) {
5090 error = got_error_from_errno("asprintf");
5091 free(p);
5092 goto done;
5094 free(p);
5095 } else {
5096 char *mapped_path, *s;
5097 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5098 if (error)
5099 goto done;
5100 s = mapped_path;
5101 while (s[0] == '/')
5102 s++;
5103 in_repo_path = strdup(s);
5104 if (in_repo_path == NULL) {
5105 error = got_error_from_errno("asprintf");
5106 free(mapped_path);
5107 goto done;
5109 free(mapped_path);
5112 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5113 if (error || new == NULL /* duplicate */)
5114 free(in_repo_path);
5115 if (error)
5116 goto done;
5119 if (worktree) {
5120 /* Release work tree lock. */
5121 got_worktree_close(worktree);
5122 worktree = NULL;
5125 f1 = got_opentemp();
5126 if (f1 == NULL) {
5127 error = got_error_from_errno("got_opentemp");
5128 goto done;
5131 f2 = got_opentemp();
5132 if (f2 == NULL) {
5133 error = got_error_from_errno("got_opentemp");
5134 goto done;
5137 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5138 case GOT_OBJ_TYPE_BLOB:
5139 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5140 ids[0], ids[1], NULL, NULL, diff_context,
5141 ignore_whitespace, force_text_diff, repo, stdout);
5142 break;
5143 case GOT_OBJ_TYPE_TREE:
5144 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5145 ids[0], ids[1], &paths, "", "", diff_context,
5146 ignore_whitespace, force_text_diff, repo, stdout);
5147 break;
5148 case GOT_OBJ_TYPE_COMMIT:
5149 printf("diff %s %s\n", labels[0], labels[1]);
5150 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5151 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5152 force_text_diff, repo, stdout);
5153 break;
5154 default:
5155 error = got_error(GOT_ERR_OBJ_TYPE);
5157 done:
5158 free(labels[0]);
5159 free(labels[1]);
5160 free(ids[0]);
5161 free(ids[1]);
5162 if (worktree)
5163 got_worktree_close(worktree);
5164 if (repo) {
5165 const struct got_error *close_err = got_repo_close(repo);
5166 if (error == NULL)
5167 error = close_err;
5169 if (pack_fds) {
5170 const struct got_error *pack_err =
5171 got_repo_pack_fds_close(pack_fds);
5172 if (error == NULL)
5173 error = pack_err;
5175 TAILQ_FOREACH(pe, &paths, entry)
5176 free((char *)pe->path);
5177 got_pathlist_free(&paths);
5178 got_ref_list_free(&refs);
5179 if (f1 && fclose(f1) == EOF && error == NULL)
5180 error = got_error_from_errno("fclose");
5181 if (f2 && fclose(f2) == EOF && error == NULL)
5182 error = got_error_from_errno("fclose");
5183 return error;
5186 __dead static void
5187 usage_blame(void)
5189 fprintf(stderr,
5190 "usage: %s blame [-c commit] [-r repository-path] path\n",
5191 getprogname());
5192 exit(1);
5195 struct blame_line {
5196 int annotated;
5197 char *id_str;
5198 char *committer;
5199 char datebuf[11]; /* YYYY-MM-DD + NUL */
5202 struct blame_cb_args {
5203 struct blame_line *lines;
5204 int nlines;
5205 int nlines_prec;
5206 int lineno_cur;
5207 off_t *line_offsets;
5208 FILE *f;
5209 struct got_repository *repo;
5212 static const struct got_error *
5213 blame_cb(void *arg, int nlines, int lineno,
5214 struct got_commit_object *commit, struct got_object_id *id)
5216 const struct got_error *err = NULL;
5217 struct blame_cb_args *a = arg;
5218 struct blame_line *bline;
5219 char *line = NULL;
5220 size_t linesize = 0;
5221 off_t offset;
5222 struct tm tm;
5223 time_t committer_time;
5225 if (nlines != a->nlines ||
5226 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5227 return got_error(GOT_ERR_RANGE);
5229 if (sigint_received)
5230 return got_error(GOT_ERR_ITER_COMPLETED);
5232 if (lineno == -1)
5233 return NULL; /* no change in this commit */
5235 /* Annotate this line. */
5236 bline = &a->lines[lineno - 1];
5237 if (bline->annotated)
5238 return NULL;
5239 err = got_object_id_str(&bline->id_str, id);
5240 if (err)
5241 return err;
5243 bline->committer = strdup(got_object_commit_get_committer(commit));
5244 if (bline->committer == NULL) {
5245 err = got_error_from_errno("strdup");
5246 goto done;
5249 committer_time = got_object_commit_get_committer_time(commit);
5250 if (gmtime_r(&committer_time, &tm) == NULL)
5251 return got_error_from_errno("gmtime_r");
5252 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5253 &tm) == 0) {
5254 err = got_error(GOT_ERR_NO_SPACE);
5255 goto done;
5257 bline->annotated = 1;
5259 /* Print lines annotated so far. */
5260 bline = &a->lines[a->lineno_cur - 1];
5261 if (!bline->annotated)
5262 goto done;
5264 offset = a->line_offsets[a->lineno_cur - 1];
5265 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5266 err = got_error_from_errno("fseeko");
5267 goto done;
5270 while (bline->annotated) {
5271 char *smallerthan, *at, *nl, *committer;
5272 size_t len;
5274 if (getline(&line, &linesize, a->f) == -1) {
5275 if (ferror(a->f))
5276 err = got_error_from_errno("getline");
5277 break;
5280 committer = bline->committer;
5281 smallerthan = strchr(committer, '<');
5282 if (smallerthan && smallerthan[1] != '\0')
5283 committer = smallerthan + 1;
5284 at = strchr(committer, '@');
5285 if (at)
5286 *at = '\0';
5287 len = strlen(committer);
5288 if (len >= 9)
5289 committer[8] = '\0';
5291 nl = strchr(line, '\n');
5292 if (nl)
5293 *nl = '\0';
5294 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5295 bline->id_str, bline->datebuf, committer, line);
5297 a->lineno_cur++;
5298 bline = &a->lines[a->lineno_cur - 1];
5300 done:
5301 free(line);
5302 return err;
5305 static const struct got_error *
5306 cmd_blame(int argc, char *argv[])
5308 const struct got_error *error;
5309 struct got_repository *repo = NULL;
5310 struct got_worktree *worktree = NULL;
5311 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5312 char *link_target = NULL;
5313 struct got_object_id *obj_id = NULL;
5314 struct got_object_id *commit_id = NULL;
5315 struct got_commit_object *commit = NULL;
5316 struct got_blob_object *blob = NULL;
5317 char *commit_id_str = NULL;
5318 struct blame_cb_args bca;
5319 int ch, obj_type, i, fd = -1, fd1 = -1;
5320 off_t filesize;
5321 int *pack_fds = NULL;
5323 fd = got_opentempfd();
5324 if (fd == -1)
5325 return got_error_from_errno("got_opentempfd");
5327 memset(&bca, 0, sizeof(bca));
5329 #ifndef PROFILE
5330 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5331 NULL) == -1)
5332 err(1, "pledge");
5333 #endif
5335 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5336 switch (ch) {
5337 case 'c':
5338 commit_id_str = optarg;
5339 break;
5340 case 'r':
5341 repo_path = realpath(optarg, NULL);
5342 if (repo_path == NULL)
5343 return got_error_from_errno2("realpath",
5344 optarg);
5345 got_path_strip_trailing_slashes(repo_path);
5346 break;
5347 default:
5348 usage_blame();
5349 /* NOTREACHED */
5353 argc -= optind;
5354 argv += optind;
5356 if (argc == 1)
5357 path = argv[0];
5358 else
5359 usage_blame();
5361 cwd = getcwd(NULL, 0);
5362 if (cwd == NULL) {
5363 error = got_error_from_errno("getcwd");
5364 goto done;
5367 error = got_repo_pack_fds_open(&pack_fds);
5368 if (error != NULL)
5369 goto done;
5371 if (repo_path == NULL) {
5372 error = got_worktree_open(&worktree, cwd);
5373 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5374 goto done;
5375 else
5376 error = NULL;
5377 if (worktree) {
5378 repo_path =
5379 strdup(got_worktree_get_repo_path(worktree));
5380 if (repo_path == NULL) {
5381 error = got_error_from_errno("strdup");
5382 if (error)
5383 goto done;
5385 } else {
5386 repo_path = strdup(cwd);
5387 if (repo_path == NULL) {
5388 error = got_error_from_errno("strdup");
5389 goto done;
5394 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5395 if (error != NULL)
5396 goto done;
5398 if (worktree) {
5399 const char *prefix = got_worktree_get_path_prefix(worktree);
5400 char *p;
5402 error = got_worktree_resolve_path(&p, worktree, path);
5403 if (error)
5404 goto done;
5405 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5406 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5407 p) == -1) {
5408 error = got_error_from_errno("asprintf");
5409 free(p);
5410 goto done;
5412 free(p);
5413 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5414 } else {
5415 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5416 if (error)
5417 goto done;
5418 error = got_repo_map_path(&in_repo_path, repo, path);
5420 if (error)
5421 goto done;
5423 if (commit_id_str == NULL) {
5424 struct got_reference *head_ref;
5425 error = got_ref_open(&head_ref, repo, worktree ?
5426 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5427 if (error != NULL)
5428 goto done;
5429 error = got_ref_resolve(&commit_id, repo, head_ref);
5430 got_ref_close(head_ref);
5431 if (error != NULL)
5432 goto done;
5433 } else {
5434 struct got_reflist_head refs;
5435 TAILQ_INIT(&refs);
5436 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5437 NULL);
5438 if (error)
5439 goto done;
5440 error = got_repo_match_object_id(&commit_id, NULL,
5441 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5442 got_ref_list_free(&refs);
5443 if (error)
5444 goto done;
5447 if (worktree) {
5448 /* Release work tree lock. */
5449 got_worktree_close(worktree);
5450 worktree = NULL;
5453 error = got_object_open_as_commit(&commit, repo, commit_id);
5454 if (error)
5455 goto done;
5457 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5458 commit, repo);
5459 if (error)
5460 goto done;
5462 error = got_object_id_by_path(&obj_id, repo, commit,
5463 link_target ? link_target : in_repo_path);
5464 if (error)
5465 goto done;
5467 error = got_object_get_type(&obj_type, repo, obj_id);
5468 if (error)
5469 goto done;
5471 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5472 error = got_error_path(link_target ? link_target : in_repo_path,
5473 GOT_ERR_OBJ_TYPE);
5474 goto done;
5477 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd);
5478 if (error)
5479 goto done;
5480 bca.f = got_opentemp();
5481 if (bca.f == NULL) {
5482 error = got_error_from_errno("got_opentemp");
5483 goto done;
5485 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5486 &bca.line_offsets, bca.f, blob);
5487 if (error || bca.nlines == 0)
5488 goto done;
5490 /* Don't include \n at EOF in the blame line count. */
5491 if (bca.line_offsets[bca.nlines - 1] == filesize)
5492 bca.nlines--;
5494 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5495 if (bca.lines == NULL) {
5496 error = got_error_from_errno("calloc");
5497 goto done;
5499 bca.lineno_cur = 1;
5500 bca.nlines_prec = 0;
5501 i = bca.nlines;
5502 while (i > 0) {
5503 i /= 10;
5504 bca.nlines_prec++;
5506 bca.repo = repo;
5508 fd1 = got_opentempfd();
5509 if (fd1 == -1) {
5510 error = got_error_from_errno("got_opentempfd");
5511 goto done;
5513 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5514 repo, blame_cb, &bca, check_cancelled, NULL, fd1);
5515 done:
5516 free(in_repo_path);
5517 free(link_target);
5518 free(repo_path);
5519 free(cwd);
5520 free(commit_id);
5521 free(obj_id);
5522 if (commit)
5523 got_object_commit_close(commit);
5524 if (fd != -1 && close(fd) == -1 && error == NULL)
5525 error = got_error_from_errno("close");
5526 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5527 error = got_error_from_errno("close");
5528 if (blob)
5529 got_object_blob_close(blob);
5530 if (worktree)
5531 got_worktree_close(worktree);
5532 if (repo) {
5533 const struct got_error *close_err = got_repo_close(repo);
5534 if (error == NULL)
5535 error = close_err;
5537 if (pack_fds) {
5538 const struct got_error *pack_err =
5539 got_repo_pack_fds_close(pack_fds);
5540 if (error == NULL)
5541 error = pack_err;
5543 if (bca.lines) {
5544 for (i = 0; i < bca.nlines; i++) {
5545 struct blame_line *bline = &bca.lines[i];
5546 free(bline->id_str);
5547 free(bline->committer);
5549 free(bca.lines);
5551 free(bca.line_offsets);
5552 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5553 error = got_error_from_errno("fclose");
5554 return error;
5557 __dead static void
5558 usage_tree(void)
5560 fprintf(stderr,
5561 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5562 getprogname());
5563 exit(1);
5566 static const struct got_error *
5567 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5568 const char *root_path, struct got_repository *repo)
5570 const struct got_error *err = NULL;
5571 int is_root_path = (strcmp(path, root_path) == 0);
5572 const char *modestr = "";
5573 mode_t mode = got_tree_entry_get_mode(te);
5574 char *link_target = NULL;
5576 path += strlen(root_path);
5577 while (path[0] == '/')
5578 path++;
5580 if (got_object_tree_entry_is_submodule(te))
5581 modestr = "$";
5582 else if (S_ISLNK(mode)) {
5583 int i;
5585 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5586 if (err)
5587 return err;
5588 for (i = 0; i < strlen(link_target); i++) {
5589 if (!isprint((unsigned char)link_target[i]))
5590 link_target[i] = '?';
5593 modestr = "@";
5595 else if (S_ISDIR(mode))
5596 modestr = "/";
5597 else if (mode & S_IXUSR)
5598 modestr = "*";
5600 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5601 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5602 link_target ? " -> ": "", link_target ? link_target : "");
5604 free(link_target);
5605 return NULL;
5608 static const struct got_error *
5609 print_tree(const char *path, struct got_commit_object *commit,
5610 int show_ids, int recurse, const char *root_path,
5611 struct got_repository *repo)
5613 const struct got_error *err = NULL;
5614 struct got_object_id *tree_id = NULL;
5615 struct got_tree_object *tree = NULL;
5616 int nentries, i;
5618 err = got_object_id_by_path(&tree_id, repo, commit, path);
5619 if (err)
5620 goto done;
5622 err = got_object_open_as_tree(&tree, repo, tree_id);
5623 if (err)
5624 goto done;
5625 nentries = got_object_tree_get_nentries(tree);
5626 for (i = 0; i < nentries; i++) {
5627 struct got_tree_entry *te;
5628 char *id = NULL;
5630 if (sigint_received || sigpipe_received)
5631 break;
5633 te = got_object_tree_get_entry(tree, i);
5634 if (show_ids) {
5635 char *id_str;
5636 err = got_object_id_str(&id_str,
5637 got_tree_entry_get_id(te));
5638 if (err)
5639 goto done;
5640 if (asprintf(&id, "%s ", id_str) == -1) {
5641 err = got_error_from_errno("asprintf");
5642 free(id_str);
5643 goto done;
5645 free(id_str);
5647 err = print_entry(te, id, path, root_path, repo);
5648 free(id);
5649 if (err)
5650 goto done;
5652 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5653 char *child_path;
5654 if (asprintf(&child_path, "%s%s%s", path,
5655 path[0] == '/' && path[1] == '\0' ? "" : "/",
5656 got_tree_entry_get_name(te)) == -1) {
5657 err = got_error_from_errno("asprintf");
5658 goto done;
5660 err = print_tree(child_path, commit, show_ids, 1,
5661 root_path, repo);
5662 free(child_path);
5663 if (err)
5664 goto done;
5667 done:
5668 if (tree)
5669 got_object_tree_close(tree);
5670 free(tree_id);
5671 return err;
5674 static const struct got_error *
5675 cmd_tree(int argc, char *argv[])
5677 const struct got_error *error;
5678 struct got_repository *repo = NULL;
5679 struct got_worktree *worktree = NULL;
5680 const char *path, *refname = NULL;
5681 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5682 struct got_object_id *commit_id = NULL;
5683 struct got_commit_object *commit = NULL;
5684 char *commit_id_str = NULL;
5685 int show_ids = 0, recurse = 0;
5686 int ch;
5687 int *pack_fds = NULL;
5689 #ifndef PROFILE
5690 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5691 NULL) == -1)
5692 err(1, "pledge");
5693 #endif
5695 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5696 switch (ch) {
5697 case 'c':
5698 commit_id_str = optarg;
5699 break;
5700 case 'r':
5701 repo_path = realpath(optarg, NULL);
5702 if (repo_path == NULL)
5703 return got_error_from_errno2("realpath",
5704 optarg);
5705 got_path_strip_trailing_slashes(repo_path);
5706 break;
5707 case 'i':
5708 show_ids = 1;
5709 break;
5710 case 'R':
5711 recurse = 1;
5712 break;
5713 default:
5714 usage_tree();
5715 /* NOTREACHED */
5719 argc -= optind;
5720 argv += optind;
5722 if (argc == 1)
5723 path = argv[0];
5724 else if (argc > 1)
5725 usage_tree();
5726 else
5727 path = NULL;
5729 cwd = getcwd(NULL, 0);
5730 if (cwd == NULL) {
5731 error = got_error_from_errno("getcwd");
5732 goto done;
5735 error = got_repo_pack_fds_open(&pack_fds);
5736 if (error != NULL)
5737 goto done;
5739 if (repo_path == NULL) {
5740 error = got_worktree_open(&worktree, cwd);
5741 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5742 goto done;
5743 else
5744 error = NULL;
5745 if (worktree) {
5746 repo_path =
5747 strdup(got_worktree_get_repo_path(worktree));
5748 if (repo_path == NULL)
5749 error = got_error_from_errno("strdup");
5750 if (error)
5751 goto done;
5752 } else {
5753 repo_path = strdup(cwd);
5754 if (repo_path == NULL) {
5755 error = got_error_from_errno("strdup");
5756 goto done;
5761 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5762 if (error != NULL)
5763 goto done;
5765 if (worktree) {
5766 const char *prefix = got_worktree_get_path_prefix(worktree);
5767 char *p;
5769 if (path == NULL)
5770 path = "";
5771 error = got_worktree_resolve_path(&p, worktree, path);
5772 if (error)
5773 goto done;
5774 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5775 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5776 p) == -1) {
5777 error = got_error_from_errno("asprintf");
5778 free(p);
5779 goto done;
5781 free(p);
5782 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5783 if (error)
5784 goto done;
5785 } else {
5786 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5787 if (error)
5788 goto done;
5789 if (path == NULL)
5790 path = "/";
5791 error = got_repo_map_path(&in_repo_path, repo, path);
5792 if (error != NULL)
5793 goto done;
5796 if (commit_id_str == NULL) {
5797 struct got_reference *head_ref;
5798 if (worktree)
5799 refname = got_worktree_get_head_ref_name(worktree);
5800 else
5801 refname = GOT_REF_HEAD;
5802 error = got_ref_open(&head_ref, repo, refname, 0);
5803 if (error != NULL)
5804 goto done;
5805 error = got_ref_resolve(&commit_id, repo, head_ref);
5806 got_ref_close(head_ref);
5807 if (error != NULL)
5808 goto done;
5809 } else {
5810 struct got_reflist_head refs;
5811 TAILQ_INIT(&refs);
5812 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5813 NULL);
5814 if (error)
5815 goto done;
5816 error = got_repo_match_object_id(&commit_id, NULL,
5817 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5818 got_ref_list_free(&refs);
5819 if (error)
5820 goto done;
5823 if (worktree) {
5824 /* Release work tree lock. */
5825 got_worktree_close(worktree);
5826 worktree = NULL;
5829 error = got_object_open_as_commit(&commit, repo, commit_id);
5830 if (error)
5831 goto done;
5833 error = print_tree(in_repo_path, commit, show_ids, recurse,
5834 in_repo_path, repo);
5835 done:
5836 free(in_repo_path);
5837 free(repo_path);
5838 free(cwd);
5839 free(commit_id);
5840 if (commit)
5841 got_object_commit_close(commit);
5842 if (worktree)
5843 got_worktree_close(worktree);
5844 if (repo) {
5845 const struct got_error *close_err = got_repo_close(repo);
5846 if (error == NULL)
5847 error = close_err;
5849 if (pack_fds) {
5850 const struct got_error *pack_err =
5851 got_repo_pack_fds_close(pack_fds);
5852 if (error == NULL)
5853 error = pack_err;
5855 return error;
5858 __dead static void
5859 usage_status(void)
5861 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5862 "[-S status-codes] [path ...]\n", getprogname());
5863 exit(1);
5866 struct got_status_arg {
5867 char *status_codes;
5868 int suppress;
5871 static const struct got_error *
5872 print_status(void *arg, unsigned char status, unsigned char staged_status,
5873 const char *path, struct got_object_id *blob_id,
5874 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5875 int dirfd, const char *de_name)
5877 struct got_status_arg *st = arg;
5879 if (status == staged_status && (status == GOT_STATUS_DELETE))
5880 status = GOT_STATUS_NO_CHANGE;
5881 if (st != NULL && st->status_codes) {
5882 size_t ncodes = strlen(st->status_codes);
5883 int i, j = 0;
5885 for (i = 0; i < ncodes ; i++) {
5886 if (st->suppress) {
5887 if (status == st->status_codes[i] ||
5888 staged_status == st->status_codes[i]) {
5889 j++;
5890 continue;
5892 } else {
5893 if (status == st->status_codes[i] ||
5894 staged_status == st->status_codes[i])
5895 break;
5899 if (st->suppress && j == 0)
5900 goto print;
5902 if (i == ncodes)
5903 return NULL;
5905 print:
5906 printf("%c%c %s\n", status, staged_status, path);
5907 return NULL;
5910 static const struct got_error *
5911 cmd_status(int argc, char *argv[])
5913 const struct got_error *error = NULL;
5914 struct got_repository *repo = NULL;
5915 struct got_worktree *worktree = NULL;
5916 struct got_status_arg st;
5917 char *cwd = NULL;
5918 struct got_pathlist_head paths;
5919 struct got_pathlist_entry *pe;
5920 int ch, i, no_ignores = 0;
5921 int *pack_fds = NULL;
5923 TAILQ_INIT(&paths);
5925 memset(&st, 0, sizeof(st));
5926 st.status_codes = NULL;
5927 st.suppress = 0;
5929 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5930 switch (ch) {
5931 case 'I':
5932 no_ignores = 1;
5933 break;
5934 case 'S':
5935 if (st.status_codes != NULL && st.suppress == 0)
5936 option_conflict('S', 's');
5937 st.suppress = 1;
5938 /* fallthrough */
5939 case 's':
5940 for (i = 0; i < strlen(optarg); i++) {
5941 switch (optarg[i]) {
5942 case GOT_STATUS_MODIFY:
5943 case GOT_STATUS_ADD:
5944 case GOT_STATUS_DELETE:
5945 case GOT_STATUS_CONFLICT:
5946 case GOT_STATUS_MISSING:
5947 case GOT_STATUS_OBSTRUCTED:
5948 case GOT_STATUS_UNVERSIONED:
5949 case GOT_STATUS_MODE_CHANGE:
5950 case GOT_STATUS_NONEXISTENT:
5951 break;
5952 default:
5953 errx(1, "invalid status code '%c'",
5954 optarg[i]);
5957 if (ch == 's' && st.suppress)
5958 option_conflict('s', 'S');
5959 st.status_codes = optarg;
5960 break;
5961 default:
5962 usage_status();
5963 /* NOTREACHED */
5967 argc -= optind;
5968 argv += optind;
5970 #ifndef PROFILE
5971 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5972 NULL) == -1)
5973 err(1, "pledge");
5974 #endif
5975 cwd = getcwd(NULL, 0);
5976 if (cwd == NULL) {
5977 error = got_error_from_errno("getcwd");
5978 goto done;
5981 error = got_repo_pack_fds_open(&pack_fds);
5982 if (error != NULL)
5983 goto done;
5985 error = got_worktree_open(&worktree, cwd);
5986 if (error) {
5987 if (error->code == GOT_ERR_NOT_WORKTREE)
5988 error = wrap_not_worktree_error(error, "status", cwd);
5989 goto done;
5992 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5993 NULL, pack_fds);
5994 if (error != NULL)
5995 goto done;
5997 error = apply_unveil(got_repo_get_path(repo), 1,
5998 got_worktree_get_root_path(worktree));
5999 if (error)
6000 goto done;
6002 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6003 if (error)
6004 goto done;
6006 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6007 print_status, &st, check_cancelled, NULL);
6008 done:
6009 if (pack_fds) {
6010 const struct got_error *pack_err =
6011 got_repo_pack_fds_close(pack_fds);
6012 if (error == NULL)
6013 error = pack_err;
6016 TAILQ_FOREACH(pe, &paths, entry)
6017 free((char *)pe->path);
6018 got_pathlist_free(&paths);
6019 free(cwd);
6020 return error;
6023 __dead static void
6024 usage_ref(void)
6026 fprintf(stderr,
6027 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6028 "[-s reference] [-d] [name]\n",
6029 getprogname());
6030 exit(1);
6033 static const struct got_error *
6034 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6036 static const struct got_error *err = NULL;
6037 struct got_reflist_head refs;
6038 struct got_reflist_entry *re;
6040 TAILQ_INIT(&refs);
6041 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6042 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6043 repo);
6044 if (err)
6045 return err;
6047 TAILQ_FOREACH(re, &refs, entry) {
6048 char *refstr;
6049 refstr = got_ref_to_str(re->ref);
6050 if (refstr == NULL) {
6051 err = got_error_from_errno("got_ref_to_str");
6052 break;
6054 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6055 free(refstr);
6058 got_ref_list_free(&refs);
6059 return err;
6062 static const struct got_error *
6063 delete_ref_by_name(struct got_repository *repo, const char *refname)
6065 const struct got_error *err;
6066 struct got_reference *ref;
6068 err = got_ref_open(&ref, repo, refname, 0);
6069 if (err)
6070 return err;
6072 err = delete_ref(repo, ref);
6073 got_ref_close(ref);
6074 return err;
6077 static const struct got_error *
6078 add_ref(struct got_repository *repo, const char *refname, const char *target)
6080 const struct got_error *err = NULL;
6081 struct got_object_id *id = NULL;
6082 struct got_reference *ref = NULL;
6083 struct got_reflist_head refs;
6086 * Don't let the user create a reference name with a leading '-'.
6087 * While technically a valid reference name, this case is usually
6088 * an unintended typo.
6090 if (refname[0] == '-')
6091 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6093 TAILQ_INIT(&refs);
6094 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6095 if (err)
6096 goto done;
6097 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6098 &refs, repo);
6099 got_ref_list_free(&refs);
6100 if (err)
6101 goto done;
6103 err = got_ref_alloc(&ref, refname, id);
6104 if (err)
6105 goto done;
6107 err = got_ref_write(ref, repo);
6108 done:
6109 if (ref)
6110 got_ref_close(ref);
6111 free(id);
6112 return err;
6115 static const struct got_error *
6116 add_symref(struct got_repository *repo, const char *refname, const char *target)
6118 const struct got_error *err = NULL;
6119 struct got_reference *ref = NULL;
6120 struct got_reference *target_ref = NULL;
6123 * Don't let the user create a reference name with a leading '-'.
6124 * While technically a valid reference name, this case is usually
6125 * an unintended typo.
6127 if (refname[0] == '-')
6128 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6130 err = got_ref_open(&target_ref, repo, target, 0);
6131 if (err)
6132 return err;
6134 err = got_ref_alloc_symref(&ref, refname, target_ref);
6135 if (err)
6136 goto done;
6138 err = got_ref_write(ref, repo);
6139 done:
6140 if (target_ref)
6141 got_ref_close(target_ref);
6142 if (ref)
6143 got_ref_close(ref);
6144 return err;
6147 static const struct got_error *
6148 cmd_ref(int argc, char *argv[])
6150 const struct got_error *error = NULL;
6151 struct got_repository *repo = NULL;
6152 struct got_worktree *worktree = NULL;
6153 char *cwd = NULL, *repo_path = NULL;
6154 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6155 const char *obj_arg = NULL, *symref_target= NULL;
6156 char *refname = NULL;
6157 int *pack_fds = NULL;
6159 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6160 switch (ch) {
6161 case 'c':
6162 obj_arg = optarg;
6163 break;
6164 case 'd':
6165 do_delete = 1;
6166 break;
6167 case 'r':
6168 repo_path = realpath(optarg, NULL);
6169 if (repo_path == NULL)
6170 return got_error_from_errno2("realpath",
6171 optarg);
6172 got_path_strip_trailing_slashes(repo_path);
6173 break;
6174 case 'l':
6175 do_list = 1;
6176 break;
6177 case 's':
6178 symref_target = optarg;
6179 break;
6180 case 't':
6181 sort_by_time = 1;
6182 break;
6183 default:
6184 usage_ref();
6185 /* NOTREACHED */
6189 if (obj_arg && do_list)
6190 option_conflict('c', 'l');
6191 if (obj_arg && do_delete)
6192 option_conflict('c', 'd');
6193 if (obj_arg && symref_target)
6194 option_conflict('c', 's');
6195 if (symref_target && do_delete)
6196 option_conflict('s', 'd');
6197 if (symref_target && do_list)
6198 option_conflict('s', 'l');
6199 if (do_delete && do_list)
6200 option_conflict('d', 'l');
6201 if (sort_by_time && !do_list)
6202 errx(1, "-t option requires -l option");
6204 argc -= optind;
6205 argv += optind;
6207 if (do_list) {
6208 if (argc != 0 && argc != 1)
6209 usage_ref();
6210 if (argc == 1) {
6211 refname = strdup(argv[0]);
6212 if (refname == NULL) {
6213 error = got_error_from_errno("strdup");
6214 goto done;
6217 } else {
6218 if (argc != 1)
6219 usage_ref();
6220 refname = strdup(argv[0]);
6221 if (refname == NULL) {
6222 error = got_error_from_errno("strdup");
6223 goto done;
6227 if (refname)
6228 got_path_strip_trailing_slashes(refname);
6230 #ifndef PROFILE
6231 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6232 "sendfd unveil", NULL) == -1)
6233 err(1, "pledge");
6234 #endif
6235 cwd = getcwd(NULL, 0);
6236 if (cwd == NULL) {
6237 error = got_error_from_errno("getcwd");
6238 goto done;
6241 error = got_repo_pack_fds_open(&pack_fds);
6242 if (error != NULL)
6243 goto done;
6245 if (repo_path == NULL) {
6246 error = got_worktree_open(&worktree, cwd);
6247 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6248 goto done;
6249 else
6250 error = NULL;
6251 if (worktree) {
6252 repo_path =
6253 strdup(got_worktree_get_repo_path(worktree));
6254 if (repo_path == NULL)
6255 error = got_error_from_errno("strdup");
6256 if (error)
6257 goto done;
6258 } else {
6259 repo_path = strdup(cwd);
6260 if (repo_path == NULL) {
6261 error = got_error_from_errno("strdup");
6262 goto done;
6267 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6268 if (error != NULL)
6269 goto done;
6271 #ifndef PROFILE
6272 if (do_list) {
6273 /* Remove "cpath" promise. */
6274 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6275 NULL) == -1)
6276 err(1, "pledge");
6278 #endif
6280 error = apply_unveil(got_repo_get_path(repo), do_list,
6281 worktree ? got_worktree_get_root_path(worktree) : NULL);
6282 if (error)
6283 goto done;
6285 if (do_list)
6286 error = list_refs(repo, refname, sort_by_time);
6287 else if (do_delete)
6288 error = delete_ref_by_name(repo, refname);
6289 else if (symref_target)
6290 error = add_symref(repo, refname, symref_target);
6291 else {
6292 if (obj_arg == NULL)
6293 usage_ref();
6294 error = add_ref(repo, refname, obj_arg);
6296 done:
6297 free(refname);
6298 if (repo) {
6299 const struct got_error *close_err = got_repo_close(repo);
6300 if (error == NULL)
6301 error = close_err;
6303 if (worktree)
6304 got_worktree_close(worktree);
6305 if (pack_fds) {
6306 const struct got_error *pack_err =
6307 got_repo_pack_fds_close(pack_fds);
6308 if (error == NULL)
6309 error = pack_err;
6311 free(cwd);
6312 free(repo_path);
6313 return error;
6316 __dead static void
6317 usage_branch(void)
6319 fprintf(stderr,
6320 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6321 "[-n] [name]\n", getprogname());
6322 exit(1);
6325 static const struct got_error *
6326 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6327 struct got_reference *ref)
6329 const struct got_error *err = NULL;
6330 const char *refname, *marker = " ";
6331 char *refstr;
6333 refname = got_ref_get_name(ref);
6334 if (worktree && strcmp(refname,
6335 got_worktree_get_head_ref_name(worktree)) == 0) {
6336 struct got_object_id *id = NULL;
6338 err = got_ref_resolve(&id, repo, ref);
6339 if (err)
6340 return err;
6341 if (got_object_id_cmp(id,
6342 got_worktree_get_base_commit_id(worktree)) == 0)
6343 marker = "* ";
6344 else
6345 marker = "~ ";
6346 free(id);
6349 if (strncmp(refname, "refs/heads/", 11) == 0)
6350 refname += 11;
6351 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6352 refname += 18;
6353 if (strncmp(refname, "refs/remotes/", 13) == 0)
6354 refname += 13;
6356 refstr = got_ref_to_str(ref);
6357 if (refstr == NULL)
6358 return got_error_from_errno("got_ref_to_str");
6360 printf("%s%s: %s\n", marker, refname, refstr);
6361 free(refstr);
6362 return NULL;
6365 static const struct got_error *
6366 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6368 const char *refname;
6370 if (worktree == NULL)
6371 return got_error(GOT_ERR_NOT_WORKTREE);
6373 refname = got_worktree_get_head_ref_name(worktree);
6375 if (strncmp(refname, "refs/heads/", 11) == 0)
6376 refname += 11;
6377 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6378 refname += 18;
6380 printf("%s\n", refname);
6382 return NULL;
6385 static const struct got_error *
6386 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6387 int sort_by_time)
6389 static const struct got_error *err = NULL;
6390 struct got_reflist_head refs;
6391 struct got_reflist_entry *re;
6392 struct got_reference *temp_ref = NULL;
6393 int rebase_in_progress, histedit_in_progress;
6395 TAILQ_INIT(&refs);
6397 if (worktree) {
6398 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6399 worktree);
6400 if (err)
6401 return err;
6403 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6404 worktree);
6405 if (err)
6406 return err;
6408 if (rebase_in_progress || histedit_in_progress) {
6409 err = got_ref_open(&temp_ref, repo,
6410 got_worktree_get_head_ref_name(worktree), 0);
6411 if (err)
6412 return err;
6413 list_branch(repo, worktree, temp_ref);
6414 got_ref_close(temp_ref);
6418 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6419 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6420 repo);
6421 if (err)
6422 return err;
6424 TAILQ_FOREACH(re, &refs, entry)
6425 list_branch(repo, worktree, re->ref);
6427 got_ref_list_free(&refs);
6429 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6430 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6431 repo);
6432 if (err)
6433 return err;
6435 TAILQ_FOREACH(re, &refs, entry)
6436 list_branch(repo, worktree, re->ref);
6438 got_ref_list_free(&refs);
6440 return NULL;
6443 static const struct got_error *
6444 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6445 const char *branch_name)
6447 const struct got_error *err = NULL;
6448 struct got_reference *ref = NULL;
6449 char *refname, *remote_refname = NULL;
6451 if (strncmp(branch_name, "refs/", 5) == 0)
6452 branch_name += 5;
6453 if (strncmp(branch_name, "heads/", 6) == 0)
6454 branch_name += 6;
6455 else if (strncmp(branch_name, "remotes/", 8) == 0)
6456 branch_name += 8;
6458 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6459 return got_error_from_errno("asprintf");
6461 if (asprintf(&remote_refname, "refs/remotes/%s",
6462 branch_name) == -1) {
6463 err = got_error_from_errno("asprintf");
6464 goto done;
6467 err = got_ref_open(&ref, repo, refname, 0);
6468 if (err) {
6469 const struct got_error *err2;
6470 if (err->code != GOT_ERR_NOT_REF)
6471 goto done;
6473 * Keep 'err' intact such that if neither branch exists
6474 * we report "refs/heads" rather than "refs/remotes" in
6475 * our error message.
6477 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6478 if (err2)
6479 goto done;
6480 err = NULL;
6483 if (worktree &&
6484 strcmp(got_worktree_get_head_ref_name(worktree),
6485 got_ref_get_name(ref)) == 0) {
6486 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6487 "will not delete this work tree's current branch");
6488 goto done;
6491 err = delete_ref(repo, ref);
6492 done:
6493 if (ref)
6494 got_ref_close(ref);
6495 free(refname);
6496 free(remote_refname);
6497 return err;
6500 static const struct got_error *
6501 add_branch(struct got_repository *repo, const char *branch_name,
6502 struct got_object_id *base_commit_id)
6504 const struct got_error *err = NULL;
6505 struct got_reference *ref = NULL;
6506 char *base_refname = NULL, *refname = NULL;
6509 * Don't let the user create a branch name with a leading '-'.
6510 * While technically a valid reference name, this case is usually
6511 * an unintended typo.
6513 if (branch_name[0] == '-')
6514 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6516 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6517 branch_name += 11;
6519 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6520 err = got_error_from_errno("asprintf");
6521 goto done;
6524 err = got_ref_open(&ref, repo, refname, 0);
6525 if (err == NULL) {
6526 err = got_error(GOT_ERR_BRANCH_EXISTS);
6527 goto done;
6528 } else if (err->code != GOT_ERR_NOT_REF)
6529 goto done;
6531 err = got_ref_alloc(&ref, refname, base_commit_id);
6532 if (err)
6533 goto done;
6535 err = got_ref_write(ref, repo);
6536 done:
6537 if (ref)
6538 got_ref_close(ref);
6539 free(base_refname);
6540 free(refname);
6541 return err;
6544 static const struct got_error *
6545 cmd_branch(int argc, char *argv[])
6547 const struct got_error *error = NULL;
6548 struct got_repository *repo = NULL;
6549 struct got_worktree *worktree = NULL;
6550 char *cwd = NULL, *repo_path = NULL;
6551 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6552 const char *delref = NULL, *commit_id_arg = NULL;
6553 struct got_reference *ref = NULL;
6554 struct got_pathlist_head paths;
6555 struct got_pathlist_entry *pe;
6556 struct got_object_id *commit_id = NULL;
6557 char *commit_id_str = NULL;
6558 int *pack_fds = NULL;
6560 TAILQ_INIT(&paths);
6562 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6563 switch (ch) {
6564 case 'c':
6565 commit_id_arg = optarg;
6566 break;
6567 case 'd':
6568 delref = optarg;
6569 break;
6570 case 'r':
6571 repo_path = realpath(optarg, NULL);
6572 if (repo_path == NULL)
6573 return got_error_from_errno2("realpath",
6574 optarg);
6575 got_path_strip_trailing_slashes(repo_path);
6576 break;
6577 case 'l':
6578 do_list = 1;
6579 break;
6580 case 'n':
6581 do_update = 0;
6582 break;
6583 case 't':
6584 sort_by_time = 1;
6585 break;
6586 default:
6587 usage_branch();
6588 /* NOTREACHED */
6592 if (do_list && delref)
6593 option_conflict('l', 'd');
6594 if (sort_by_time && !do_list)
6595 errx(1, "-t option requires -l option");
6597 argc -= optind;
6598 argv += optind;
6600 if (!do_list && !delref && argc == 0)
6601 do_show = 1;
6603 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6604 errx(1, "-c option can only be used when creating a branch");
6606 if (do_list || delref) {
6607 if (argc > 0)
6608 usage_branch();
6609 } else if (!do_show && argc != 1)
6610 usage_branch();
6612 #ifndef PROFILE
6613 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6614 "sendfd unveil", NULL) == -1)
6615 err(1, "pledge");
6616 #endif
6617 cwd = getcwd(NULL, 0);
6618 if (cwd == NULL) {
6619 error = got_error_from_errno("getcwd");
6620 goto done;
6623 error = got_repo_pack_fds_open(&pack_fds);
6624 if (error != NULL)
6625 goto done;
6627 if (repo_path == NULL) {
6628 error = got_worktree_open(&worktree, cwd);
6629 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6630 goto done;
6631 else
6632 error = NULL;
6633 if (worktree) {
6634 repo_path =
6635 strdup(got_worktree_get_repo_path(worktree));
6636 if (repo_path == NULL)
6637 error = got_error_from_errno("strdup");
6638 if (error)
6639 goto done;
6640 } else {
6641 repo_path = strdup(cwd);
6642 if (repo_path == NULL) {
6643 error = got_error_from_errno("strdup");
6644 goto done;
6649 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6650 if (error != NULL)
6651 goto done;
6653 #ifndef PROFILE
6654 if (do_list || do_show) {
6655 /* Remove "cpath" promise. */
6656 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6657 NULL) == -1)
6658 err(1, "pledge");
6660 #endif
6662 error = apply_unveil(got_repo_get_path(repo), do_list,
6663 worktree ? got_worktree_get_root_path(worktree) : NULL);
6664 if (error)
6665 goto done;
6667 if (do_show)
6668 error = show_current_branch(repo, worktree);
6669 else if (do_list)
6670 error = list_branches(repo, worktree, sort_by_time);
6671 else if (delref)
6672 error = delete_branch(repo, worktree, delref);
6673 else {
6674 struct got_reflist_head refs;
6675 TAILQ_INIT(&refs);
6676 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6677 NULL);
6678 if (error)
6679 goto done;
6680 if (commit_id_arg == NULL)
6681 commit_id_arg = worktree ?
6682 got_worktree_get_head_ref_name(worktree) :
6683 GOT_REF_HEAD;
6684 error = got_repo_match_object_id(&commit_id, NULL,
6685 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6686 got_ref_list_free(&refs);
6687 if (error)
6688 goto done;
6689 error = add_branch(repo, argv[0], commit_id);
6690 if (error)
6691 goto done;
6692 if (worktree && do_update) {
6693 struct got_update_progress_arg upa;
6694 char *branch_refname = NULL;
6696 error = got_object_id_str(&commit_id_str, commit_id);
6697 if (error)
6698 goto done;
6699 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6700 worktree);
6701 if (error)
6702 goto done;
6703 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6704 == -1) {
6705 error = got_error_from_errno("asprintf");
6706 goto done;
6708 error = got_ref_open(&ref, repo, branch_refname, 0);
6709 free(branch_refname);
6710 if (error)
6711 goto done;
6712 error = switch_head_ref(ref, commit_id, worktree,
6713 repo);
6714 if (error)
6715 goto done;
6716 error = got_worktree_set_base_commit_id(worktree, repo,
6717 commit_id);
6718 if (error)
6719 goto done;
6720 memset(&upa, 0, sizeof(upa));
6721 error = got_worktree_checkout_files(worktree, &paths,
6722 repo, update_progress, &upa, check_cancelled,
6723 NULL);
6724 if (error)
6725 goto done;
6726 if (upa.did_something) {
6727 printf("Updated to %s: %s\n",
6728 got_worktree_get_head_ref_name(worktree),
6729 commit_id_str);
6731 print_update_progress_stats(&upa);
6734 done:
6735 if (ref)
6736 got_ref_close(ref);
6737 if (repo) {
6738 const struct got_error *close_err = got_repo_close(repo);
6739 if (error == NULL)
6740 error = close_err;
6742 if (worktree)
6743 got_worktree_close(worktree);
6744 if (pack_fds) {
6745 const struct got_error *pack_err =
6746 got_repo_pack_fds_close(pack_fds);
6747 if (error == NULL)
6748 error = pack_err;
6750 free(cwd);
6751 free(repo_path);
6752 free(commit_id);
6753 free(commit_id_str);
6754 TAILQ_FOREACH(pe, &paths, entry)
6755 free((char *)pe->path);
6756 got_pathlist_free(&paths);
6757 return error;
6761 __dead static void
6762 usage_tag(void)
6764 fprintf(stderr,
6765 "usage: %s tag [-c commit] [-r repository] [-l] "
6766 "[-m message] name\n", getprogname());
6767 exit(1);
6770 #if 0
6771 static const struct got_error *
6772 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6774 const struct got_error *err = NULL;
6775 struct got_reflist_entry *re, *se, *new;
6776 struct got_object_id *re_id, *se_id;
6777 struct got_tag_object *re_tag, *se_tag;
6778 time_t re_time, se_time;
6780 STAILQ_FOREACH(re, tags, entry) {
6781 se = STAILQ_FIRST(sorted);
6782 if (se == NULL) {
6783 err = got_reflist_entry_dup(&new, re);
6784 if (err)
6785 return err;
6786 STAILQ_INSERT_HEAD(sorted, new, entry);
6787 continue;
6788 } else {
6789 err = got_ref_resolve(&re_id, repo, re->ref);
6790 if (err)
6791 break;
6792 err = got_object_open_as_tag(&re_tag, repo, re_id);
6793 free(re_id);
6794 if (err)
6795 break;
6796 re_time = got_object_tag_get_tagger_time(re_tag);
6797 got_object_tag_close(re_tag);
6800 while (se) {
6801 err = got_ref_resolve(&se_id, repo, re->ref);
6802 if (err)
6803 break;
6804 err = got_object_open_as_tag(&se_tag, repo, se_id);
6805 free(se_id);
6806 if (err)
6807 break;
6808 se_time = got_object_tag_get_tagger_time(se_tag);
6809 got_object_tag_close(se_tag);
6811 if (se_time > re_time) {
6812 err = got_reflist_entry_dup(&new, re);
6813 if (err)
6814 return err;
6815 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6816 break;
6818 se = STAILQ_NEXT(se, entry);
6819 continue;
6822 done:
6823 return err;
6825 #endif
6827 static const struct got_error *
6828 list_tags(struct got_repository *repo)
6830 static const struct got_error *err = NULL;
6831 struct got_reflist_head refs;
6832 struct got_reflist_entry *re;
6834 TAILQ_INIT(&refs);
6836 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6837 if (err)
6838 return err;
6840 TAILQ_FOREACH(re, &refs, entry) {
6841 const char *refname;
6842 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6843 char datebuf[26];
6844 const char *tagger;
6845 time_t tagger_time;
6846 struct got_object_id *id;
6847 struct got_tag_object *tag;
6848 struct got_commit_object *commit = NULL;
6850 refname = got_ref_get_name(re->ref);
6851 if (strncmp(refname, "refs/tags/", 10) != 0)
6852 continue;
6853 refname += 10;
6854 refstr = got_ref_to_str(re->ref);
6855 if (refstr == NULL) {
6856 err = got_error_from_errno("got_ref_to_str");
6857 break;
6859 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6860 free(refstr);
6862 err = got_ref_resolve(&id, repo, re->ref);
6863 if (err)
6864 break;
6865 err = got_object_open_as_tag(&tag, repo, id);
6866 if (err) {
6867 if (err->code != GOT_ERR_OBJ_TYPE) {
6868 free(id);
6869 break;
6871 /* "lightweight" tag */
6872 err = got_object_open_as_commit(&commit, repo, id);
6873 if (err) {
6874 free(id);
6875 break;
6877 tagger = got_object_commit_get_committer(commit);
6878 tagger_time =
6879 got_object_commit_get_committer_time(commit);
6880 err = got_object_id_str(&id_str, id);
6881 free(id);
6882 if (err)
6883 break;
6884 } else {
6885 free(id);
6886 tagger = got_object_tag_get_tagger(tag);
6887 tagger_time = got_object_tag_get_tagger_time(tag);
6888 err = got_object_id_str(&id_str,
6889 got_object_tag_get_object_id(tag));
6890 if (err)
6891 break;
6893 printf("from: %s\n", tagger);
6894 datestr = get_datestr(&tagger_time, datebuf);
6895 if (datestr)
6896 printf("date: %s UTC\n", datestr);
6897 if (commit)
6898 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6899 else {
6900 switch (got_object_tag_get_object_type(tag)) {
6901 case GOT_OBJ_TYPE_BLOB:
6902 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6903 id_str);
6904 break;
6905 case GOT_OBJ_TYPE_TREE:
6906 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6907 id_str);
6908 break;
6909 case GOT_OBJ_TYPE_COMMIT:
6910 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6911 id_str);
6912 break;
6913 case GOT_OBJ_TYPE_TAG:
6914 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6915 id_str);
6916 break;
6917 default:
6918 break;
6921 free(id_str);
6922 if (commit) {
6923 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6924 if (err)
6925 break;
6926 got_object_commit_close(commit);
6927 } else {
6928 tagmsg0 = strdup(got_object_tag_get_message(tag));
6929 got_object_tag_close(tag);
6930 if (tagmsg0 == NULL) {
6931 err = got_error_from_errno("strdup");
6932 break;
6936 tagmsg = tagmsg0;
6937 do {
6938 line = strsep(&tagmsg, "\n");
6939 if (line)
6940 printf(" %s\n", line);
6941 } while (line);
6942 free(tagmsg0);
6945 got_ref_list_free(&refs);
6946 return NULL;
6949 static const struct got_error *
6950 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6951 const char *tag_name, const char *repo_path)
6953 const struct got_error *err = NULL;
6954 char *template = NULL, *initial_content = NULL;
6955 char *editor = NULL;
6956 int initial_content_len;
6957 int fd = -1;
6959 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6960 err = got_error_from_errno("asprintf");
6961 goto done;
6964 initial_content_len = asprintf(&initial_content,
6965 "\n# tagging commit %s as %s\n",
6966 commit_id_str, tag_name);
6967 if (initial_content_len == -1) {
6968 err = got_error_from_errno("asprintf");
6969 goto done;
6972 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6973 if (err)
6974 goto done;
6976 if (write(fd, initial_content, initial_content_len) == -1) {
6977 err = got_error_from_errno2("write", *tagmsg_path);
6978 goto done;
6981 err = get_editor(&editor);
6982 if (err)
6983 goto done;
6984 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6985 initial_content_len, 1);
6986 done:
6987 free(initial_content);
6988 free(template);
6989 free(editor);
6991 if (fd != -1 && close(fd) == -1 && err == NULL)
6992 err = got_error_from_errno2("close", *tagmsg_path);
6994 /* Editor is done; we can now apply unveil(2) */
6995 if (err == NULL)
6996 err = apply_unveil(repo_path, 0, NULL);
6997 if (err) {
6998 free(*tagmsg);
6999 *tagmsg = NULL;
7001 return err;
7004 static const struct got_error *
7005 add_tag(struct got_repository *repo, const char *tagger,
7006 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
7008 const struct got_error *err = NULL;
7009 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7010 char *label = NULL, *commit_id_str = NULL;
7011 struct got_reference *ref = NULL;
7012 char *refname = NULL, *tagmsg = NULL;
7013 char *tagmsg_path = NULL, *tag_id_str = NULL;
7014 int preserve_tagmsg = 0;
7015 struct got_reflist_head refs;
7017 TAILQ_INIT(&refs);
7020 * Don't let the user create a tag name with a leading '-'.
7021 * While technically a valid reference name, this case is usually
7022 * an unintended typo.
7024 if (tag_name[0] == '-')
7025 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7027 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7028 if (err)
7029 goto done;
7031 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7032 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7033 if (err)
7034 goto done;
7036 err = got_object_id_str(&commit_id_str, commit_id);
7037 if (err)
7038 goto done;
7040 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7041 refname = strdup(tag_name);
7042 if (refname == NULL) {
7043 err = got_error_from_errno("strdup");
7044 goto done;
7046 tag_name += 10;
7047 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
7048 err = got_error_from_errno("asprintf");
7049 goto done;
7052 err = got_ref_open(&ref, repo, refname, 0);
7053 if (err == NULL) {
7054 err = got_error(GOT_ERR_TAG_EXISTS);
7055 goto done;
7056 } else if (err->code != GOT_ERR_NOT_REF)
7057 goto done;
7059 if (tagmsg_arg == NULL) {
7060 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7061 tag_name, got_repo_get_path(repo));
7062 if (err) {
7063 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7064 tagmsg_path != NULL)
7065 preserve_tagmsg = 1;
7066 goto done;
7070 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7071 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7072 if (err) {
7073 if (tagmsg_path)
7074 preserve_tagmsg = 1;
7075 goto done;
7078 err = got_ref_alloc(&ref, refname, tag_id);
7079 if (err) {
7080 if (tagmsg_path)
7081 preserve_tagmsg = 1;
7082 goto done;
7085 err = got_ref_write(ref, repo);
7086 if (err) {
7087 if (tagmsg_path)
7088 preserve_tagmsg = 1;
7089 goto done;
7092 err = got_object_id_str(&tag_id_str, tag_id);
7093 if (err) {
7094 if (tagmsg_path)
7095 preserve_tagmsg = 1;
7096 goto done;
7098 printf("Created tag %s\n", tag_id_str);
7099 done:
7100 if (preserve_tagmsg) {
7101 fprintf(stderr, "%s: tag message preserved in %s\n",
7102 getprogname(), tagmsg_path);
7103 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7104 err = got_error_from_errno2("unlink", tagmsg_path);
7105 free(tag_id_str);
7106 if (ref)
7107 got_ref_close(ref);
7108 free(commit_id);
7109 free(commit_id_str);
7110 free(refname);
7111 free(tagmsg);
7112 free(tagmsg_path);
7113 got_ref_list_free(&refs);
7114 return err;
7117 static const struct got_error *
7118 cmd_tag(int argc, char *argv[])
7120 const struct got_error *error = NULL;
7121 struct got_repository *repo = NULL;
7122 struct got_worktree *worktree = NULL;
7123 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7124 char *gitconfig_path = NULL, *tagger = NULL;
7125 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
7126 int ch, do_list = 0;
7127 int *pack_fds = NULL;
7129 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7130 switch (ch) {
7131 case 'c':
7132 commit_id_arg = optarg;
7133 break;
7134 case 'm':
7135 tagmsg = optarg;
7136 break;
7137 case 'r':
7138 repo_path = realpath(optarg, NULL);
7139 if (repo_path == NULL)
7140 return got_error_from_errno2("realpath",
7141 optarg);
7142 got_path_strip_trailing_slashes(repo_path);
7143 break;
7144 case 'l':
7145 do_list = 1;
7146 break;
7147 default:
7148 usage_tag();
7149 /* NOTREACHED */
7153 argc -= optind;
7154 argv += optind;
7156 if (do_list) {
7157 if (commit_id_arg != NULL)
7158 errx(1,
7159 "-c option can only be used when creating a tag");
7160 if (tagmsg)
7161 option_conflict('l', 'm');
7162 if (argc > 0)
7163 usage_tag();
7164 } else if (argc != 1)
7165 usage_tag();
7167 tag_name = argv[0];
7169 #ifndef PROFILE
7170 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7171 "sendfd unveil", NULL) == -1)
7172 err(1, "pledge");
7173 #endif
7174 cwd = getcwd(NULL, 0);
7175 if (cwd == NULL) {
7176 error = got_error_from_errno("getcwd");
7177 goto done;
7180 error = got_repo_pack_fds_open(&pack_fds);
7181 if (error != NULL)
7182 goto done;
7184 if (repo_path == NULL) {
7185 error = got_worktree_open(&worktree, cwd);
7186 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7187 goto done;
7188 else
7189 error = NULL;
7190 if (worktree) {
7191 repo_path =
7192 strdup(got_worktree_get_repo_path(worktree));
7193 if (repo_path == NULL)
7194 error = got_error_from_errno("strdup");
7195 if (error)
7196 goto done;
7197 } else {
7198 repo_path = strdup(cwd);
7199 if (repo_path == NULL) {
7200 error = got_error_from_errno("strdup");
7201 goto done;
7206 if (do_list) {
7207 if (worktree) {
7208 /* Release work tree lock. */
7209 got_worktree_close(worktree);
7210 worktree = NULL;
7212 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7213 if (error != NULL)
7214 goto done;
7216 #ifndef PROFILE
7217 /* Remove "cpath" promise. */
7218 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7219 NULL) == -1)
7220 err(1, "pledge");
7221 #endif
7222 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7223 if (error)
7224 goto done;
7225 error = list_tags(repo);
7226 } else {
7227 error = get_gitconfig_path(&gitconfig_path);
7228 if (error)
7229 goto done;
7230 error = got_repo_open(&repo, repo_path, gitconfig_path,
7231 pack_fds);
7232 if (error != NULL)
7233 goto done;
7235 error = get_author(&tagger, repo, worktree);
7236 if (error)
7237 goto done;
7238 if (worktree) {
7239 /* Release work tree lock. */
7240 got_worktree_close(worktree);
7241 worktree = NULL;
7244 if (tagmsg) {
7245 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7246 if (error)
7247 goto done;
7250 if (commit_id_arg == NULL) {
7251 struct got_reference *head_ref;
7252 struct got_object_id *commit_id;
7253 error = got_ref_open(&head_ref, repo,
7254 worktree ? got_worktree_get_head_ref_name(worktree)
7255 : GOT_REF_HEAD, 0);
7256 if (error)
7257 goto done;
7258 error = got_ref_resolve(&commit_id, repo, head_ref);
7259 got_ref_close(head_ref);
7260 if (error)
7261 goto done;
7262 error = got_object_id_str(&commit_id_str, commit_id);
7263 free(commit_id);
7264 if (error)
7265 goto done;
7268 error = add_tag(repo, tagger, tag_name,
7269 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7271 done:
7272 if (repo) {
7273 const struct got_error *close_err = got_repo_close(repo);
7274 if (error == NULL)
7275 error = close_err;
7277 if (worktree)
7278 got_worktree_close(worktree);
7279 if (pack_fds) {
7280 const struct got_error *pack_err =
7281 got_repo_pack_fds_close(pack_fds);
7282 if (error == NULL)
7283 error = pack_err;
7285 free(cwd);
7286 free(repo_path);
7287 free(gitconfig_path);
7288 free(commit_id_str);
7289 free(tagger);
7290 return error;
7293 __dead static void
7294 usage_add(void)
7296 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7297 getprogname());
7298 exit(1);
7301 static const struct got_error *
7302 add_progress(void *arg, unsigned char status, const char *path)
7304 while (path[0] == '/')
7305 path++;
7306 printf("%c %s\n", status, path);
7307 return NULL;
7310 static const struct got_error *
7311 cmd_add(int argc, char *argv[])
7313 const struct got_error *error = NULL;
7314 struct got_repository *repo = NULL;
7315 struct got_worktree *worktree = NULL;
7316 char *cwd = NULL;
7317 struct got_pathlist_head paths;
7318 struct got_pathlist_entry *pe;
7319 int ch, can_recurse = 0, no_ignores = 0;
7320 int *pack_fds = NULL;
7322 TAILQ_INIT(&paths);
7324 while ((ch = getopt(argc, argv, "IR")) != -1) {
7325 switch (ch) {
7326 case 'I':
7327 no_ignores = 1;
7328 break;
7329 case 'R':
7330 can_recurse = 1;
7331 break;
7332 default:
7333 usage_add();
7334 /* NOTREACHED */
7338 argc -= optind;
7339 argv += optind;
7341 #ifndef PROFILE
7342 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7343 NULL) == -1)
7344 err(1, "pledge");
7345 #endif
7346 if (argc < 1)
7347 usage_add();
7349 cwd = getcwd(NULL, 0);
7350 if (cwd == NULL) {
7351 error = got_error_from_errno("getcwd");
7352 goto done;
7355 error = got_repo_pack_fds_open(&pack_fds);
7356 if (error != NULL)
7357 goto done;
7359 error = got_worktree_open(&worktree, cwd);
7360 if (error) {
7361 if (error->code == GOT_ERR_NOT_WORKTREE)
7362 error = wrap_not_worktree_error(error, "add", cwd);
7363 goto done;
7366 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7367 NULL, pack_fds);
7368 if (error != NULL)
7369 goto done;
7371 error = apply_unveil(got_repo_get_path(repo), 1,
7372 got_worktree_get_root_path(worktree));
7373 if (error)
7374 goto done;
7376 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7377 if (error)
7378 goto done;
7380 if (!can_recurse) {
7381 char *ondisk_path;
7382 struct stat sb;
7383 TAILQ_FOREACH(pe, &paths, entry) {
7384 if (asprintf(&ondisk_path, "%s/%s",
7385 got_worktree_get_root_path(worktree),
7386 pe->path) == -1) {
7387 error = got_error_from_errno("asprintf");
7388 goto done;
7390 if (lstat(ondisk_path, &sb) == -1) {
7391 if (errno == ENOENT) {
7392 free(ondisk_path);
7393 continue;
7395 error = got_error_from_errno2("lstat",
7396 ondisk_path);
7397 free(ondisk_path);
7398 goto done;
7400 free(ondisk_path);
7401 if (S_ISDIR(sb.st_mode)) {
7402 error = got_error_msg(GOT_ERR_BAD_PATH,
7403 "adding directories requires -R option");
7404 goto done;
7409 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7410 NULL, repo, no_ignores);
7411 done:
7412 if (repo) {
7413 const struct got_error *close_err = got_repo_close(repo);
7414 if (error == NULL)
7415 error = close_err;
7417 if (worktree)
7418 got_worktree_close(worktree);
7419 if (pack_fds) {
7420 const struct got_error *pack_err =
7421 got_repo_pack_fds_close(pack_fds);
7422 if (error == NULL)
7423 error = pack_err;
7425 TAILQ_FOREACH(pe, &paths, entry)
7426 free((char *)pe->path);
7427 got_pathlist_free(&paths);
7428 free(cwd);
7429 return error;
7432 __dead static void
7433 usage_remove(void)
7435 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7436 "path ...\n", getprogname());
7437 exit(1);
7440 static const struct got_error *
7441 print_remove_status(void *arg, unsigned char status,
7442 unsigned char staged_status, const char *path)
7444 while (path[0] == '/')
7445 path++;
7446 if (status == GOT_STATUS_NONEXISTENT)
7447 return NULL;
7448 if (status == staged_status && (status == GOT_STATUS_DELETE))
7449 status = GOT_STATUS_NO_CHANGE;
7450 printf("%c%c %s\n", status, staged_status, path);
7451 return NULL;
7454 static const struct got_error *
7455 cmd_remove(int argc, char *argv[])
7457 const struct got_error *error = NULL;
7458 struct got_worktree *worktree = NULL;
7459 struct got_repository *repo = NULL;
7460 const char *status_codes = NULL;
7461 char *cwd = NULL;
7462 struct got_pathlist_head paths;
7463 struct got_pathlist_entry *pe;
7464 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7465 int ignore_missing_paths = 0;
7466 int *pack_fds = NULL;
7468 TAILQ_INIT(&paths);
7470 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7471 switch (ch) {
7472 case 'f':
7473 delete_local_mods = 1;
7474 ignore_missing_paths = 1;
7475 break;
7476 case 'k':
7477 keep_on_disk = 1;
7478 break;
7479 case 'R':
7480 can_recurse = 1;
7481 break;
7482 case 's':
7483 for (i = 0; i < strlen(optarg); i++) {
7484 switch (optarg[i]) {
7485 case GOT_STATUS_MODIFY:
7486 delete_local_mods = 1;
7487 break;
7488 case GOT_STATUS_MISSING:
7489 ignore_missing_paths = 1;
7490 break;
7491 default:
7492 errx(1, "invalid status code '%c'",
7493 optarg[i]);
7496 status_codes = optarg;
7497 break;
7498 default:
7499 usage_remove();
7500 /* NOTREACHED */
7504 argc -= optind;
7505 argv += optind;
7507 #ifndef PROFILE
7508 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7509 NULL) == -1)
7510 err(1, "pledge");
7511 #endif
7512 if (argc < 1)
7513 usage_remove();
7515 cwd = getcwd(NULL, 0);
7516 if (cwd == NULL) {
7517 error = got_error_from_errno("getcwd");
7518 goto done;
7521 error = got_repo_pack_fds_open(&pack_fds);
7522 if (error != NULL)
7523 goto done;
7525 error = got_worktree_open(&worktree, cwd);
7526 if (error) {
7527 if (error->code == GOT_ERR_NOT_WORKTREE)
7528 error = wrap_not_worktree_error(error, "remove", cwd);
7529 goto done;
7532 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7533 NULL, pack_fds);
7534 if (error)
7535 goto done;
7537 error = apply_unveil(got_repo_get_path(repo), 1,
7538 got_worktree_get_root_path(worktree));
7539 if (error)
7540 goto done;
7542 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7543 if (error)
7544 goto done;
7546 if (!can_recurse) {
7547 char *ondisk_path;
7548 struct stat sb;
7549 TAILQ_FOREACH(pe, &paths, entry) {
7550 if (asprintf(&ondisk_path, "%s/%s",
7551 got_worktree_get_root_path(worktree),
7552 pe->path) == -1) {
7553 error = got_error_from_errno("asprintf");
7554 goto done;
7556 if (lstat(ondisk_path, &sb) == -1) {
7557 if (errno == ENOENT) {
7558 free(ondisk_path);
7559 continue;
7561 error = got_error_from_errno2("lstat",
7562 ondisk_path);
7563 free(ondisk_path);
7564 goto done;
7566 free(ondisk_path);
7567 if (S_ISDIR(sb.st_mode)) {
7568 error = got_error_msg(GOT_ERR_BAD_PATH,
7569 "removing directories requires -R option");
7570 goto done;
7575 error = got_worktree_schedule_delete(worktree, &paths,
7576 delete_local_mods, status_codes, print_remove_status, NULL,
7577 repo, keep_on_disk, ignore_missing_paths);
7578 done:
7579 if (repo) {
7580 const struct got_error *close_err = got_repo_close(repo);
7581 if (error == NULL)
7582 error = close_err;
7584 if (worktree)
7585 got_worktree_close(worktree);
7586 if (pack_fds) {
7587 const struct got_error *pack_err =
7588 got_repo_pack_fds_close(pack_fds);
7589 if (error == NULL)
7590 error = pack_err;
7592 TAILQ_FOREACH(pe, &paths, entry)
7593 free((char *)pe->path);
7594 got_pathlist_free(&paths);
7595 free(cwd);
7596 return error;
7599 __dead static void
7600 usage_patch(void)
7602 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7603 "[-R] [patchfile]\n", getprogname());
7604 exit(1);
7607 static const struct got_error *
7608 patch_from_stdin(int *patchfd)
7610 const struct got_error *err = NULL;
7611 ssize_t r;
7612 char *path, buf[BUFSIZ];
7613 sig_t sighup, sigint, sigquit;
7615 err = got_opentemp_named_fd(&path, patchfd,
7616 GOT_TMPDIR_STR "/got-patch");
7617 if (err)
7618 return err;
7619 unlink(path);
7620 free(path);
7622 sighup = signal(SIGHUP, SIG_DFL);
7623 sigint = signal(SIGINT, SIG_DFL);
7624 sigquit = signal(SIGQUIT, SIG_DFL);
7626 for (;;) {
7627 r = read(0, buf, sizeof(buf));
7628 if (r == -1) {
7629 err = got_error_from_errno("read");
7630 break;
7632 if (r == 0)
7633 break;
7634 if (write(*patchfd, buf, r) == -1) {
7635 err = got_error_from_errno("write");
7636 break;
7640 signal(SIGHUP, sighup);
7641 signal(SIGINT, sigint);
7642 signal(SIGQUIT, sigquit);
7644 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7645 err = got_error_from_errno("lseek");
7647 if (err != NULL) {
7648 close(*patchfd);
7649 *patchfd = -1;
7652 return err;
7655 static const struct got_error *
7656 patch_progress(void *arg, const char *old, const char *new,
7657 unsigned char status, const struct got_error *error, long old_from,
7658 long old_lines, long new_from, long new_lines, long offset,
7659 const struct got_error *hunk_err)
7661 const char *path = new == NULL ? old : new;
7663 while (*path == '/')
7664 path++;
7666 if (status != 0)
7667 printf("%c %s\n", status, path);
7669 if (error != NULL)
7670 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7672 if (offset != 0 || hunk_err != NULL) {
7673 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7674 old_lines, new_from, new_lines);
7675 if (hunk_err != NULL)
7676 printf("%s\n", hunk_err->msg);
7677 else
7678 printf("applied with offset %ld\n", offset);
7681 return NULL;
7684 static const struct got_error *
7685 cmd_patch(int argc, char *argv[])
7687 const struct got_error *error = NULL, *close_error = NULL;
7688 struct got_worktree *worktree = NULL;
7689 struct got_repository *repo = NULL;
7690 const char *errstr;
7691 char *cwd = NULL;
7692 int ch, nop = 0, strip = -1, reverse = 0;
7693 int patchfd;
7694 int *pack_fds = NULL;
7696 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7697 switch (ch) {
7698 case 'n':
7699 nop = 1;
7700 break;
7701 case 'p':
7702 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7703 if (errstr != NULL)
7704 errx(1, "pathname strip count is %s: %s",
7705 errstr, optarg);
7706 break;
7707 case 'R':
7708 reverse = 1;
7709 break;
7710 default:
7711 usage_patch();
7712 /* NOTREACHED */
7716 argc -= optind;
7717 argv += optind;
7719 if (argc == 0) {
7720 error = patch_from_stdin(&patchfd);
7721 if (error)
7722 return error;
7723 } else if (argc == 1) {
7724 patchfd = open(argv[0], O_RDONLY);
7725 if (patchfd == -1) {
7726 error = got_error_from_errno2("open", argv[0]);
7727 return error;
7729 } else
7730 usage_patch();
7732 if ((cwd = getcwd(NULL, 0)) == NULL) {
7733 error = got_error_from_errno("getcwd");
7734 goto done;
7737 error = got_repo_pack_fds_open(&pack_fds);
7738 if (error != NULL)
7739 goto done;
7741 error = got_worktree_open(&worktree, cwd);
7742 if (error != NULL)
7743 goto done;
7745 const char *repo_path = got_worktree_get_repo_path(worktree);
7746 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7747 if (error != NULL)
7748 goto done;
7750 error = apply_unveil(got_repo_get_path(repo), 0,
7751 got_worktree_get_root_path(worktree));
7752 if (error != NULL)
7753 goto done;
7755 #ifndef PROFILE
7756 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7757 NULL) == -1)
7758 err(1, "pledge");
7759 #endif
7761 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7762 &patch_progress, NULL, check_cancelled, NULL);
7764 done:
7765 if (repo) {
7766 close_error = got_repo_close(repo);
7767 if (error == NULL)
7768 error = close_error;
7770 if (worktree != NULL) {
7771 close_error = got_worktree_close(worktree);
7772 if (error == NULL)
7773 error = close_error;
7775 if (pack_fds) {
7776 const struct got_error *pack_err =
7777 got_repo_pack_fds_close(pack_fds);
7778 if (error == NULL)
7779 error = pack_err;
7781 free(cwd);
7782 return error;
7785 __dead static void
7786 usage_revert(void)
7788 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7789 "path ...\n", getprogname());
7790 exit(1);
7793 static const struct got_error *
7794 revert_progress(void *arg, unsigned char status, const char *path)
7796 if (status == GOT_STATUS_UNVERSIONED)
7797 return NULL;
7799 while (path[0] == '/')
7800 path++;
7801 printf("%c %s\n", status, path);
7802 return NULL;
7805 struct choose_patch_arg {
7806 FILE *patch_script_file;
7807 const char *action;
7810 static const struct got_error *
7811 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7812 int nchanges, const char *action)
7814 const struct got_error *err;
7815 char *line = NULL;
7816 size_t linesize = 0;
7817 ssize_t linelen;
7819 switch (status) {
7820 case GOT_STATUS_ADD:
7821 printf("A %s\n%s this addition? [y/n] ", path, action);
7822 break;
7823 case GOT_STATUS_DELETE:
7824 printf("D %s\n%s this deletion? [y/n] ", path, action);
7825 break;
7826 case GOT_STATUS_MODIFY:
7827 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7828 return got_error_from_errno("fseek");
7829 printf(GOT_COMMIT_SEP_STR);
7830 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7831 printf("%s", line);
7832 if (linelen == -1 && ferror(patch_file)) {
7833 err = got_error_from_errno("getline");
7834 free(line);
7835 return err;
7837 free(line);
7838 printf(GOT_COMMIT_SEP_STR);
7839 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7840 path, n, nchanges, action);
7841 break;
7842 default:
7843 return got_error_path(path, GOT_ERR_FILE_STATUS);
7846 return NULL;
7849 static const struct got_error *
7850 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7851 FILE *patch_file, int n, int nchanges)
7853 const struct got_error *err = NULL;
7854 char *line = NULL;
7855 size_t linesize = 0;
7856 ssize_t linelen;
7857 int resp = ' ';
7858 struct choose_patch_arg *a = arg;
7860 *choice = GOT_PATCH_CHOICE_NONE;
7862 if (a->patch_script_file) {
7863 char *nl;
7864 err = show_change(status, path, patch_file, n, nchanges,
7865 a->action);
7866 if (err)
7867 return err;
7868 linelen = getline(&line, &linesize, a->patch_script_file);
7869 if (linelen == -1) {
7870 if (ferror(a->patch_script_file))
7871 return got_error_from_errno("getline");
7872 return NULL;
7874 nl = strchr(line, '\n');
7875 if (nl)
7876 *nl = '\0';
7877 if (strcmp(line, "y") == 0) {
7878 *choice = GOT_PATCH_CHOICE_YES;
7879 printf("y\n");
7880 } else if (strcmp(line, "n") == 0) {
7881 *choice = GOT_PATCH_CHOICE_NO;
7882 printf("n\n");
7883 } else if (strcmp(line, "q") == 0 &&
7884 status == GOT_STATUS_MODIFY) {
7885 *choice = GOT_PATCH_CHOICE_QUIT;
7886 printf("q\n");
7887 } else
7888 printf("invalid response '%s'\n", line);
7889 free(line);
7890 return NULL;
7893 while (resp != 'y' && resp != 'n' && resp != 'q') {
7894 err = show_change(status, path, patch_file, n, nchanges,
7895 a->action);
7896 if (err)
7897 return err;
7898 resp = getchar();
7899 if (resp == '\n')
7900 resp = getchar();
7901 if (status == GOT_STATUS_MODIFY) {
7902 if (resp != 'y' && resp != 'n' && resp != 'q') {
7903 printf("invalid response '%c'\n", resp);
7904 resp = ' ';
7906 } else if (resp != 'y' && resp != 'n') {
7907 printf("invalid response '%c'\n", resp);
7908 resp = ' ';
7912 if (resp == 'y')
7913 *choice = GOT_PATCH_CHOICE_YES;
7914 else if (resp == 'n')
7915 *choice = GOT_PATCH_CHOICE_NO;
7916 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7917 *choice = GOT_PATCH_CHOICE_QUIT;
7919 return NULL;
7922 static const struct got_error *
7923 cmd_revert(int argc, char *argv[])
7925 const struct got_error *error = NULL;
7926 struct got_worktree *worktree = NULL;
7927 struct got_repository *repo = NULL;
7928 char *cwd = NULL, *path = NULL;
7929 struct got_pathlist_head paths;
7930 struct got_pathlist_entry *pe;
7931 int ch, can_recurse = 0, pflag = 0;
7932 FILE *patch_script_file = NULL;
7933 const char *patch_script_path = NULL;
7934 struct choose_patch_arg cpa;
7935 int *pack_fds = NULL;
7937 TAILQ_INIT(&paths);
7939 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7940 switch (ch) {
7941 case 'p':
7942 pflag = 1;
7943 break;
7944 case 'F':
7945 patch_script_path = optarg;
7946 break;
7947 case 'R':
7948 can_recurse = 1;
7949 break;
7950 default:
7951 usage_revert();
7952 /* NOTREACHED */
7956 argc -= optind;
7957 argv += optind;
7959 #ifndef PROFILE
7960 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7961 "unveil", NULL) == -1)
7962 err(1, "pledge");
7963 #endif
7964 if (argc < 1)
7965 usage_revert();
7966 if (patch_script_path && !pflag)
7967 errx(1, "-F option can only be used together with -p option");
7969 cwd = getcwd(NULL, 0);
7970 if (cwd == NULL) {
7971 error = got_error_from_errno("getcwd");
7972 goto done;
7975 error = got_repo_pack_fds_open(&pack_fds);
7976 if (error != NULL)
7977 goto done;
7979 error = got_worktree_open(&worktree, cwd);
7980 if (error) {
7981 if (error->code == GOT_ERR_NOT_WORKTREE)
7982 error = wrap_not_worktree_error(error, "revert", cwd);
7983 goto done;
7986 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7987 NULL, pack_fds);
7988 if (error != NULL)
7989 goto done;
7991 if (patch_script_path) {
7992 patch_script_file = fopen(patch_script_path, "re");
7993 if (patch_script_file == NULL) {
7994 error = got_error_from_errno2("fopen",
7995 patch_script_path);
7996 goto done;
7999 error = apply_unveil(got_repo_get_path(repo), 1,
8000 got_worktree_get_root_path(worktree));
8001 if (error)
8002 goto done;
8004 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8005 if (error)
8006 goto done;
8008 if (!can_recurse) {
8009 char *ondisk_path;
8010 struct stat sb;
8011 TAILQ_FOREACH(pe, &paths, entry) {
8012 if (asprintf(&ondisk_path, "%s/%s",
8013 got_worktree_get_root_path(worktree),
8014 pe->path) == -1) {
8015 error = got_error_from_errno("asprintf");
8016 goto done;
8018 if (lstat(ondisk_path, &sb) == -1) {
8019 if (errno == ENOENT) {
8020 free(ondisk_path);
8021 continue;
8023 error = got_error_from_errno2("lstat",
8024 ondisk_path);
8025 free(ondisk_path);
8026 goto done;
8028 free(ondisk_path);
8029 if (S_ISDIR(sb.st_mode)) {
8030 error = got_error_msg(GOT_ERR_BAD_PATH,
8031 "reverting directories requires -R option");
8032 goto done;
8037 cpa.patch_script_file = patch_script_file;
8038 cpa.action = "revert";
8039 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8040 pflag ? choose_patch : NULL, &cpa, repo);
8041 done:
8042 if (patch_script_file && fclose(patch_script_file) == EOF &&
8043 error == NULL)
8044 error = got_error_from_errno2("fclose", patch_script_path);
8045 if (repo) {
8046 const struct got_error *close_err = got_repo_close(repo);
8047 if (error == NULL)
8048 error = close_err;
8050 if (worktree)
8051 got_worktree_close(worktree);
8052 if (pack_fds) {
8053 const struct got_error *pack_err =
8054 got_repo_pack_fds_close(pack_fds);
8055 if (error == NULL)
8056 error = pack_err;
8058 free(path);
8059 free(cwd);
8060 return error;
8063 __dead static void
8064 usage_commit(void)
8066 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8067 "[path ...]\n", getprogname());
8068 exit(1);
8071 struct collect_commit_logmsg_arg {
8072 const char *cmdline_log;
8073 const char *prepared_log;
8074 int non_interactive;
8075 const char *editor;
8076 const char *worktree_path;
8077 const char *branch_name;
8078 const char *repo_path;
8079 char *logmsg_path;
8083 static const struct got_error *
8084 read_prepared_logmsg(char **logmsg, const char *path)
8086 const struct got_error *err = NULL;
8087 FILE *f = NULL;
8088 struct stat sb;
8089 size_t r;
8091 *logmsg = NULL;
8092 memset(&sb, 0, sizeof(sb));
8094 f = fopen(path, "re");
8095 if (f == NULL)
8096 return got_error_from_errno2("fopen", path);
8098 if (fstat(fileno(f), &sb) == -1) {
8099 err = got_error_from_errno2("fstat", path);
8100 goto done;
8102 if (sb.st_size == 0) {
8103 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8104 goto done;
8107 *logmsg = malloc(sb.st_size + 1);
8108 if (*logmsg == NULL) {
8109 err = got_error_from_errno("malloc");
8110 goto done;
8113 r = fread(*logmsg, 1, sb.st_size, f);
8114 if (r != sb.st_size) {
8115 if (ferror(f))
8116 err = got_error_from_errno2("fread", path);
8117 else
8118 err = got_error(GOT_ERR_IO);
8119 goto done;
8121 (*logmsg)[sb.st_size] = '\0';
8122 done:
8123 if (fclose(f) == EOF && err == NULL)
8124 err = got_error_from_errno2("fclose", path);
8125 if (err) {
8126 free(*logmsg);
8127 *logmsg = NULL;
8129 return err;
8133 static const struct got_error *
8134 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8135 void *arg)
8137 char *initial_content = NULL;
8138 struct got_pathlist_entry *pe;
8139 const struct got_error *err = NULL;
8140 char *template = NULL;
8141 struct collect_commit_logmsg_arg *a = arg;
8142 int initial_content_len;
8143 int fd = -1;
8144 size_t len;
8146 /* if a message was specified on the command line, just use it */
8147 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8148 len = strlen(a->cmdline_log) + 1;
8149 *logmsg = malloc(len + 1);
8150 if (*logmsg == NULL)
8151 return got_error_from_errno("malloc");
8152 strlcpy(*logmsg, a->cmdline_log, len);
8153 return NULL;
8154 } else if (a->prepared_log != NULL && a->non_interactive)
8155 return read_prepared_logmsg(logmsg, a->prepared_log);
8157 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8158 return got_error_from_errno("asprintf");
8160 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8161 if (err)
8162 goto done;
8164 if (a->prepared_log) {
8165 char *msg;
8166 err = read_prepared_logmsg(&msg, a->prepared_log);
8167 if (err)
8168 goto done;
8169 if (write(fd, msg, strlen(msg)) == -1) {
8170 err = got_error_from_errno2("write", a->logmsg_path);
8171 free(msg);
8172 goto done;
8174 free(msg);
8177 initial_content_len = asprintf(&initial_content,
8178 "\n# changes to be committed on branch %s:\n",
8179 a->branch_name);
8180 if (initial_content_len == -1) {
8181 err = got_error_from_errno("asprintf");
8182 goto done;
8185 if (write(fd, initial_content, initial_content_len) == -1) {
8186 err = got_error_from_errno2("write", a->logmsg_path);
8187 goto done;
8190 TAILQ_FOREACH(pe, commitable_paths, entry) {
8191 struct got_commitable *ct = pe->data;
8192 dprintf(fd, "# %c %s\n",
8193 got_commitable_get_status(ct),
8194 got_commitable_get_path(ct));
8197 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8198 initial_content_len, a->prepared_log ? 0 : 1);
8199 done:
8200 free(initial_content);
8201 free(template);
8203 if (fd != -1 && close(fd) == -1 && err == NULL)
8204 err = got_error_from_errno2("close", a->logmsg_path);
8206 /* Editor is done; we can now apply unveil(2) */
8207 if (err == NULL)
8208 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8209 if (err) {
8210 free(*logmsg);
8211 *logmsg = NULL;
8213 return err;
8216 static const struct got_error *
8217 cmd_commit(int argc, char *argv[])
8219 const struct got_error *error = NULL;
8220 struct got_worktree *worktree = NULL;
8221 struct got_repository *repo = NULL;
8222 char *cwd = NULL, *id_str = NULL;
8223 struct got_object_id *id = NULL;
8224 const char *logmsg = NULL;
8225 char *prepared_logmsg = NULL;
8226 struct collect_commit_logmsg_arg cl_arg;
8227 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8228 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8229 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8230 struct got_pathlist_head paths;
8231 int *pack_fds = NULL;
8233 TAILQ_INIT(&paths);
8234 cl_arg.logmsg_path = NULL;
8236 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8237 switch (ch) {
8238 case 'F':
8239 if (logmsg != NULL)
8240 option_conflict('F', 'm');
8241 prepared_logmsg = realpath(optarg, NULL);
8242 if (prepared_logmsg == NULL)
8243 return got_error_from_errno2("realpath",
8244 optarg);
8245 break;
8246 case 'm':
8247 if (prepared_logmsg)
8248 option_conflict('m', 'F');
8249 logmsg = optarg;
8250 break;
8251 case 'N':
8252 non_interactive = 1;
8253 break;
8254 case 'S':
8255 allow_bad_symlinks = 1;
8256 break;
8257 default:
8258 usage_commit();
8259 /* NOTREACHED */
8263 argc -= optind;
8264 argv += optind;
8266 #ifndef PROFILE
8267 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8268 "unveil", NULL) == -1)
8269 err(1, "pledge");
8270 #endif
8271 cwd = getcwd(NULL, 0);
8272 if (cwd == NULL) {
8273 error = got_error_from_errno("getcwd");
8274 goto done;
8277 error = got_repo_pack_fds_open(&pack_fds);
8278 if (error != NULL)
8279 goto done;
8281 error = got_worktree_open(&worktree, cwd);
8282 if (error) {
8283 if (error->code == GOT_ERR_NOT_WORKTREE)
8284 error = wrap_not_worktree_error(error, "commit", cwd);
8285 goto done;
8288 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8289 if (error)
8290 goto done;
8291 if (rebase_in_progress) {
8292 error = got_error(GOT_ERR_REBASING);
8293 goto done;
8296 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8297 worktree);
8298 if (error)
8299 goto done;
8301 error = get_gitconfig_path(&gitconfig_path);
8302 if (error)
8303 goto done;
8304 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8305 gitconfig_path, pack_fds);
8306 if (error != NULL)
8307 goto done;
8309 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8310 if (error)
8311 goto done;
8312 if (merge_in_progress) {
8313 error = got_error(GOT_ERR_MERGE_BUSY);
8314 goto done;
8317 error = get_author(&author, repo, worktree);
8318 if (error)
8319 return error;
8322 * unveil(2) traverses exec(2); if an editor is used we have
8323 * to apply unveil after the log message has been written.
8325 if (logmsg == NULL || strlen(logmsg) == 0)
8326 error = get_editor(&editor);
8327 else
8328 error = apply_unveil(got_repo_get_path(repo), 0,
8329 got_worktree_get_root_path(worktree));
8330 if (error)
8331 goto done;
8333 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8334 if (error)
8335 goto done;
8337 cl_arg.editor = editor;
8338 cl_arg.cmdline_log = logmsg;
8339 cl_arg.prepared_log = prepared_logmsg;
8340 cl_arg.non_interactive = non_interactive;
8341 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8342 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8343 if (!histedit_in_progress) {
8344 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8345 error = got_error(GOT_ERR_COMMIT_BRANCH);
8346 goto done;
8348 cl_arg.branch_name += 11;
8350 cl_arg.repo_path = got_repo_get_path(repo);
8351 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8352 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8353 print_status, NULL, repo);
8354 if (error) {
8355 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8356 cl_arg.logmsg_path != NULL)
8357 preserve_logmsg = 1;
8358 goto done;
8361 error = got_object_id_str(&id_str, id);
8362 if (error)
8363 goto done;
8364 printf("Created commit %s\n", id_str);
8365 done:
8366 if (preserve_logmsg) {
8367 fprintf(stderr, "%s: log message preserved in %s\n",
8368 getprogname(), cl_arg.logmsg_path);
8369 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8370 error == NULL)
8371 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8372 free(cl_arg.logmsg_path);
8373 if (repo) {
8374 const struct got_error *close_err = got_repo_close(repo);
8375 if (error == NULL)
8376 error = close_err;
8378 if (worktree)
8379 got_worktree_close(worktree);
8380 if (pack_fds) {
8381 const struct got_error *pack_err =
8382 got_repo_pack_fds_close(pack_fds);
8383 if (error == NULL)
8384 error = pack_err;
8386 free(cwd);
8387 free(id_str);
8388 free(gitconfig_path);
8389 free(editor);
8390 free(author);
8391 free(prepared_logmsg);
8392 return error;
8395 __dead static void
8396 usage_send(void)
8398 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8399 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8400 "[remote-repository]\n", getprogname());
8401 exit(1);
8404 static void
8405 print_load_info(int print_colored, int print_found, int print_trees,
8406 int ncolored, int nfound, int ntrees)
8408 if (print_colored) {
8409 printf("%d commit%s colored", ncolored,
8410 ncolored == 1 ? "" : "s");
8412 if (print_found) {
8413 printf("%s%d object%s found",
8414 ncolored > 0 ? "; " : "",
8415 nfound, nfound == 1 ? "" : "s");
8417 if (print_trees) {
8418 printf("; %d tree%s scanned", ntrees,
8419 ntrees == 1 ? "" : "s");
8423 struct got_send_progress_arg {
8424 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8425 int verbosity;
8426 int last_ncolored;
8427 int last_nfound;
8428 int last_ntrees;
8429 int loading_done;
8430 int last_ncommits;
8431 int last_nobj_total;
8432 int last_p_deltify;
8433 int last_p_written;
8434 int last_p_sent;
8435 int printed_something;
8436 int sent_something;
8437 struct got_pathlist_head *delete_branches;
8440 static const struct got_error *
8441 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8442 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8443 int nobj_written, off_t bytes_sent, const char *refname, int success)
8445 struct got_send_progress_arg *a = arg;
8446 char scaled_packsize[FMT_SCALED_STRSIZE];
8447 char scaled_sent[FMT_SCALED_STRSIZE];
8448 int p_deltify = 0, p_written = 0, p_sent = 0;
8449 int print_colored = 0, print_found = 0, print_trees = 0;
8450 int print_searching = 0, print_total = 0;
8451 int print_deltify = 0, print_written = 0, print_sent = 0;
8453 if (a->verbosity < 0)
8454 return NULL;
8456 if (refname) {
8457 const char *status = success ? "accepted" : "rejected";
8459 if (success) {
8460 struct got_pathlist_entry *pe;
8461 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8462 const char *branchname = pe->path;
8463 if (got_path_cmp(branchname, refname,
8464 strlen(branchname), strlen(refname)) == 0) {
8465 status = "deleted";
8466 a->sent_something = 1;
8467 break;
8472 if (a->printed_something)
8473 putchar('\n');
8474 printf("Server has %s %s", status, refname);
8475 a->printed_something = 1;
8476 return NULL;
8479 if (a->last_ncolored != ncolored) {
8480 print_colored = 1;
8481 a->last_ncolored = ncolored;
8484 if (a->last_nfound != nfound) {
8485 print_colored = 1;
8486 print_found = 1;
8487 a->last_nfound = nfound;
8490 if (a->last_ntrees != ntrees) {
8491 print_colored = 1;
8492 print_found = 1;
8493 print_trees = 1;
8494 a->last_ntrees = ntrees;
8497 if ((print_colored || print_found || print_trees) &&
8498 !a->loading_done) {
8499 printf("\r");
8500 print_load_info(print_colored, print_found, print_trees,
8501 ncolored, nfound, ntrees);
8502 a->printed_something = 1;
8503 fflush(stdout);
8504 return NULL;
8505 } else if (!a->loading_done) {
8506 printf("\r");
8507 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8508 printf("\n");
8509 a->loading_done = 1;
8512 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8513 return got_error_from_errno("fmt_scaled");
8514 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8515 return got_error_from_errno("fmt_scaled");
8517 if (a->last_ncommits != ncommits) {
8518 print_searching = 1;
8519 a->last_ncommits = ncommits;
8522 if (a->last_nobj_total != nobj_total) {
8523 print_searching = 1;
8524 print_total = 1;
8525 a->last_nobj_total = nobj_total;
8528 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8529 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8530 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8531 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8532 return got_error(GOT_ERR_NO_SPACE);
8535 if (nobj_deltify > 0 || nobj_written > 0) {
8536 if (nobj_deltify > 0) {
8537 p_deltify = (nobj_deltify * 100) / nobj_total;
8538 if (p_deltify != a->last_p_deltify) {
8539 a->last_p_deltify = p_deltify;
8540 print_searching = 1;
8541 print_total = 1;
8542 print_deltify = 1;
8545 if (nobj_written > 0) {
8546 p_written = (nobj_written * 100) / nobj_total;
8547 if (p_written != a->last_p_written) {
8548 a->last_p_written = p_written;
8549 print_searching = 1;
8550 print_total = 1;
8551 print_deltify = 1;
8552 print_written = 1;
8557 if (bytes_sent > 0) {
8558 p_sent = (bytes_sent * 100) / packfile_size;
8559 if (p_sent != a->last_p_sent) {
8560 a->last_p_sent = p_sent;
8561 print_searching = 1;
8562 print_total = 1;
8563 print_deltify = 1;
8564 print_written = 1;
8565 print_sent = 1;
8567 a->sent_something = 1;
8570 if (print_searching || print_total || print_deltify || print_written ||
8571 print_sent)
8572 printf("\r");
8573 if (print_searching)
8574 printf("packing %d reference%s", ncommits,
8575 ncommits == 1 ? "" : "s");
8576 if (print_total)
8577 printf("; %d object%s", nobj_total,
8578 nobj_total == 1 ? "" : "s");
8579 if (print_deltify)
8580 printf("; deltify: %d%%", p_deltify);
8581 if (print_sent)
8582 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8583 scaled_packsize, p_sent);
8584 else if (print_written)
8585 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8586 scaled_packsize, p_written);
8587 if (print_searching || print_total || print_deltify ||
8588 print_written || print_sent) {
8589 a->printed_something = 1;
8590 fflush(stdout);
8592 return NULL;
8595 static const struct got_error *
8596 cmd_send(int argc, char *argv[])
8598 const struct got_error *error = NULL;
8599 char *cwd = NULL, *repo_path = NULL;
8600 const char *remote_name;
8601 char *proto = NULL, *host = NULL, *port = NULL;
8602 char *repo_name = NULL, *server_path = NULL;
8603 const struct got_remote_repo *remotes, *remote = NULL;
8604 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8605 struct got_repository *repo = NULL;
8606 struct got_worktree *worktree = NULL;
8607 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8608 struct got_pathlist_head branches;
8609 struct got_pathlist_head tags;
8610 struct got_reflist_head all_branches;
8611 struct got_reflist_head all_tags;
8612 struct got_pathlist_head delete_args;
8613 struct got_pathlist_head delete_branches;
8614 struct got_reflist_entry *re;
8615 struct got_pathlist_entry *pe;
8616 int i, ch, sendfd = -1, sendstatus;
8617 pid_t sendpid = -1;
8618 struct got_send_progress_arg spa;
8619 int verbosity = 0, overwrite_refs = 0;
8620 int send_all_branches = 0, send_all_tags = 0;
8621 struct got_reference *ref = NULL;
8622 int *pack_fds = NULL;
8624 TAILQ_INIT(&branches);
8625 TAILQ_INIT(&tags);
8626 TAILQ_INIT(&all_branches);
8627 TAILQ_INIT(&all_tags);
8628 TAILQ_INIT(&delete_args);
8629 TAILQ_INIT(&delete_branches);
8631 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8632 switch (ch) {
8633 case 'a':
8634 send_all_branches = 1;
8635 break;
8636 case 'b':
8637 error = got_pathlist_append(&branches, optarg, NULL);
8638 if (error)
8639 return error;
8640 nbranches++;
8641 break;
8642 case 'd':
8643 error = got_pathlist_append(&delete_args, optarg, NULL);
8644 if (error)
8645 return error;
8646 break;
8647 case 'f':
8648 overwrite_refs = 1;
8649 break;
8650 case 'r':
8651 repo_path = realpath(optarg, NULL);
8652 if (repo_path == NULL)
8653 return got_error_from_errno2("realpath",
8654 optarg);
8655 got_path_strip_trailing_slashes(repo_path);
8656 break;
8657 case 't':
8658 error = got_pathlist_append(&tags, optarg, NULL);
8659 if (error)
8660 return error;
8661 ntags++;
8662 break;
8663 case 'T':
8664 send_all_tags = 1;
8665 break;
8666 case 'v':
8667 if (verbosity < 0)
8668 verbosity = 0;
8669 else if (verbosity < 3)
8670 verbosity++;
8671 break;
8672 case 'q':
8673 verbosity = -1;
8674 break;
8675 default:
8676 usage_send();
8677 /* NOTREACHED */
8680 argc -= optind;
8681 argv += optind;
8683 if (send_all_branches && !TAILQ_EMPTY(&branches))
8684 option_conflict('a', 'b');
8685 if (send_all_tags && !TAILQ_EMPTY(&tags))
8686 option_conflict('T', 't');
8689 if (argc == 0)
8690 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8691 else if (argc == 1)
8692 remote_name = argv[0];
8693 else
8694 usage_send();
8696 cwd = getcwd(NULL, 0);
8697 if (cwd == NULL) {
8698 error = got_error_from_errno("getcwd");
8699 goto done;
8702 error = got_repo_pack_fds_open(&pack_fds);
8703 if (error != NULL)
8704 goto done;
8706 if (repo_path == NULL) {
8707 error = got_worktree_open(&worktree, cwd);
8708 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8709 goto done;
8710 else
8711 error = NULL;
8712 if (worktree) {
8713 repo_path =
8714 strdup(got_worktree_get_repo_path(worktree));
8715 if (repo_path == NULL)
8716 error = got_error_from_errno("strdup");
8717 if (error)
8718 goto done;
8719 } else {
8720 repo_path = strdup(cwd);
8721 if (repo_path == NULL) {
8722 error = got_error_from_errno("strdup");
8723 goto done;
8728 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8729 if (error)
8730 goto done;
8732 if (worktree) {
8733 worktree_conf = got_worktree_get_gotconfig(worktree);
8734 if (worktree_conf) {
8735 got_gotconfig_get_remotes(&nremotes, &remotes,
8736 worktree_conf);
8737 for (i = 0; i < nremotes; i++) {
8738 if (strcmp(remotes[i].name, remote_name) == 0) {
8739 remote = &remotes[i];
8740 break;
8745 if (remote == NULL) {
8746 repo_conf = got_repo_get_gotconfig(repo);
8747 if (repo_conf) {
8748 got_gotconfig_get_remotes(&nremotes, &remotes,
8749 repo_conf);
8750 for (i = 0; i < nremotes; i++) {
8751 if (strcmp(remotes[i].name, remote_name) == 0) {
8752 remote = &remotes[i];
8753 break;
8758 if (remote == NULL) {
8759 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8760 for (i = 0; i < nremotes; i++) {
8761 if (strcmp(remotes[i].name, remote_name) == 0) {
8762 remote = &remotes[i];
8763 break;
8767 if (remote == NULL) {
8768 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8769 goto done;
8772 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8773 &repo_name, remote->send_url);
8774 if (error)
8775 goto done;
8777 if (strcmp(proto, "git") == 0) {
8778 #ifndef PROFILE
8779 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8780 "sendfd dns inet unveil", NULL) == -1)
8781 err(1, "pledge");
8782 #endif
8783 } else if (strcmp(proto, "git+ssh") == 0 ||
8784 strcmp(proto, "ssh") == 0) {
8785 #ifndef PROFILE
8786 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8787 "sendfd unveil", NULL) == -1)
8788 err(1, "pledge");
8789 #endif
8790 } else if (strcmp(proto, "http") == 0 ||
8791 strcmp(proto, "git+http") == 0) {
8792 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8793 goto done;
8794 } else {
8795 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8796 goto done;
8799 error = got_dial_apply_unveil(proto);
8800 if (error)
8801 goto done;
8803 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8804 if (error)
8805 goto done;
8807 if (send_all_branches) {
8808 error = got_ref_list(&all_branches, repo, "refs/heads",
8809 got_ref_cmp_by_name, NULL);
8810 if (error)
8811 goto done;
8812 TAILQ_FOREACH(re, &all_branches, entry) {
8813 const char *branchname = got_ref_get_name(re->ref);
8814 error = got_pathlist_append(&branches,
8815 branchname, NULL);
8816 if (error)
8817 goto done;
8818 nbranches++;
8820 } else if (nbranches == 0) {
8821 for (i = 0; i < remote->nsend_branches; i++) {
8822 got_pathlist_append(&branches,
8823 remote->send_branches[i], NULL);
8827 if (send_all_tags) {
8828 error = got_ref_list(&all_tags, repo, "refs/tags",
8829 got_ref_cmp_by_name, NULL);
8830 if (error)
8831 goto done;
8832 TAILQ_FOREACH(re, &all_tags, entry) {
8833 const char *tagname = got_ref_get_name(re->ref);
8834 error = got_pathlist_append(&tags,
8835 tagname, NULL);
8836 if (error)
8837 goto done;
8838 ntags++;
8843 * To prevent accidents only branches in refs/heads/ can be deleted
8844 * with 'got send -d'.
8845 * Deleting anything else requires local repository access or Git.
8847 TAILQ_FOREACH(pe, &delete_args, entry) {
8848 const char *branchname = pe->path;
8849 char *s;
8850 struct got_pathlist_entry *new;
8851 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8852 s = strdup(branchname);
8853 if (s == NULL) {
8854 error = got_error_from_errno("strdup");
8855 goto done;
8857 } else {
8858 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8859 error = got_error_from_errno("asprintf");
8860 goto done;
8863 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8864 if (error || new == NULL /* duplicate */)
8865 free(s);
8866 if (error)
8867 goto done;
8868 ndelete_branches++;
8871 if (nbranches == 0 && ndelete_branches == 0) {
8872 struct got_reference *head_ref;
8873 if (worktree)
8874 error = got_ref_open(&head_ref, repo,
8875 got_worktree_get_head_ref_name(worktree), 0);
8876 else
8877 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8878 if (error)
8879 goto done;
8880 if (got_ref_is_symbolic(head_ref)) {
8881 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8882 got_ref_close(head_ref);
8883 if (error)
8884 goto done;
8885 } else
8886 ref = head_ref;
8887 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8888 NULL);
8889 if (error)
8890 goto done;
8891 nbranches++;
8894 if (verbosity >= 0)
8895 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8896 port ? ":" : "", port ? port : "");
8898 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8899 server_path, verbosity);
8900 if (error)
8901 goto done;
8903 memset(&spa, 0, sizeof(spa));
8904 spa.last_scaled_packsize[0] = '\0';
8905 spa.last_p_deltify = -1;
8906 spa.last_p_written = -1;
8907 spa.verbosity = verbosity;
8908 spa.delete_branches = &delete_branches;
8909 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8910 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8911 check_cancelled, NULL);
8912 if (spa.printed_something)
8913 putchar('\n');
8914 if (error)
8915 goto done;
8916 if (!spa.sent_something && verbosity >= 0)
8917 printf("Already up-to-date\n");
8918 done:
8919 if (sendpid > 0) {
8920 if (kill(sendpid, SIGTERM) == -1)
8921 error = got_error_from_errno("kill");
8922 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8923 error = got_error_from_errno("waitpid");
8925 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8926 error = got_error_from_errno("close");
8927 if (repo) {
8928 const struct got_error *close_err = got_repo_close(repo);
8929 if (error == NULL)
8930 error = close_err;
8932 if (worktree)
8933 got_worktree_close(worktree);
8934 if (pack_fds) {
8935 const struct got_error *pack_err =
8936 got_repo_pack_fds_close(pack_fds);
8937 if (error == NULL)
8938 error = pack_err;
8940 if (ref)
8941 got_ref_close(ref);
8942 got_pathlist_free(&branches);
8943 got_pathlist_free(&tags);
8944 got_ref_list_free(&all_branches);
8945 got_ref_list_free(&all_tags);
8946 got_pathlist_free(&delete_args);
8947 TAILQ_FOREACH(pe, &delete_branches, entry)
8948 free((char *)pe->path);
8949 got_pathlist_free(&delete_branches);
8950 free(cwd);
8951 free(repo_path);
8952 free(proto);
8953 free(host);
8954 free(port);
8955 free(server_path);
8956 free(repo_name);
8957 return error;
8960 __dead static void
8961 usage_cherrypick(void)
8963 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8964 exit(1);
8967 static const struct got_error *
8968 cmd_cherrypick(int argc, char *argv[])
8970 const struct got_error *error = NULL;
8971 struct got_worktree *worktree = NULL;
8972 struct got_repository *repo = NULL;
8973 char *cwd = NULL, *commit_id_str = NULL;
8974 struct got_object_id *commit_id = NULL;
8975 struct got_commit_object *commit = NULL;
8976 struct got_object_qid *pid;
8977 int ch;
8978 struct got_update_progress_arg upa;
8979 int *pack_fds = NULL;
8981 while ((ch = getopt(argc, argv, "")) != -1) {
8982 switch (ch) {
8983 default:
8984 usage_cherrypick();
8985 /* NOTREACHED */
8989 argc -= optind;
8990 argv += optind;
8992 #ifndef PROFILE
8993 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8994 "unveil", NULL) == -1)
8995 err(1, "pledge");
8996 #endif
8997 if (argc != 1)
8998 usage_cherrypick();
9000 cwd = getcwd(NULL, 0);
9001 if (cwd == NULL) {
9002 error = got_error_from_errno("getcwd");
9003 goto done;
9006 error = got_repo_pack_fds_open(&pack_fds);
9007 if (error != NULL)
9008 goto done;
9010 error = got_worktree_open(&worktree, cwd);
9011 if (error) {
9012 if (error->code == GOT_ERR_NOT_WORKTREE)
9013 error = wrap_not_worktree_error(error, "cherrypick",
9014 cwd);
9015 goto done;
9018 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9019 NULL, pack_fds);
9020 if (error != NULL)
9021 goto done;
9023 error = apply_unveil(got_repo_get_path(repo), 0,
9024 got_worktree_get_root_path(worktree));
9025 if (error)
9026 goto done;
9028 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9029 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9030 if (error)
9031 goto done;
9032 error = got_object_id_str(&commit_id_str, commit_id);
9033 if (error)
9034 goto done;
9036 error = got_object_open_as_commit(&commit, repo, commit_id);
9037 if (error)
9038 goto done;
9039 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9040 memset(&upa, 0, sizeof(upa));
9041 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9042 commit_id, repo, update_progress, &upa, check_cancelled,
9043 NULL);
9044 if (error != NULL)
9045 goto done;
9047 if (upa.did_something)
9048 printf("Merged commit %s\n", commit_id_str);
9049 print_merge_progress_stats(&upa);
9050 done:
9051 if (commit)
9052 got_object_commit_close(commit);
9053 free(commit_id_str);
9054 if (worktree)
9055 got_worktree_close(worktree);
9056 if (repo) {
9057 const struct got_error *close_err = got_repo_close(repo);
9058 if (error == NULL)
9059 error = close_err;
9061 if (pack_fds) {
9062 const struct got_error *pack_err =
9063 got_repo_pack_fds_close(pack_fds);
9064 if (error == NULL)
9065 error = pack_err;
9068 return error;
9071 __dead static void
9072 usage_backout(void)
9074 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9075 exit(1);
9078 static const struct got_error *
9079 cmd_backout(int argc, char *argv[])
9081 const struct got_error *error = NULL;
9082 struct got_worktree *worktree = NULL;
9083 struct got_repository *repo = NULL;
9084 char *cwd = NULL, *commit_id_str = NULL;
9085 struct got_object_id *commit_id = NULL;
9086 struct got_commit_object *commit = NULL;
9087 struct got_object_qid *pid;
9088 int ch;
9089 struct got_update_progress_arg upa;
9090 int *pack_fds = NULL;
9092 while ((ch = getopt(argc, argv, "")) != -1) {
9093 switch (ch) {
9094 default:
9095 usage_backout();
9096 /* NOTREACHED */
9100 argc -= optind;
9101 argv += optind;
9103 #ifndef PROFILE
9104 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9105 "unveil", NULL) == -1)
9106 err(1, "pledge");
9107 #endif
9108 if (argc != 1)
9109 usage_backout();
9111 cwd = getcwd(NULL, 0);
9112 if (cwd == NULL) {
9113 error = got_error_from_errno("getcwd");
9114 goto done;
9117 error = got_repo_pack_fds_open(&pack_fds);
9118 if (error != NULL)
9119 goto done;
9121 error = got_worktree_open(&worktree, cwd);
9122 if (error) {
9123 if (error->code == GOT_ERR_NOT_WORKTREE)
9124 error = wrap_not_worktree_error(error, "backout", cwd);
9125 goto done;
9128 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9129 NULL, pack_fds);
9130 if (error != NULL)
9131 goto done;
9133 error = apply_unveil(got_repo_get_path(repo), 0,
9134 got_worktree_get_root_path(worktree));
9135 if (error)
9136 goto done;
9138 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9139 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9140 if (error)
9141 goto done;
9142 error = got_object_id_str(&commit_id_str, commit_id);
9143 if (error)
9144 goto done;
9146 error = got_object_open_as_commit(&commit, repo, commit_id);
9147 if (error)
9148 goto done;
9149 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9150 if (pid == NULL) {
9151 error = got_error(GOT_ERR_ROOT_COMMIT);
9152 goto done;
9155 memset(&upa, 0, sizeof(upa));
9156 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9157 repo, update_progress, &upa, check_cancelled, NULL);
9158 if (error != NULL)
9159 goto done;
9161 if (upa.did_something)
9162 printf("Backed out commit %s\n", commit_id_str);
9163 print_merge_progress_stats(&upa);
9164 done:
9165 if (commit)
9166 got_object_commit_close(commit);
9167 free(commit_id_str);
9168 if (worktree)
9169 got_worktree_close(worktree);
9170 if (repo) {
9171 const struct got_error *close_err = got_repo_close(repo);
9172 if (error == NULL)
9173 error = close_err;
9175 if (pack_fds) {
9176 const struct got_error *pack_err =
9177 got_repo_pack_fds_close(pack_fds);
9178 if (error == NULL)
9179 error = pack_err;
9181 return error;
9184 __dead static void
9185 usage_rebase(void)
9187 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9188 getprogname());
9189 exit(1);
9192 static void
9193 trim_logmsg(char *logmsg, int limit)
9195 char *nl;
9196 size_t len;
9198 len = strlen(logmsg);
9199 if (len > limit)
9200 len = limit;
9201 logmsg[len] = '\0';
9202 nl = strchr(logmsg, '\n');
9203 if (nl)
9204 *nl = '\0';
9207 static const struct got_error *
9208 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9210 const struct got_error *err;
9211 char *logmsg0 = NULL;
9212 const char *s;
9214 err = got_object_commit_get_logmsg(&logmsg0, commit);
9215 if (err)
9216 return err;
9218 s = logmsg0;
9219 while (isspace((unsigned char)s[0]))
9220 s++;
9222 *logmsg = strdup(s);
9223 if (*logmsg == NULL) {
9224 err = got_error_from_errno("strdup");
9225 goto done;
9228 trim_logmsg(*logmsg, limit);
9229 done:
9230 free(logmsg0);
9231 return err;
9234 static const struct got_error *
9235 show_rebase_merge_conflict(struct got_object_id *id,
9236 struct got_repository *repo)
9238 const struct got_error *err;
9239 struct got_commit_object *commit = NULL;
9240 char *id_str = NULL, *logmsg = NULL;
9242 err = got_object_open_as_commit(&commit, repo, id);
9243 if (err)
9244 return err;
9246 err = got_object_id_str(&id_str, id);
9247 if (err)
9248 goto done;
9250 id_str[12] = '\0';
9252 err = get_short_logmsg(&logmsg, 42, commit);
9253 if (err)
9254 goto done;
9256 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9257 done:
9258 free(id_str);
9259 got_object_commit_close(commit);
9260 free(logmsg);
9261 return err;
9264 static const struct got_error *
9265 show_rebase_progress(struct got_commit_object *commit,
9266 struct got_object_id *old_id, struct got_object_id *new_id)
9268 const struct got_error *err;
9269 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9271 err = got_object_id_str(&old_id_str, old_id);
9272 if (err)
9273 goto done;
9275 if (new_id) {
9276 err = got_object_id_str(&new_id_str, new_id);
9277 if (err)
9278 goto done;
9281 old_id_str[12] = '\0';
9282 if (new_id_str)
9283 new_id_str[12] = '\0';
9285 err = get_short_logmsg(&logmsg, 42, commit);
9286 if (err)
9287 goto done;
9289 printf("%s -> %s: %s\n", old_id_str,
9290 new_id_str ? new_id_str : "no-op change", logmsg);
9291 done:
9292 free(old_id_str);
9293 free(new_id_str);
9294 free(logmsg);
9295 return err;
9298 static const struct got_error *
9299 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9300 struct got_reference *branch, struct got_reference *new_base_branch,
9301 struct got_reference *tmp_branch, struct got_repository *repo,
9302 int create_backup)
9304 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9305 return got_worktree_rebase_complete(worktree, fileindex,
9306 new_base_branch, tmp_branch, branch, repo, create_backup);
9309 static const struct got_error *
9310 rebase_commit(struct got_pathlist_head *merged_paths,
9311 struct got_worktree *worktree, struct got_fileindex *fileindex,
9312 struct got_reference *tmp_branch,
9313 struct got_object_id *commit_id, struct got_repository *repo)
9315 const struct got_error *error;
9316 struct got_commit_object *commit;
9317 struct got_object_id *new_commit_id;
9319 error = got_object_open_as_commit(&commit, repo, commit_id);
9320 if (error)
9321 return error;
9323 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9324 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9325 if (error) {
9326 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9327 goto done;
9328 error = show_rebase_progress(commit, commit_id, NULL);
9329 } else {
9330 error = show_rebase_progress(commit, commit_id, new_commit_id);
9331 free(new_commit_id);
9333 done:
9334 got_object_commit_close(commit);
9335 return error;
9338 struct check_path_prefix_arg {
9339 const char *path_prefix;
9340 size_t len;
9341 int errcode;
9344 static const struct got_error *
9345 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9346 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9347 struct got_object_id *id1, struct got_object_id *id2,
9348 const char *path1, const char *path2,
9349 mode_t mode1, mode_t mode2, struct got_repository *repo)
9351 struct check_path_prefix_arg *a = arg;
9353 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9354 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9355 return got_error(a->errcode);
9357 return NULL;
9360 static const struct got_error *
9361 check_path_prefix(struct got_object_id *parent_id,
9362 struct got_object_id *commit_id, const char *path_prefix,
9363 int errcode, struct got_repository *repo)
9365 const struct got_error *err;
9366 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9367 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9368 struct check_path_prefix_arg cpp_arg;
9370 if (got_path_is_root_dir(path_prefix))
9371 return NULL;
9373 err = got_object_open_as_commit(&commit, repo, commit_id);
9374 if (err)
9375 goto done;
9377 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9378 if (err)
9379 goto done;
9381 err = got_object_open_as_tree(&tree1, repo,
9382 got_object_commit_get_tree_id(parent_commit));
9383 if (err)
9384 goto done;
9386 err = got_object_open_as_tree(&tree2, repo,
9387 got_object_commit_get_tree_id(commit));
9388 if (err)
9389 goto done;
9391 cpp_arg.path_prefix = path_prefix;
9392 while (cpp_arg.path_prefix[0] == '/')
9393 cpp_arg.path_prefix++;
9394 cpp_arg.len = strlen(cpp_arg.path_prefix);
9395 cpp_arg.errcode = errcode;
9396 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9397 check_path_prefix_in_diff, &cpp_arg, 0);
9398 done:
9399 if (tree1)
9400 got_object_tree_close(tree1);
9401 if (tree2)
9402 got_object_tree_close(tree2);
9403 if (commit)
9404 got_object_commit_close(commit);
9405 if (parent_commit)
9406 got_object_commit_close(parent_commit);
9407 return err;
9410 static const struct got_error *
9411 collect_commits(struct got_object_id_queue *commits,
9412 struct got_object_id *initial_commit_id,
9413 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9414 const char *path_prefix, int path_prefix_errcode,
9415 struct got_repository *repo)
9417 const struct got_error *err = NULL;
9418 struct got_commit_graph *graph = NULL;
9419 struct got_object_id *parent_id = NULL;
9420 struct got_object_qid *qid;
9421 struct got_object_id *commit_id = initial_commit_id;
9423 err = got_commit_graph_open(&graph, "/", 1);
9424 if (err)
9425 return err;
9427 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9428 check_cancelled, NULL);
9429 if (err)
9430 goto done;
9431 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9432 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9433 check_cancelled, NULL);
9434 if (err) {
9435 if (err->code == GOT_ERR_ITER_COMPLETED) {
9436 err = got_error_msg(GOT_ERR_ANCESTRY,
9437 "ran out of commits to rebase before "
9438 "youngest common ancestor commit has "
9439 "been reached?!?");
9441 goto done;
9442 } else {
9443 err = check_path_prefix(parent_id, commit_id,
9444 path_prefix, path_prefix_errcode, repo);
9445 if (err)
9446 goto done;
9448 err = got_object_qid_alloc(&qid, commit_id);
9449 if (err)
9450 goto done;
9451 STAILQ_INSERT_HEAD(commits, qid, entry);
9452 commit_id = parent_id;
9455 done:
9456 got_commit_graph_close(graph);
9457 return err;
9460 static const struct got_error *
9461 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9463 const struct got_error *err = NULL;
9464 time_t committer_time;
9465 struct tm tm;
9466 char datebuf[11]; /* YYYY-MM-DD + NUL */
9467 char *author0 = NULL, *author, *smallerthan;
9468 char *logmsg0 = NULL, *logmsg, *newline;
9470 committer_time = got_object_commit_get_committer_time(commit);
9471 if (gmtime_r(&committer_time, &tm) == NULL)
9472 return got_error_from_errno("gmtime_r");
9473 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9474 return got_error(GOT_ERR_NO_SPACE);
9476 author0 = strdup(got_object_commit_get_author(commit));
9477 if (author0 == NULL)
9478 return got_error_from_errno("strdup");
9479 author = author0;
9480 smallerthan = strchr(author, '<');
9481 if (smallerthan && smallerthan[1] != '\0')
9482 author = smallerthan + 1;
9483 author[strcspn(author, "@>")] = '\0';
9485 err = got_object_commit_get_logmsg(&logmsg0, commit);
9486 if (err)
9487 goto done;
9488 logmsg = logmsg0;
9489 while (*logmsg == '\n')
9490 logmsg++;
9491 newline = strchr(logmsg, '\n');
9492 if (newline)
9493 *newline = '\0';
9495 if (asprintf(brief_str, "%s %s %s",
9496 datebuf, author, logmsg) == -1)
9497 err = got_error_from_errno("asprintf");
9498 done:
9499 free(author0);
9500 free(logmsg0);
9501 return err;
9504 static const struct got_error *
9505 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9506 struct got_repository *repo)
9508 const struct got_error *err;
9509 char *id_str;
9511 err = got_object_id_str(&id_str, id);
9512 if (err)
9513 return err;
9515 err = got_ref_delete(ref, repo);
9516 if (err)
9517 goto done;
9519 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9520 done:
9521 free(id_str);
9522 return err;
9525 static const struct got_error *
9526 print_backup_ref(const char *branch_name, const char *new_id_str,
9527 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9528 struct got_reflist_object_id_map *refs_idmap,
9529 struct got_repository *repo)
9531 const struct got_error *err = NULL;
9532 struct got_reflist_head *refs;
9533 char *refs_str = NULL;
9534 struct got_object_id *new_commit_id = NULL;
9535 struct got_commit_object *new_commit = NULL;
9536 char *new_commit_brief_str = NULL;
9537 struct got_object_id *yca_id = NULL;
9538 struct got_commit_object *yca_commit = NULL;
9539 char *yca_id_str = NULL, *yca_brief_str = NULL;
9540 char *custom_refs_str;
9542 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9543 return got_error_from_errno("asprintf");
9545 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9546 0, 0, refs_idmap, custom_refs_str);
9547 if (err)
9548 goto done;
9550 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9551 if (err)
9552 goto done;
9554 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9555 if (refs) {
9556 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9557 if (err)
9558 goto done;
9561 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9562 if (err)
9563 goto done;
9565 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9566 if (err)
9567 goto done;
9569 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9570 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9571 if (err)
9572 goto done;
9574 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9575 refs_str ? " (" : "", refs_str ? refs_str : "",
9576 refs_str ? ")" : "", new_commit_brief_str);
9577 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9578 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9579 free(refs_str);
9580 refs_str = NULL;
9582 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9583 if (err)
9584 goto done;
9586 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9587 if (err)
9588 goto done;
9590 err = got_object_id_str(&yca_id_str, yca_id);
9591 if (err)
9592 goto done;
9594 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9595 if (refs) {
9596 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9597 if (err)
9598 goto done;
9600 printf("history forked at %s%s%s%s\n %s\n",
9601 yca_id_str,
9602 refs_str ? " (" : "", refs_str ? refs_str : "",
9603 refs_str ? ")" : "", yca_brief_str);
9605 done:
9606 free(custom_refs_str);
9607 free(new_commit_id);
9608 free(refs_str);
9609 free(yca_id);
9610 free(yca_id_str);
9611 free(yca_brief_str);
9612 if (new_commit)
9613 got_object_commit_close(new_commit);
9614 if (yca_commit)
9615 got_object_commit_close(yca_commit);
9617 return NULL;
9620 static const struct got_error *
9621 process_backup_refs(const char *backup_ref_prefix,
9622 const char *wanted_branch_name,
9623 int delete, struct got_repository *repo)
9625 const struct got_error *err;
9626 struct got_reflist_head refs, backup_refs;
9627 struct got_reflist_entry *re;
9628 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9629 struct got_object_id *old_commit_id = NULL;
9630 char *branch_name = NULL;
9631 struct got_commit_object *old_commit = NULL;
9632 struct got_reflist_object_id_map *refs_idmap = NULL;
9633 int wanted_branch_found = 0;
9635 TAILQ_INIT(&refs);
9636 TAILQ_INIT(&backup_refs);
9638 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9639 if (err)
9640 return err;
9642 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9643 if (err)
9644 goto done;
9646 if (wanted_branch_name) {
9647 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9648 wanted_branch_name += 11;
9651 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9652 got_ref_cmp_by_commit_timestamp_descending, repo);
9653 if (err)
9654 goto done;
9656 TAILQ_FOREACH(re, &backup_refs, entry) {
9657 const char *refname = got_ref_get_name(re->ref);
9658 char *slash;
9660 err = check_cancelled(NULL);
9661 if (err)
9662 break;
9664 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9665 if (err)
9666 break;
9668 err = got_object_open_as_commit(&old_commit, repo,
9669 old_commit_id);
9670 if (err)
9671 break;
9673 if (strncmp(backup_ref_prefix, refname,
9674 backup_ref_prefix_len) == 0)
9675 refname += backup_ref_prefix_len;
9677 while (refname[0] == '/')
9678 refname++;
9680 branch_name = strdup(refname);
9681 if (branch_name == NULL) {
9682 err = got_error_from_errno("strdup");
9683 break;
9685 slash = strrchr(branch_name, '/');
9686 if (slash) {
9687 *slash = '\0';
9688 refname += strlen(branch_name) + 1;
9691 if (wanted_branch_name == NULL ||
9692 strcmp(wanted_branch_name, branch_name) == 0) {
9693 wanted_branch_found = 1;
9694 if (delete) {
9695 err = delete_backup_ref(re->ref,
9696 old_commit_id, repo);
9697 } else {
9698 err = print_backup_ref(branch_name, refname,
9699 old_commit_id, old_commit, refs_idmap,
9700 repo);
9702 if (err)
9703 break;
9706 free(old_commit_id);
9707 old_commit_id = NULL;
9708 free(branch_name);
9709 branch_name = NULL;
9710 got_object_commit_close(old_commit);
9711 old_commit = NULL;
9714 if (wanted_branch_name && !wanted_branch_found) {
9715 err = got_error_fmt(GOT_ERR_NOT_REF,
9716 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9718 done:
9719 if (refs_idmap)
9720 got_reflist_object_id_map_free(refs_idmap);
9721 got_ref_list_free(&refs);
9722 got_ref_list_free(&backup_refs);
9723 free(old_commit_id);
9724 free(branch_name);
9725 if (old_commit)
9726 got_object_commit_close(old_commit);
9727 return err;
9730 static const struct got_error *
9731 abort_progress(void *arg, unsigned char status, const char *path)
9734 * Unversioned files should not clutter progress output when
9735 * an operation is aborted.
9737 if (status == GOT_STATUS_UNVERSIONED)
9738 return NULL;
9740 return update_progress(arg, status, path);
9743 static const struct got_error *
9744 cmd_rebase(int argc, char *argv[])
9746 const struct got_error *error = NULL;
9747 struct got_worktree *worktree = NULL;
9748 struct got_repository *repo = NULL;
9749 struct got_fileindex *fileindex = NULL;
9750 char *cwd = NULL;
9751 struct got_reference *branch = NULL;
9752 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9753 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9754 struct got_object_id *resume_commit_id = NULL;
9755 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9756 struct got_commit_object *commit = NULL;
9757 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9758 int histedit_in_progress = 0, merge_in_progress = 0;
9759 int create_backup = 1, list_backups = 0, delete_backups = 0;
9760 struct got_object_id_queue commits;
9761 struct got_pathlist_head merged_paths;
9762 const struct got_object_id_queue *parent_ids;
9763 struct got_object_qid *qid, *pid;
9764 struct got_update_progress_arg upa;
9765 int *pack_fds = NULL;
9767 STAILQ_INIT(&commits);
9768 TAILQ_INIT(&merged_paths);
9769 memset(&upa, 0, sizeof(upa));
9771 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9772 switch (ch) {
9773 case 'a':
9774 abort_rebase = 1;
9775 break;
9776 case 'c':
9777 continue_rebase = 1;
9778 break;
9779 case 'l':
9780 list_backups = 1;
9781 break;
9782 case 'X':
9783 delete_backups = 1;
9784 break;
9785 default:
9786 usage_rebase();
9787 /* NOTREACHED */
9791 argc -= optind;
9792 argv += optind;
9794 #ifndef PROFILE
9795 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9796 "unveil", NULL) == -1)
9797 err(1, "pledge");
9798 #endif
9799 if (list_backups) {
9800 if (abort_rebase)
9801 option_conflict('l', 'a');
9802 if (continue_rebase)
9803 option_conflict('l', 'c');
9804 if (delete_backups)
9805 option_conflict('l', 'X');
9806 if (argc != 0 && argc != 1)
9807 usage_rebase();
9808 } else if (delete_backups) {
9809 if (abort_rebase)
9810 option_conflict('X', 'a');
9811 if (continue_rebase)
9812 option_conflict('X', 'c');
9813 if (list_backups)
9814 option_conflict('l', 'X');
9815 if (argc != 0 && argc != 1)
9816 usage_rebase();
9817 } else {
9818 if (abort_rebase && continue_rebase)
9819 usage_rebase();
9820 else if (abort_rebase || continue_rebase) {
9821 if (argc != 0)
9822 usage_rebase();
9823 } else if (argc != 1)
9824 usage_rebase();
9827 cwd = getcwd(NULL, 0);
9828 if (cwd == NULL) {
9829 error = got_error_from_errno("getcwd");
9830 goto done;
9833 error = got_repo_pack_fds_open(&pack_fds);
9834 if (error != NULL)
9835 goto done;
9837 error = got_worktree_open(&worktree, cwd);
9838 if (error) {
9839 if (list_backups || delete_backups) {
9840 if (error->code != GOT_ERR_NOT_WORKTREE)
9841 goto done;
9842 } else {
9843 if (error->code == GOT_ERR_NOT_WORKTREE)
9844 error = wrap_not_worktree_error(error,
9845 "rebase", cwd);
9846 goto done;
9850 error = got_repo_open(&repo,
9851 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9852 pack_fds);
9853 if (error != NULL)
9854 goto done;
9856 error = apply_unveil(got_repo_get_path(repo), 0,
9857 worktree ? got_worktree_get_root_path(worktree) : NULL);
9858 if (error)
9859 goto done;
9861 if (list_backups || delete_backups) {
9862 error = process_backup_refs(
9863 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9864 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9865 goto done; /* nothing else to do */
9868 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9869 worktree);
9870 if (error)
9871 goto done;
9872 if (histedit_in_progress) {
9873 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9874 goto done;
9877 error = got_worktree_merge_in_progress(&merge_in_progress,
9878 worktree, repo);
9879 if (error)
9880 goto done;
9881 if (merge_in_progress) {
9882 error = got_error(GOT_ERR_MERGE_BUSY);
9883 goto done;
9886 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9887 if (error)
9888 goto done;
9890 if (abort_rebase) {
9891 if (!rebase_in_progress) {
9892 error = got_error(GOT_ERR_NOT_REBASING);
9893 goto done;
9895 error = got_worktree_rebase_continue(&resume_commit_id,
9896 &new_base_branch, &tmp_branch, &branch, &fileindex,
9897 worktree, repo);
9898 if (error)
9899 goto done;
9900 printf("Switching work tree to %s\n",
9901 got_ref_get_symref_target(new_base_branch));
9902 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9903 new_base_branch, abort_progress, &upa);
9904 if (error)
9905 goto done;
9906 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9907 print_merge_progress_stats(&upa);
9908 goto done; /* nothing else to do */
9911 if (continue_rebase) {
9912 if (!rebase_in_progress) {
9913 error = got_error(GOT_ERR_NOT_REBASING);
9914 goto done;
9916 error = got_worktree_rebase_continue(&resume_commit_id,
9917 &new_base_branch, &tmp_branch, &branch, &fileindex,
9918 worktree, repo);
9919 if (error)
9920 goto done;
9922 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9923 resume_commit_id, repo);
9924 if (error)
9925 goto done;
9927 yca_id = got_object_id_dup(resume_commit_id);
9928 if (yca_id == NULL) {
9929 error = got_error_from_errno("got_object_id_dup");
9930 goto done;
9932 } else {
9933 error = got_ref_open(&branch, repo, argv[0], 0);
9934 if (error != NULL)
9935 goto done;
9938 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9939 if (error)
9940 goto done;
9942 if (!continue_rebase) {
9943 struct got_object_id *base_commit_id;
9945 base_commit_id = got_worktree_get_base_commit_id(worktree);
9946 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9947 base_commit_id, branch_head_commit_id, 1, repo,
9948 check_cancelled, NULL);
9949 if (error)
9950 goto done;
9951 if (yca_id == NULL) {
9952 error = got_error_msg(GOT_ERR_ANCESTRY,
9953 "specified branch shares no common ancestry "
9954 "with work tree's branch");
9955 goto done;
9958 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9959 if (error) {
9960 if (error->code != GOT_ERR_ANCESTRY)
9961 goto done;
9962 error = NULL;
9963 } else {
9964 struct got_pathlist_head paths;
9965 printf("%s is already based on %s\n",
9966 got_ref_get_name(branch),
9967 got_worktree_get_head_ref_name(worktree));
9968 error = switch_head_ref(branch, branch_head_commit_id,
9969 worktree, repo);
9970 if (error)
9971 goto done;
9972 error = got_worktree_set_base_commit_id(worktree, repo,
9973 branch_head_commit_id);
9974 if (error)
9975 goto done;
9976 TAILQ_INIT(&paths);
9977 error = got_pathlist_append(&paths, "", NULL);
9978 if (error)
9979 goto done;
9980 error = got_worktree_checkout_files(worktree,
9981 &paths, repo, update_progress, &upa,
9982 check_cancelled, NULL);
9983 got_pathlist_free(&paths);
9984 if (error)
9985 goto done;
9986 if (upa.did_something) {
9987 char *id_str;
9988 error = got_object_id_str(&id_str,
9989 branch_head_commit_id);
9990 if (error)
9991 goto done;
9992 printf("Updated to %s: %s\n",
9993 got_worktree_get_head_ref_name(worktree),
9994 id_str);
9995 free(id_str);
9996 } else
9997 printf("Already up-to-date\n");
9998 print_update_progress_stats(&upa);
9999 goto done;
10003 commit_id = branch_head_commit_id;
10004 error = got_object_open_as_commit(&commit, repo, commit_id);
10005 if (error)
10006 goto done;
10008 parent_ids = got_object_commit_get_parent_ids(commit);
10009 pid = STAILQ_FIRST(parent_ids);
10010 if (pid == NULL) {
10011 error = got_error(GOT_ERR_EMPTY_REBASE);
10012 goto done;
10014 error = collect_commits(&commits, commit_id, &pid->id,
10015 yca_id, got_worktree_get_path_prefix(worktree),
10016 GOT_ERR_REBASE_PATH, repo);
10017 got_object_commit_close(commit);
10018 commit = NULL;
10019 if (error)
10020 goto done;
10022 if (!continue_rebase) {
10023 error = got_worktree_rebase_prepare(&new_base_branch,
10024 &tmp_branch, &fileindex, worktree, branch, repo);
10025 if (error)
10026 goto done;
10029 if (STAILQ_EMPTY(&commits)) {
10030 if (continue_rebase) {
10031 error = rebase_complete(worktree, fileindex,
10032 branch, new_base_branch, tmp_branch, repo,
10033 create_backup);
10034 goto done;
10035 } else {
10036 /* Fast-forward the reference of the branch. */
10037 struct got_object_id *new_head_commit_id;
10038 char *id_str;
10039 error = got_ref_resolve(&new_head_commit_id, repo,
10040 new_base_branch);
10041 if (error)
10042 goto done;
10043 error = got_object_id_str(&id_str, new_head_commit_id);
10044 printf("Forwarding %s to commit %s\n",
10045 got_ref_get_name(branch), id_str);
10046 free(id_str);
10047 error = got_ref_change_ref(branch,
10048 new_head_commit_id);
10049 if (error)
10050 goto done;
10051 /* No backup needed since objects did not change. */
10052 create_backup = 0;
10056 pid = NULL;
10057 STAILQ_FOREACH(qid, &commits, entry) {
10059 commit_id = &qid->id;
10060 parent_id = pid ? &pid->id : yca_id;
10061 pid = qid;
10063 memset(&upa, 0, sizeof(upa));
10064 error = got_worktree_rebase_merge_files(&merged_paths,
10065 worktree, fileindex, parent_id, commit_id, repo,
10066 update_progress, &upa, check_cancelled, NULL);
10067 if (error)
10068 goto done;
10070 print_merge_progress_stats(&upa);
10071 if (upa.conflicts > 0 || upa.missing > 0 ||
10072 upa.not_deleted > 0 || upa.unversioned > 0) {
10073 if (upa.conflicts > 0) {
10074 error = show_rebase_merge_conflict(&qid->id,
10075 repo);
10076 if (error)
10077 goto done;
10079 got_worktree_rebase_pathlist_free(&merged_paths);
10080 break;
10083 error = rebase_commit(&merged_paths, worktree, fileindex,
10084 tmp_branch, commit_id, repo);
10085 got_worktree_rebase_pathlist_free(&merged_paths);
10086 if (error)
10087 goto done;
10090 if (upa.conflicts > 0 || upa.missing > 0 ||
10091 upa.not_deleted > 0 || upa.unversioned > 0) {
10092 error = got_worktree_rebase_postpone(worktree, fileindex);
10093 if (error)
10094 goto done;
10095 if (upa.conflicts > 0 && upa.missing == 0 &&
10096 upa.not_deleted == 0 && upa.unversioned == 0) {
10097 error = got_error_msg(GOT_ERR_CONFLICTS,
10098 "conflicts must be resolved before rebasing "
10099 "can continue");
10100 } else if (upa.conflicts > 0) {
10101 error = got_error_msg(GOT_ERR_CONFLICTS,
10102 "conflicts must be resolved before rebasing "
10103 "can continue; changes destined for some "
10104 "files were not yet merged and should be "
10105 "merged manually if required before the "
10106 "rebase operation is continued");
10107 } else {
10108 error = got_error_msg(GOT_ERR_CONFLICTS,
10109 "changes destined for some files were not "
10110 "yet merged and should be merged manually "
10111 "if required before the rebase operation "
10112 "is continued");
10114 } else
10115 error = rebase_complete(worktree, fileindex, branch,
10116 new_base_branch, tmp_branch, repo, create_backup);
10117 done:
10118 got_object_id_queue_free(&commits);
10119 free(branch_head_commit_id);
10120 free(resume_commit_id);
10121 free(yca_id);
10122 if (commit)
10123 got_object_commit_close(commit);
10124 if (branch)
10125 got_ref_close(branch);
10126 if (new_base_branch)
10127 got_ref_close(new_base_branch);
10128 if (tmp_branch)
10129 got_ref_close(tmp_branch);
10130 if (worktree)
10131 got_worktree_close(worktree);
10132 if (repo) {
10133 const struct got_error *close_err = got_repo_close(repo);
10134 if (error == NULL)
10135 error = close_err;
10137 if (pack_fds) {
10138 const struct got_error *pack_err =
10139 got_repo_pack_fds_close(pack_fds);
10140 if (error == NULL)
10141 error = pack_err;
10143 return error;
10146 __dead static void
10147 usage_histedit(void)
10149 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10150 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10151 getprogname());
10152 exit(1);
10155 #define GOT_HISTEDIT_PICK 'p'
10156 #define GOT_HISTEDIT_EDIT 'e'
10157 #define GOT_HISTEDIT_FOLD 'f'
10158 #define GOT_HISTEDIT_DROP 'd'
10159 #define GOT_HISTEDIT_MESG 'm'
10161 static const struct got_histedit_cmd {
10162 unsigned char code;
10163 const char *name;
10164 const char *desc;
10165 } got_histedit_cmds[] = {
10166 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10167 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10168 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10169 "be used" },
10170 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10171 { GOT_HISTEDIT_MESG, "mesg",
10172 "single-line log message for commit above (open editor if empty)" },
10175 struct got_histedit_list_entry {
10176 TAILQ_ENTRY(got_histedit_list_entry) entry;
10177 struct got_object_id *commit_id;
10178 const struct got_histedit_cmd *cmd;
10179 char *logmsg;
10181 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10183 static const struct got_error *
10184 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10185 FILE *f, struct got_repository *repo)
10187 const struct got_error *err = NULL;
10188 char *logmsg = NULL, *id_str = NULL;
10189 struct got_commit_object *commit = NULL;
10190 int n;
10192 err = got_object_open_as_commit(&commit, repo, commit_id);
10193 if (err)
10194 goto done;
10196 err = get_short_logmsg(&logmsg, 34, commit);
10197 if (err)
10198 goto done;
10200 err = got_object_id_str(&id_str, commit_id);
10201 if (err)
10202 goto done;
10204 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10205 if (n < 0)
10206 err = got_ferror(f, GOT_ERR_IO);
10207 done:
10208 if (commit)
10209 got_object_commit_close(commit);
10210 free(id_str);
10211 free(logmsg);
10212 return err;
10215 static const struct got_error *
10216 histedit_write_commit_list(struct got_object_id_queue *commits,
10217 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10218 struct got_repository *repo)
10220 const struct got_error *err = NULL;
10221 struct got_object_qid *qid;
10222 const char *histedit_cmd = NULL;
10224 if (STAILQ_EMPTY(commits))
10225 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10227 STAILQ_FOREACH(qid, commits, entry) {
10228 histedit_cmd = got_histedit_cmds[0].name;
10229 if (edit_only)
10230 histedit_cmd = "edit";
10231 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10232 histedit_cmd = "fold";
10233 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10234 if (err)
10235 break;
10236 if (edit_logmsg_only) {
10237 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10238 if (n < 0) {
10239 err = got_ferror(f, GOT_ERR_IO);
10240 break;
10245 return err;
10248 static const struct got_error *
10249 write_cmd_list(FILE *f, const char *branch_name,
10250 struct got_object_id_queue *commits)
10252 const struct got_error *err = NULL;
10253 size_t i;
10254 int n;
10255 char *id_str;
10256 struct got_object_qid *qid;
10258 qid = STAILQ_FIRST(commits);
10259 err = got_object_id_str(&id_str, &qid->id);
10260 if (err)
10261 return err;
10263 n = fprintf(f,
10264 "# Editing the history of branch '%s' starting at\n"
10265 "# commit %s\n"
10266 "# Commits will be processed in order from top to "
10267 "bottom of this file.\n", branch_name, id_str);
10268 if (n < 0) {
10269 err = got_ferror(f, GOT_ERR_IO);
10270 goto done;
10273 n = fprintf(f, "# Available histedit commands:\n");
10274 if (n < 0) {
10275 err = got_ferror(f, GOT_ERR_IO);
10276 goto done;
10279 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10280 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10281 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10282 cmd->desc);
10283 if (n < 0) {
10284 err = got_ferror(f, GOT_ERR_IO);
10285 break;
10288 done:
10289 free(id_str);
10290 return err;
10293 static const struct got_error *
10294 histedit_syntax_error(int lineno)
10296 static char msg[42];
10297 int ret;
10299 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10300 lineno);
10301 if (ret == -1 || ret >= sizeof(msg))
10302 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10304 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10307 static const struct got_error *
10308 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10309 char *logmsg, struct got_repository *repo)
10311 const struct got_error *err;
10312 struct got_commit_object *folded_commit = NULL;
10313 char *id_str, *folded_logmsg = NULL;
10315 err = got_object_id_str(&id_str, hle->commit_id);
10316 if (err)
10317 return err;
10319 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10320 if (err)
10321 goto done;
10323 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10324 if (err)
10325 goto done;
10326 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10327 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10328 folded_logmsg) == -1) {
10329 err = got_error_from_errno("asprintf");
10331 done:
10332 if (folded_commit)
10333 got_object_commit_close(folded_commit);
10334 free(id_str);
10335 free(folded_logmsg);
10336 return err;
10339 static struct got_histedit_list_entry *
10340 get_folded_commits(struct got_histedit_list_entry *hle)
10342 struct got_histedit_list_entry *prev, *folded = NULL;
10344 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10345 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10346 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10347 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10348 folded = prev;
10349 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10352 return folded;
10355 static const struct got_error *
10356 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10357 struct got_repository *repo)
10359 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10360 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10361 const struct got_error *err = NULL;
10362 struct got_commit_object *commit = NULL;
10363 int logmsg_len;
10364 int fd;
10365 struct got_histedit_list_entry *folded = NULL;
10367 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10368 if (err)
10369 return err;
10371 folded = get_folded_commits(hle);
10372 if (folded) {
10373 while (folded != hle) {
10374 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10375 folded = TAILQ_NEXT(folded, entry);
10376 continue;
10378 err = append_folded_commit_msg(&new_msg, folded,
10379 logmsg, repo);
10380 if (err)
10381 goto done;
10382 free(logmsg);
10383 logmsg = new_msg;
10384 folded = TAILQ_NEXT(folded, entry);
10388 err = got_object_id_str(&id_str, hle->commit_id);
10389 if (err)
10390 goto done;
10391 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10392 if (err)
10393 goto done;
10394 logmsg_len = asprintf(&new_msg,
10395 "%s\n# original log message of commit %s: %s",
10396 logmsg ? logmsg : "", id_str, orig_logmsg);
10397 if (logmsg_len == -1) {
10398 err = got_error_from_errno("asprintf");
10399 goto done;
10401 free(logmsg);
10402 logmsg = new_msg;
10404 err = got_object_id_str(&id_str, hle->commit_id);
10405 if (err)
10406 goto done;
10408 err = got_opentemp_named_fd(&logmsg_path, &fd,
10409 GOT_TMPDIR_STR "/got-logmsg");
10410 if (err)
10411 goto done;
10413 write(fd, logmsg, logmsg_len);
10414 close(fd);
10416 err = get_editor(&editor);
10417 if (err)
10418 goto done;
10420 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10421 logmsg_len, 0);
10422 if (err) {
10423 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10424 goto done;
10425 err = NULL;
10426 hle->logmsg = strdup(new_msg);
10427 if (hle->logmsg == NULL)
10428 err = got_error_from_errno("strdup");
10430 done:
10431 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10432 err = got_error_from_errno2("unlink", logmsg_path);
10433 free(logmsg_path);
10434 free(logmsg);
10435 free(orig_logmsg);
10436 free(editor);
10437 if (commit)
10438 got_object_commit_close(commit);
10439 return err;
10442 static const struct got_error *
10443 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10444 FILE *f, struct got_repository *repo)
10446 const struct got_error *err = NULL;
10447 char *line = NULL, *p, *end;
10448 size_t i, size;
10449 ssize_t len;
10450 int lineno = 0;
10451 const struct got_histedit_cmd *cmd;
10452 struct got_object_id *commit_id = NULL;
10453 struct got_histedit_list_entry *hle = NULL;
10455 for (;;) {
10456 len = getline(&line, &size, f);
10457 if (len == -1) {
10458 const struct got_error *getline_err;
10459 if (feof(f))
10460 break;
10461 getline_err = got_error_from_errno("getline");
10462 err = got_ferror(f, getline_err->code);
10463 break;
10465 lineno++;
10466 p = line;
10467 while (isspace((unsigned char)p[0]))
10468 p++;
10469 if (p[0] == '#' || p[0] == '\0') {
10470 free(line);
10471 line = NULL;
10472 continue;
10474 cmd = NULL;
10475 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10476 cmd = &got_histedit_cmds[i];
10477 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10478 isspace((unsigned char)p[strlen(cmd->name)])) {
10479 p += strlen(cmd->name);
10480 break;
10482 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10483 p++;
10484 break;
10487 if (i == nitems(got_histedit_cmds)) {
10488 err = histedit_syntax_error(lineno);
10489 break;
10491 while (isspace((unsigned char)p[0]))
10492 p++;
10493 if (cmd->code == GOT_HISTEDIT_MESG) {
10494 if (hle == NULL || hle->logmsg != NULL) {
10495 err = got_error(GOT_ERR_HISTEDIT_CMD);
10496 break;
10498 if (p[0] == '\0') {
10499 err = histedit_edit_logmsg(hle, repo);
10500 if (err)
10501 break;
10502 } else {
10503 hle->logmsg = strdup(p);
10504 if (hle->logmsg == NULL) {
10505 err = got_error_from_errno("strdup");
10506 break;
10509 free(line);
10510 line = NULL;
10511 continue;
10512 } else {
10513 end = p;
10514 while (end[0] && !isspace((unsigned char)end[0]))
10515 end++;
10516 *end = '\0';
10518 err = got_object_resolve_id_str(&commit_id, repo, p);
10519 if (err) {
10520 /* override error code */
10521 err = histedit_syntax_error(lineno);
10522 break;
10525 hle = malloc(sizeof(*hle));
10526 if (hle == NULL) {
10527 err = got_error_from_errno("malloc");
10528 break;
10530 hle->cmd = cmd;
10531 hle->commit_id = commit_id;
10532 hle->logmsg = NULL;
10533 commit_id = NULL;
10534 free(line);
10535 line = NULL;
10536 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10539 free(line);
10540 free(commit_id);
10541 return err;
10544 static const struct got_error *
10545 histedit_check_script(struct got_histedit_list *histedit_cmds,
10546 struct got_object_id_queue *commits, struct got_repository *repo)
10548 const struct got_error *err = NULL;
10549 struct got_object_qid *qid;
10550 struct got_histedit_list_entry *hle;
10551 static char msg[92];
10552 char *id_str;
10554 if (TAILQ_EMPTY(histedit_cmds))
10555 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10556 "histedit script contains no commands");
10557 if (STAILQ_EMPTY(commits))
10558 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10560 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10561 struct got_histedit_list_entry *hle2;
10562 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10563 if (hle == hle2)
10564 continue;
10565 if (got_object_id_cmp(hle->commit_id,
10566 hle2->commit_id) != 0)
10567 continue;
10568 err = got_object_id_str(&id_str, hle->commit_id);
10569 if (err)
10570 return err;
10571 snprintf(msg, sizeof(msg), "commit %s is listed "
10572 "more than once in histedit script", id_str);
10573 free(id_str);
10574 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10578 STAILQ_FOREACH(qid, commits, entry) {
10579 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10580 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10581 break;
10583 if (hle == NULL) {
10584 err = got_object_id_str(&id_str, &qid->id);
10585 if (err)
10586 return err;
10587 snprintf(msg, sizeof(msg),
10588 "commit %s missing from histedit script", id_str);
10589 free(id_str);
10590 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10594 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10595 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10596 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10597 "last commit in histedit script cannot be folded");
10599 return NULL;
10602 static const struct got_error *
10603 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10604 const char *path, struct got_object_id_queue *commits,
10605 struct got_repository *repo)
10607 const struct got_error *err = NULL;
10608 char *editor;
10609 FILE *f = NULL;
10611 err = get_editor(&editor);
10612 if (err)
10613 return err;
10615 if (spawn_editor(editor, path) == -1) {
10616 err = got_error_from_errno("failed spawning editor");
10617 goto done;
10620 f = fopen(path, "re");
10621 if (f == NULL) {
10622 err = got_error_from_errno("fopen");
10623 goto done;
10625 err = histedit_parse_list(histedit_cmds, f, repo);
10626 if (err)
10627 goto done;
10629 err = histedit_check_script(histedit_cmds, commits, repo);
10630 done:
10631 if (f && fclose(f) == EOF && err == NULL)
10632 err = got_error_from_errno("fclose");
10633 free(editor);
10634 return err;
10637 static const struct got_error *
10638 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10639 struct got_object_id_queue *, const char *, const char *,
10640 struct got_repository *);
10642 static const struct got_error *
10643 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10644 struct got_object_id_queue *commits, const char *branch_name,
10645 int edit_logmsg_only, int fold_only, int edit_only,
10646 struct got_repository *repo)
10648 const struct got_error *err;
10649 FILE *f = NULL;
10650 char *path = NULL;
10652 err = got_opentemp_named(&path, &f, "got-histedit");
10653 if (err)
10654 return err;
10656 err = write_cmd_list(f, branch_name, commits);
10657 if (err)
10658 goto done;
10660 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10661 fold_only, edit_only, repo);
10662 if (err)
10663 goto done;
10665 if (edit_logmsg_only || fold_only || edit_only) {
10666 rewind(f);
10667 err = histedit_parse_list(histedit_cmds, f, repo);
10668 } else {
10669 if (fclose(f) == EOF) {
10670 err = got_error_from_errno("fclose");
10671 goto done;
10673 f = NULL;
10674 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10675 if (err) {
10676 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10677 err->code != GOT_ERR_HISTEDIT_CMD)
10678 goto done;
10679 err = histedit_edit_list_retry(histedit_cmds, err,
10680 commits, path, branch_name, repo);
10683 done:
10684 if (f && fclose(f) == EOF && err == NULL)
10685 err = got_error_from_errno("fclose");
10686 if (path && unlink(path) != 0 && err == NULL)
10687 err = got_error_from_errno2("unlink", path);
10688 free(path);
10689 return err;
10692 static const struct got_error *
10693 histedit_save_list(struct got_histedit_list *histedit_cmds,
10694 struct got_worktree *worktree, struct got_repository *repo)
10696 const struct got_error *err = NULL;
10697 char *path = NULL;
10698 FILE *f = NULL;
10699 struct got_histedit_list_entry *hle;
10700 struct got_commit_object *commit = NULL;
10702 err = got_worktree_get_histedit_script_path(&path, worktree);
10703 if (err)
10704 return err;
10706 f = fopen(path, "we");
10707 if (f == NULL) {
10708 err = got_error_from_errno2("fopen", path);
10709 goto done;
10711 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10712 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10713 repo);
10714 if (err)
10715 break;
10717 if (hle->logmsg) {
10718 int n = fprintf(f, "%c %s\n",
10719 GOT_HISTEDIT_MESG, hle->logmsg);
10720 if (n < 0) {
10721 err = got_ferror(f, GOT_ERR_IO);
10722 break;
10726 done:
10727 if (f && fclose(f) == EOF && err == NULL)
10728 err = got_error_from_errno("fclose");
10729 free(path);
10730 if (commit)
10731 got_object_commit_close(commit);
10732 return err;
10735 static void
10736 histedit_free_list(struct got_histedit_list *histedit_cmds)
10738 struct got_histedit_list_entry *hle;
10740 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10741 TAILQ_REMOVE(histedit_cmds, hle, entry);
10742 free(hle);
10746 static const struct got_error *
10747 histedit_load_list(struct got_histedit_list *histedit_cmds,
10748 const char *path, struct got_repository *repo)
10750 const struct got_error *err = NULL;
10751 FILE *f = NULL;
10753 f = fopen(path, "re");
10754 if (f == NULL) {
10755 err = got_error_from_errno2("fopen", path);
10756 goto done;
10759 err = histedit_parse_list(histedit_cmds, f, repo);
10760 done:
10761 if (f && fclose(f) == EOF && err == NULL)
10762 err = got_error_from_errno("fclose");
10763 return err;
10766 static const struct got_error *
10767 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10768 const struct got_error *edit_err, struct got_object_id_queue *commits,
10769 const char *path, const char *branch_name, struct got_repository *repo)
10771 const struct got_error *err = NULL, *prev_err = edit_err;
10772 int resp = ' ';
10774 while (resp != 'c' && resp != 'r' && resp != 'a') {
10775 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10776 "or (a)bort: ", getprogname(), prev_err->msg);
10777 resp = getchar();
10778 if (resp == '\n')
10779 resp = getchar();
10780 if (resp == 'c') {
10781 histedit_free_list(histedit_cmds);
10782 err = histedit_run_editor(histedit_cmds, path, commits,
10783 repo);
10784 if (err) {
10785 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10786 err->code != GOT_ERR_HISTEDIT_CMD)
10787 break;
10788 prev_err = err;
10789 resp = ' ';
10790 continue;
10792 break;
10793 } else if (resp == 'r') {
10794 histedit_free_list(histedit_cmds);
10795 err = histedit_edit_script(histedit_cmds,
10796 commits, branch_name, 0, 0, 0, repo);
10797 if (err) {
10798 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10799 err->code != GOT_ERR_HISTEDIT_CMD)
10800 break;
10801 prev_err = err;
10802 resp = ' ';
10803 continue;
10805 break;
10806 } else if (resp == 'a') {
10807 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10808 break;
10809 } else
10810 printf("invalid response '%c'\n", resp);
10813 return err;
10816 static const struct got_error *
10817 histedit_complete(struct got_worktree *worktree,
10818 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10819 struct got_reference *branch, struct got_repository *repo)
10821 printf("Switching work tree to %s\n",
10822 got_ref_get_symref_target(branch));
10823 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10824 branch, repo);
10827 static const struct got_error *
10828 show_histedit_progress(struct got_commit_object *commit,
10829 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10831 const struct got_error *err;
10832 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10834 err = got_object_id_str(&old_id_str, hle->commit_id);
10835 if (err)
10836 goto done;
10838 if (new_id) {
10839 err = got_object_id_str(&new_id_str, new_id);
10840 if (err)
10841 goto done;
10844 old_id_str[12] = '\0';
10845 if (new_id_str)
10846 new_id_str[12] = '\0';
10848 if (hle->logmsg) {
10849 logmsg = strdup(hle->logmsg);
10850 if (logmsg == NULL) {
10851 err = got_error_from_errno("strdup");
10852 goto done;
10854 trim_logmsg(logmsg, 42);
10855 } else {
10856 err = get_short_logmsg(&logmsg, 42, commit);
10857 if (err)
10858 goto done;
10861 switch (hle->cmd->code) {
10862 case GOT_HISTEDIT_PICK:
10863 case GOT_HISTEDIT_EDIT:
10864 printf("%s -> %s: %s\n", old_id_str,
10865 new_id_str ? new_id_str : "no-op change", logmsg);
10866 break;
10867 case GOT_HISTEDIT_DROP:
10868 case GOT_HISTEDIT_FOLD:
10869 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10870 logmsg);
10871 break;
10872 default:
10873 break;
10875 done:
10876 free(old_id_str);
10877 free(new_id_str);
10878 return err;
10881 static const struct got_error *
10882 histedit_commit(struct got_pathlist_head *merged_paths,
10883 struct got_worktree *worktree, struct got_fileindex *fileindex,
10884 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10885 struct got_repository *repo)
10887 const struct got_error *err;
10888 struct got_commit_object *commit;
10889 struct got_object_id *new_commit_id;
10891 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10892 && hle->logmsg == NULL) {
10893 err = histedit_edit_logmsg(hle, repo);
10894 if (err)
10895 return err;
10898 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10899 if (err)
10900 return err;
10902 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10903 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10904 hle->logmsg, repo);
10905 if (err) {
10906 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10907 goto done;
10908 err = show_histedit_progress(commit, hle, NULL);
10909 } else {
10910 err = show_histedit_progress(commit, hle, new_commit_id);
10911 free(new_commit_id);
10913 done:
10914 got_object_commit_close(commit);
10915 return err;
10918 static const struct got_error *
10919 histedit_skip_commit(struct got_histedit_list_entry *hle,
10920 struct got_worktree *worktree, struct got_repository *repo)
10922 const struct got_error *error;
10923 struct got_commit_object *commit;
10925 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10926 repo);
10927 if (error)
10928 return error;
10930 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10931 if (error)
10932 return error;
10934 error = show_histedit_progress(commit, hle, NULL);
10935 got_object_commit_close(commit);
10936 return error;
10939 static const struct got_error *
10940 check_local_changes(void *arg, unsigned char status,
10941 unsigned char staged_status, const char *path,
10942 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10943 struct got_object_id *commit_id, int dirfd, const char *de_name)
10945 int *have_local_changes = arg;
10947 switch (status) {
10948 case GOT_STATUS_ADD:
10949 case GOT_STATUS_DELETE:
10950 case GOT_STATUS_MODIFY:
10951 case GOT_STATUS_CONFLICT:
10952 *have_local_changes = 1;
10953 return got_error(GOT_ERR_CANCELLED);
10954 default:
10955 break;
10958 switch (staged_status) {
10959 case GOT_STATUS_ADD:
10960 case GOT_STATUS_DELETE:
10961 case GOT_STATUS_MODIFY:
10962 *have_local_changes = 1;
10963 return got_error(GOT_ERR_CANCELLED);
10964 default:
10965 break;
10968 return NULL;
10971 static const struct got_error *
10972 cmd_histedit(int argc, char *argv[])
10974 const struct got_error *error = NULL;
10975 struct got_worktree *worktree = NULL;
10976 struct got_fileindex *fileindex = NULL;
10977 struct got_repository *repo = NULL;
10978 char *cwd = NULL;
10979 struct got_reference *branch = NULL;
10980 struct got_reference *tmp_branch = NULL;
10981 struct got_object_id *resume_commit_id = NULL;
10982 struct got_object_id *base_commit_id = NULL;
10983 struct got_object_id *head_commit_id = NULL;
10984 struct got_commit_object *commit = NULL;
10985 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10986 struct got_update_progress_arg upa;
10987 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10988 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10989 int list_backups = 0, delete_backups = 0;
10990 const char *edit_script_path = NULL;
10991 struct got_object_id_queue commits;
10992 struct got_pathlist_head merged_paths;
10993 const struct got_object_id_queue *parent_ids;
10994 struct got_object_qid *pid;
10995 struct got_histedit_list histedit_cmds;
10996 struct got_histedit_list_entry *hle;
10997 int *pack_fds = NULL;
10999 STAILQ_INIT(&commits);
11000 TAILQ_INIT(&histedit_cmds);
11001 TAILQ_INIT(&merged_paths);
11002 memset(&upa, 0, sizeof(upa));
11004 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11005 switch (ch) {
11006 case 'a':
11007 abort_edit = 1;
11008 break;
11009 case 'c':
11010 continue_edit = 1;
11011 break;
11012 case 'e':
11013 edit_only = 1;
11014 break;
11015 case 'f':
11016 fold_only = 1;
11017 break;
11018 case 'F':
11019 edit_script_path = optarg;
11020 break;
11021 case 'm':
11022 edit_logmsg_only = 1;
11023 break;
11024 case 'l':
11025 list_backups = 1;
11026 break;
11027 case 'X':
11028 delete_backups = 1;
11029 break;
11030 default:
11031 usage_histedit();
11032 /* NOTREACHED */
11036 argc -= optind;
11037 argv += optind;
11039 #ifndef PROFILE
11040 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11041 "unveil", NULL) == -1)
11042 err(1, "pledge");
11043 #endif
11044 if (abort_edit && continue_edit)
11045 option_conflict('a', 'c');
11046 if (edit_script_path && edit_logmsg_only)
11047 option_conflict('F', 'm');
11048 if (abort_edit && edit_logmsg_only)
11049 option_conflict('a', 'm');
11050 if (continue_edit && edit_logmsg_only)
11051 option_conflict('c', 'm');
11052 if (abort_edit && fold_only)
11053 option_conflict('a', 'f');
11054 if (continue_edit && fold_only)
11055 option_conflict('c', 'f');
11056 if (fold_only && edit_logmsg_only)
11057 option_conflict('f', 'm');
11058 if (edit_script_path && fold_only)
11059 option_conflict('F', 'f');
11060 if (abort_edit && edit_only)
11061 option_conflict('a', 'e');
11062 if (continue_edit && edit_only)
11063 option_conflict('c', 'e');
11064 if (edit_only && edit_logmsg_only)
11065 option_conflict('e', 'm');
11066 if (edit_script_path && edit_only)
11067 option_conflict('F', 'e');
11068 if (list_backups) {
11069 if (abort_edit)
11070 option_conflict('l', 'a');
11071 if (continue_edit)
11072 option_conflict('l', 'c');
11073 if (edit_script_path)
11074 option_conflict('l', 'F');
11075 if (edit_logmsg_only)
11076 option_conflict('l', 'm');
11077 if (fold_only)
11078 option_conflict('l', 'f');
11079 if (edit_only)
11080 option_conflict('l', 'e');
11081 if (delete_backups)
11082 option_conflict('l', 'X');
11083 if (argc != 0 && argc != 1)
11084 usage_histedit();
11085 } else if (delete_backups) {
11086 if (abort_edit)
11087 option_conflict('X', 'a');
11088 if (continue_edit)
11089 option_conflict('X', 'c');
11090 if (edit_script_path)
11091 option_conflict('X', 'F');
11092 if (edit_logmsg_only)
11093 option_conflict('X', 'm');
11094 if (fold_only)
11095 option_conflict('X', 'f');
11096 if (edit_only)
11097 option_conflict('X', 'e');
11098 if (list_backups)
11099 option_conflict('X', 'l');
11100 if (argc != 0 && argc != 1)
11101 usage_histedit();
11102 } else if (argc != 0)
11103 usage_histedit();
11106 * This command cannot apply unveil(2) in all cases because the
11107 * user may choose to run an editor to edit the histedit script
11108 * and to edit individual commit log messages.
11109 * unveil(2) traverses exec(2); if an editor is used we have to
11110 * apply unveil after edit script and log messages have been written.
11111 * XXX TODO: Make use of unveil(2) where possible.
11114 cwd = getcwd(NULL, 0);
11115 if (cwd == NULL) {
11116 error = got_error_from_errno("getcwd");
11117 goto done;
11120 error = got_repo_pack_fds_open(&pack_fds);
11121 if (error != NULL)
11122 goto done;
11124 error = got_worktree_open(&worktree, cwd);
11125 if (error) {
11126 if (list_backups || delete_backups) {
11127 if (error->code != GOT_ERR_NOT_WORKTREE)
11128 goto done;
11129 } else {
11130 if (error->code == GOT_ERR_NOT_WORKTREE)
11131 error = wrap_not_worktree_error(error,
11132 "histedit", cwd);
11133 goto done;
11137 if (list_backups || delete_backups) {
11138 error = got_repo_open(&repo,
11139 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11140 NULL, pack_fds);
11141 if (error != NULL)
11142 goto done;
11143 error = apply_unveil(got_repo_get_path(repo), 0,
11144 worktree ? got_worktree_get_root_path(worktree) : NULL);
11145 if (error)
11146 goto done;
11147 error = process_backup_refs(
11148 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11149 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11150 goto done; /* nothing else to do */
11153 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11154 NULL, pack_fds);
11155 if (error != NULL)
11156 goto done;
11158 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11159 if (error)
11160 goto done;
11161 if (rebase_in_progress) {
11162 error = got_error(GOT_ERR_REBASING);
11163 goto done;
11166 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11167 repo);
11168 if (error)
11169 goto done;
11170 if (merge_in_progress) {
11171 error = got_error(GOT_ERR_MERGE_BUSY);
11172 goto done;
11175 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11176 if (error)
11177 goto done;
11179 if (edit_in_progress && edit_logmsg_only) {
11180 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11181 "histedit operation is in progress in this "
11182 "work tree and must be continued or aborted "
11183 "before the -m option can be used");
11184 goto done;
11186 if (edit_in_progress && fold_only) {
11187 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11188 "histedit operation is in progress in this "
11189 "work tree and must be continued or aborted "
11190 "before the -f option can be used");
11191 goto done;
11193 if (edit_in_progress && edit_only) {
11194 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11195 "histedit operation is in progress in this "
11196 "work tree and must be continued or aborted "
11197 "before the -e option can be used");
11198 goto done;
11201 if (edit_in_progress && abort_edit) {
11202 error = got_worktree_histedit_continue(&resume_commit_id,
11203 &tmp_branch, &branch, &base_commit_id, &fileindex,
11204 worktree, repo);
11205 if (error)
11206 goto done;
11207 printf("Switching work tree to %s\n",
11208 got_ref_get_symref_target(branch));
11209 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11210 branch, base_commit_id, abort_progress, &upa);
11211 if (error)
11212 goto done;
11213 printf("Histedit of %s aborted\n",
11214 got_ref_get_symref_target(branch));
11215 print_merge_progress_stats(&upa);
11216 goto done; /* nothing else to do */
11217 } else if (abort_edit) {
11218 error = got_error(GOT_ERR_NOT_HISTEDIT);
11219 goto done;
11222 if (continue_edit) {
11223 char *path;
11225 if (!edit_in_progress) {
11226 error = got_error(GOT_ERR_NOT_HISTEDIT);
11227 goto done;
11230 error = got_worktree_get_histedit_script_path(&path, worktree);
11231 if (error)
11232 goto done;
11234 error = histedit_load_list(&histedit_cmds, path, repo);
11235 free(path);
11236 if (error)
11237 goto done;
11239 error = got_worktree_histedit_continue(&resume_commit_id,
11240 &tmp_branch, &branch, &base_commit_id, &fileindex,
11241 worktree, repo);
11242 if (error)
11243 goto done;
11245 error = got_ref_resolve(&head_commit_id, repo, branch);
11246 if (error)
11247 goto done;
11249 error = got_object_open_as_commit(&commit, repo,
11250 head_commit_id);
11251 if (error)
11252 goto done;
11253 parent_ids = got_object_commit_get_parent_ids(commit);
11254 pid = STAILQ_FIRST(parent_ids);
11255 if (pid == NULL) {
11256 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11257 goto done;
11259 error = collect_commits(&commits, head_commit_id, &pid->id,
11260 base_commit_id, got_worktree_get_path_prefix(worktree),
11261 GOT_ERR_HISTEDIT_PATH, repo);
11262 got_object_commit_close(commit);
11263 commit = NULL;
11264 if (error)
11265 goto done;
11266 } else {
11267 if (edit_in_progress) {
11268 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11269 goto done;
11272 error = got_ref_open(&branch, repo,
11273 got_worktree_get_head_ref_name(worktree), 0);
11274 if (error != NULL)
11275 goto done;
11277 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11278 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11279 "will not edit commit history of a branch outside "
11280 "the \"refs/heads/\" reference namespace");
11281 goto done;
11284 error = got_ref_resolve(&head_commit_id, repo, branch);
11285 got_ref_close(branch);
11286 branch = NULL;
11287 if (error)
11288 goto done;
11290 error = got_object_open_as_commit(&commit, repo,
11291 head_commit_id);
11292 if (error)
11293 goto done;
11294 parent_ids = got_object_commit_get_parent_ids(commit);
11295 pid = STAILQ_FIRST(parent_ids);
11296 if (pid == NULL) {
11297 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11298 goto done;
11300 error = collect_commits(&commits, head_commit_id, &pid->id,
11301 got_worktree_get_base_commit_id(worktree),
11302 got_worktree_get_path_prefix(worktree),
11303 GOT_ERR_HISTEDIT_PATH, repo);
11304 got_object_commit_close(commit);
11305 commit = NULL;
11306 if (error)
11307 goto done;
11309 if (STAILQ_EMPTY(&commits)) {
11310 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11311 goto done;
11314 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11315 &base_commit_id, &fileindex, worktree, repo);
11316 if (error)
11317 goto done;
11319 if (edit_script_path) {
11320 error = histedit_load_list(&histedit_cmds,
11321 edit_script_path, repo);
11322 if (error) {
11323 got_worktree_histedit_abort(worktree, fileindex,
11324 repo, branch, base_commit_id,
11325 abort_progress, &upa);
11326 print_merge_progress_stats(&upa);
11327 goto done;
11329 } else {
11330 const char *branch_name;
11331 branch_name = got_ref_get_symref_target(branch);
11332 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11333 branch_name += 11;
11334 error = histedit_edit_script(&histedit_cmds, &commits,
11335 branch_name, edit_logmsg_only, fold_only,
11336 edit_only, repo);
11337 if (error) {
11338 got_worktree_histedit_abort(worktree, fileindex,
11339 repo, branch, base_commit_id,
11340 abort_progress, &upa);
11341 print_merge_progress_stats(&upa);
11342 goto done;
11347 error = histedit_save_list(&histedit_cmds, worktree,
11348 repo);
11349 if (error) {
11350 got_worktree_histedit_abort(worktree, fileindex,
11351 repo, branch, base_commit_id,
11352 abort_progress, &upa);
11353 print_merge_progress_stats(&upa);
11354 goto done;
11359 error = histedit_check_script(&histedit_cmds, &commits, repo);
11360 if (error)
11361 goto done;
11363 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11364 if (resume_commit_id) {
11365 if (got_object_id_cmp(hle->commit_id,
11366 resume_commit_id) != 0)
11367 continue;
11369 resume_commit_id = NULL;
11370 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11371 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11372 error = histedit_skip_commit(hle, worktree,
11373 repo);
11374 if (error)
11375 goto done;
11376 } else {
11377 struct got_pathlist_head paths;
11378 int have_changes = 0;
11380 TAILQ_INIT(&paths);
11381 error = got_pathlist_append(&paths, "", NULL);
11382 if (error)
11383 goto done;
11384 error = got_worktree_status(worktree, &paths,
11385 repo, 0, check_local_changes, &have_changes,
11386 check_cancelled, NULL);
11387 got_pathlist_free(&paths);
11388 if (error) {
11389 if (error->code != GOT_ERR_CANCELLED)
11390 goto done;
11391 if (sigint_received || sigpipe_received)
11392 goto done;
11394 if (have_changes) {
11395 error = histedit_commit(NULL, worktree,
11396 fileindex, tmp_branch, hle, repo);
11397 if (error)
11398 goto done;
11399 } else {
11400 error = got_object_open_as_commit(
11401 &commit, repo, hle->commit_id);
11402 if (error)
11403 goto done;
11404 error = show_histedit_progress(commit,
11405 hle, NULL);
11406 got_object_commit_close(commit);
11407 commit = NULL;
11408 if (error)
11409 goto done;
11412 continue;
11415 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11416 error = histedit_skip_commit(hle, worktree, repo);
11417 if (error)
11418 goto done;
11419 continue;
11422 error = got_object_open_as_commit(&commit, repo,
11423 hle->commit_id);
11424 if (error)
11425 goto done;
11426 parent_ids = got_object_commit_get_parent_ids(commit);
11427 pid = STAILQ_FIRST(parent_ids);
11429 error = got_worktree_histedit_merge_files(&merged_paths,
11430 worktree, fileindex, &pid->id, hle->commit_id, repo,
11431 update_progress, &upa, check_cancelled, NULL);
11432 if (error)
11433 goto done;
11434 got_object_commit_close(commit);
11435 commit = NULL;
11437 print_merge_progress_stats(&upa);
11438 if (upa.conflicts > 0 || upa.missing > 0 ||
11439 upa.not_deleted > 0 || upa.unversioned > 0) {
11440 if (upa.conflicts > 0) {
11441 error = show_rebase_merge_conflict(
11442 hle->commit_id, repo);
11443 if (error)
11444 goto done;
11446 got_worktree_rebase_pathlist_free(&merged_paths);
11447 break;
11450 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11451 char *id_str;
11452 error = got_object_id_str(&id_str, hle->commit_id);
11453 if (error)
11454 goto done;
11455 printf("Stopping histedit for amending commit %s\n",
11456 id_str);
11457 free(id_str);
11458 got_worktree_rebase_pathlist_free(&merged_paths);
11459 error = got_worktree_histedit_postpone(worktree,
11460 fileindex);
11461 goto done;
11464 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11465 error = histedit_skip_commit(hle, worktree, repo);
11466 if (error)
11467 goto done;
11468 continue;
11471 error = histedit_commit(&merged_paths, worktree, fileindex,
11472 tmp_branch, hle, repo);
11473 got_worktree_rebase_pathlist_free(&merged_paths);
11474 if (error)
11475 goto done;
11478 if (upa.conflicts > 0 || upa.missing > 0 ||
11479 upa.not_deleted > 0 || upa.unversioned > 0) {
11480 error = got_worktree_histedit_postpone(worktree, fileindex);
11481 if (error)
11482 goto done;
11483 if (upa.conflicts > 0 && upa.missing == 0 &&
11484 upa.not_deleted == 0 && upa.unversioned == 0) {
11485 error = got_error_msg(GOT_ERR_CONFLICTS,
11486 "conflicts must be resolved before histedit "
11487 "can continue");
11488 } else if (upa.conflicts > 0) {
11489 error = got_error_msg(GOT_ERR_CONFLICTS,
11490 "conflicts must be resolved before histedit "
11491 "can continue; changes destined for some "
11492 "files were not yet merged and should be "
11493 "merged manually if required before the "
11494 "histedit operation is continued");
11495 } else {
11496 error = got_error_msg(GOT_ERR_CONFLICTS,
11497 "changes destined for some files were not "
11498 "yet merged and should be merged manually "
11499 "if required before the histedit operation "
11500 "is continued");
11502 } else
11503 error = histedit_complete(worktree, fileindex, tmp_branch,
11504 branch, repo);
11505 done:
11506 got_object_id_queue_free(&commits);
11507 histedit_free_list(&histedit_cmds);
11508 free(head_commit_id);
11509 free(base_commit_id);
11510 free(resume_commit_id);
11511 if (commit)
11512 got_object_commit_close(commit);
11513 if (branch)
11514 got_ref_close(branch);
11515 if (tmp_branch)
11516 got_ref_close(tmp_branch);
11517 if (worktree)
11518 got_worktree_close(worktree);
11519 if (repo) {
11520 const struct got_error *close_err = got_repo_close(repo);
11521 if (error == NULL)
11522 error = close_err;
11524 if (pack_fds) {
11525 const struct got_error *pack_err =
11526 got_repo_pack_fds_close(pack_fds);
11527 if (error == NULL)
11528 error = pack_err;
11530 return error;
11533 __dead static void
11534 usage_integrate(void)
11536 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11537 exit(1);
11540 static const struct got_error *
11541 cmd_integrate(int argc, char *argv[])
11543 const struct got_error *error = NULL;
11544 struct got_repository *repo = NULL;
11545 struct got_worktree *worktree = NULL;
11546 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11547 const char *branch_arg = NULL;
11548 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11549 struct got_fileindex *fileindex = NULL;
11550 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11551 int ch;
11552 struct got_update_progress_arg upa;
11553 int *pack_fds = NULL;
11555 while ((ch = getopt(argc, argv, "")) != -1) {
11556 switch (ch) {
11557 default:
11558 usage_integrate();
11559 /* NOTREACHED */
11563 argc -= optind;
11564 argv += optind;
11566 if (argc != 1)
11567 usage_integrate();
11568 branch_arg = argv[0];
11569 #ifndef PROFILE
11570 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11571 "unveil", NULL) == -1)
11572 err(1, "pledge");
11573 #endif
11574 cwd = getcwd(NULL, 0);
11575 if (cwd == NULL) {
11576 error = got_error_from_errno("getcwd");
11577 goto done;
11580 error = got_repo_pack_fds_open(&pack_fds);
11581 if (error != NULL)
11582 goto done;
11584 error = got_worktree_open(&worktree, cwd);
11585 if (error) {
11586 if (error->code == GOT_ERR_NOT_WORKTREE)
11587 error = wrap_not_worktree_error(error, "integrate",
11588 cwd);
11589 goto done;
11592 error = check_rebase_or_histedit_in_progress(worktree);
11593 if (error)
11594 goto done;
11596 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11597 NULL, pack_fds);
11598 if (error != NULL)
11599 goto done;
11601 error = apply_unveil(got_repo_get_path(repo), 0,
11602 got_worktree_get_root_path(worktree));
11603 if (error)
11604 goto done;
11606 error = check_merge_in_progress(worktree, repo);
11607 if (error)
11608 goto done;
11610 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11611 error = got_error_from_errno("asprintf");
11612 goto done;
11615 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11616 &base_branch_ref, worktree, refname, repo);
11617 if (error)
11618 goto done;
11620 refname = strdup(got_ref_get_name(branch_ref));
11621 if (refname == NULL) {
11622 error = got_error_from_errno("strdup");
11623 got_worktree_integrate_abort(worktree, fileindex, repo,
11624 branch_ref, base_branch_ref);
11625 goto done;
11627 base_refname = strdup(got_ref_get_name(base_branch_ref));
11628 if (base_refname == NULL) {
11629 error = got_error_from_errno("strdup");
11630 got_worktree_integrate_abort(worktree, fileindex, repo,
11631 branch_ref, base_branch_ref);
11632 goto done;
11635 error = got_ref_resolve(&commit_id, repo, branch_ref);
11636 if (error)
11637 goto done;
11639 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11640 if (error)
11641 goto done;
11643 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11644 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11645 "specified branch has already been integrated");
11646 got_worktree_integrate_abort(worktree, fileindex, repo,
11647 branch_ref, base_branch_ref);
11648 goto done;
11651 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11652 if (error) {
11653 if (error->code == GOT_ERR_ANCESTRY)
11654 error = got_error(GOT_ERR_REBASE_REQUIRED);
11655 got_worktree_integrate_abort(worktree, fileindex, repo,
11656 branch_ref, base_branch_ref);
11657 goto done;
11660 memset(&upa, 0, sizeof(upa));
11661 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11662 branch_ref, base_branch_ref, update_progress, &upa,
11663 check_cancelled, NULL);
11664 if (error)
11665 goto done;
11667 printf("Integrated %s into %s\n", refname, base_refname);
11668 print_update_progress_stats(&upa);
11669 done:
11670 if (repo) {
11671 const struct got_error *close_err = got_repo_close(repo);
11672 if (error == NULL)
11673 error = close_err;
11675 if (worktree)
11676 got_worktree_close(worktree);
11677 if (pack_fds) {
11678 const struct got_error *pack_err =
11679 got_repo_pack_fds_close(pack_fds);
11680 if (error == NULL)
11681 error = pack_err;
11683 free(cwd);
11684 free(base_commit_id);
11685 free(commit_id);
11686 free(refname);
11687 free(base_refname);
11688 return error;
11691 __dead static void
11692 usage_merge(void)
11694 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11695 getprogname());
11696 exit(1);
11699 static const struct got_error *
11700 cmd_merge(int argc, char *argv[])
11702 const struct got_error *error = NULL;
11703 struct got_worktree *worktree = NULL;
11704 struct got_repository *repo = NULL;
11705 struct got_fileindex *fileindex = NULL;
11706 char *cwd = NULL, *id_str = NULL, *author = NULL;
11707 struct got_reference *branch = NULL, *wt_branch = NULL;
11708 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11709 struct got_object_id *wt_branch_tip = NULL;
11710 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11711 int interrupt_merge = 0;
11712 struct got_update_progress_arg upa;
11713 struct got_object_id *merge_commit_id = NULL;
11714 char *branch_name = NULL;
11715 int *pack_fds = NULL;
11717 memset(&upa, 0, sizeof(upa));
11719 while ((ch = getopt(argc, argv, "acn")) != -1) {
11720 switch (ch) {
11721 case 'a':
11722 abort_merge = 1;
11723 break;
11724 case 'c':
11725 continue_merge = 1;
11726 break;
11727 case 'n':
11728 interrupt_merge = 1;
11729 break;
11730 default:
11731 usage_rebase();
11732 /* NOTREACHED */
11736 argc -= optind;
11737 argv += optind;
11739 #ifndef PROFILE
11740 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11741 "unveil", NULL) == -1)
11742 err(1, "pledge");
11743 #endif
11745 if (abort_merge && continue_merge)
11746 option_conflict('a', 'c');
11747 if (abort_merge || continue_merge) {
11748 if (argc != 0)
11749 usage_merge();
11750 } else if (argc != 1)
11751 usage_merge();
11753 cwd = getcwd(NULL, 0);
11754 if (cwd == NULL) {
11755 error = got_error_from_errno("getcwd");
11756 goto done;
11759 error = got_repo_pack_fds_open(&pack_fds);
11760 if (error != NULL)
11761 goto done;
11763 error = got_worktree_open(&worktree, cwd);
11764 if (error) {
11765 if (error->code == GOT_ERR_NOT_WORKTREE)
11766 error = wrap_not_worktree_error(error,
11767 "merge", cwd);
11768 goto done;
11771 error = got_repo_open(&repo,
11772 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11773 pack_fds);
11774 if (error != NULL)
11775 goto done;
11777 error = apply_unveil(got_repo_get_path(repo), 0,
11778 worktree ? got_worktree_get_root_path(worktree) : NULL);
11779 if (error)
11780 goto done;
11782 error = check_rebase_or_histedit_in_progress(worktree);
11783 if (error)
11784 goto done;
11786 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11787 repo);
11788 if (error)
11789 goto done;
11791 if (abort_merge) {
11792 if (!merge_in_progress) {
11793 error = got_error(GOT_ERR_NOT_MERGING);
11794 goto done;
11796 error = got_worktree_merge_continue(&branch_name,
11797 &branch_tip, &fileindex, worktree, repo);
11798 if (error)
11799 goto done;
11800 error = got_worktree_merge_abort(worktree, fileindex, repo,
11801 abort_progress, &upa);
11802 if (error)
11803 goto done;
11804 printf("Merge of %s aborted\n", branch_name);
11805 goto done; /* nothing else to do */
11808 error = get_author(&author, repo, worktree);
11809 if (error)
11810 goto done;
11812 if (continue_merge) {
11813 if (!merge_in_progress) {
11814 error = got_error(GOT_ERR_NOT_MERGING);
11815 goto done;
11817 error = got_worktree_merge_continue(&branch_name,
11818 &branch_tip, &fileindex, worktree, repo);
11819 if (error)
11820 goto done;
11821 } else {
11822 error = got_ref_open(&branch, repo, argv[0], 0);
11823 if (error != NULL)
11824 goto done;
11825 branch_name = strdup(got_ref_get_name(branch));
11826 if (branch_name == NULL) {
11827 error = got_error_from_errno("strdup");
11828 goto done;
11830 error = got_ref_resolve(&branch_tip, repo, branch);
11831 if (error)
11832 goto done;
11835 error = got_ref_open(&wt_branch, repo,
11836 got_worktree_get_head_ref_name(worktree), 0);
11837 if (error)
11838 goto done;
11839 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11840 if (error)
11841 goto done;
11842 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11843 wt_branch_tip, branch_tip, 0, repo,
11844 check_cancelled, NULL);
11845 if (error && error->code != GOT_ERR_ANCESTRY)
11846 goto done;
11848 if (!continue_merge) {
11849 error = check_path_prefix(wt_branch_tip, branch_tip,
11850 got_worktree_get_path_prefix(worktree),
11851 GOT_ERR_MERGE_PATH, repo);
11852 if (error)
11853 goto done;
11854 if (yca_id) {
11855 error = check_same_branch(wt_branch_tip, branch,
11856 yca_id, repo);
11857 if (error) {
11858 if (error->code != GOT_ERR_ANCESTRY)
11859 goto done;
11860 error = NULL;
11861 } else {
11862 static char msg[512];
11863 snprintf(msg, sizeof(msg),
11864 "cannot create a merge commit because "
11865 "%s is based on %s; %s can be integrated "
11866 "with 'got integrate' instead", branch_name,
11867 got_worktree_get_head_ref_name(worktree),
11868 branch_name);
11869 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11870 goto done;
11873 error = got_worktree_merge_prepare(&fileindex, worktree,
11874 branch, repo);
11875 if (error)
11876 goto done;
11878 error = got_worktree_merge_branch(worktree, fileindex,
11879 yca_id, branch_tip, repo, update_progress, &upa,
11880 check_cancelled, NULL);
11881 if (error)
11882 goto done;
11883 print_merge_progress_stats(&upa);
11884 if (!upa.did_something) {
11885 error = got_worktree_merge_abort(worktree, fileindex,
11886 repo, abort_progress, &upa);
11887 if (error)
11888 goto done;
11889 printf("Already up-to-date\n");
11890 goto done;
11894 if (interrupt_merge) {
11895 error = got_worktree_merge_postpone(worktree, fileindex);
11896 if (error)
11897 goto done;
11898 printf("Merge of %s interrupted on request\n", branch_name);
11899 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11900 upa.not_deleted > 0 || upa.unversioned > 0) {
11901 error = got_worktree_merge_postpone(worktree, fileindex);
11902 if (error)
11903 goto done;
11904 if (upa.conflicts > 0 && upa.missing == 0 &&
11905 upa.not_deleted == 0 && upa.unversioned == 0) {
11906 error = got_error_msg(GOT_ERR_CONFLICTS,
11907 "conflicts must be resolved before merging "
11908 "can continue");
11909 } else if (upa.conflicts > 0) {
11910 error = got_error_msg(GOT_ERR_CONFLICTS,
11911 "conflicts must be resolved before merging "
11912 "can continue; changes destined for some "
11913 "files were not yet merged and "
11914 "should be merged manually if required before the "
11915 "merge operation is continued");
11916 } else {
11917 error = got_error_msg(GOT_ERR_CONFLICTS,
11918 "changes destined for some "
11919 "files were not yet merged and should be "
11920 "merged manually if required before the "
11921 "merge operation is continued");
11923 goto done;
11924 } else {
11925 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11926 fileindex, author, NULL, 1, branch_tip, branch_name,
11927 repo, continue_merge ? print_status : NULL, NULL);
11928 if (error)
11929 goto done;
11930 error = got_worktree_merge_complete(worktree, fileindex, repo);
11931 if (error)
11932 goto done;
11933 error = got_object_id_str(&id_str, merge_commit_id);
11934 if (error)
11935 goto done;
11936 printf("Merged %s into %s: %s\n", branch_name,
11937 got_worktree_get_head_ref_name(worktree),
11938 id_str);
11941 done:
11942 free(id_str);
11943 free(merge_commit_id);
11944 free(author);
11945 free(branch_tip);
11946 free(branch_name);
11947 free(yca_id);
11948 if (branch)
11949 got_ref_close(branch);
11950 if (wt_branch)
11951 got_ref_close(wt_branch);
11952 if (worktree)
11953 got_worktree_close(worktree);
11954 if (repo) {
11955 const struct got_error *close_err = got_repo_close(repo);
11956 if (error == NULL)
11957 error = close_err;
11959 if (pack_fds) {
11960 const struct got_error *pack_err =
11961 got_repo_pack_fds_close(pack_fds);
11962 if (error == NULL)
11963 error = pack_err;
11965 return error;
11968 __dead static void
11969 usage_stage(void)
11971 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11972 "[-S] [file-path ...]\n",
11973 getprogname());
11974 exit(1);
11977 static const struct got_error *
11978 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11979 const char *path, struct got_object_id *blob_id,
11980 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11981 int dirfd, const char *de_name)
11983 const struct got_error *err = NULL;
11984 char *id_str = NULL;
11986 if (staged_status != GOT_STATUS_ADD &&
11987 staged_status != GOT_STATUS_MODIFY &&
11988 staged_status != GOT_STATUS_DELETE)
11989 return NULL;
11991 if (staged_status == GOT_STATUS_ADD ||
11992 staged_status == GOT_STATUS_MODIFY)
11993 err = got_object_id_str(&id_str, staged_blob_id);
11994 else
11995 err = got_object_id_str(&id_str, blob_id);
11996 if (err)
11997 return err;
11999 printf("%s %c %s\n", id_str, staged_status, path);
12000 free(id_str);
12001 return NULL;
12004 static const struct got_error *
12005 cmd_stage(int argc, char *argv[])
12007 const struct got_error *error = NULL;
12008 struct got_repository *repo = NULL;
12009 struct got_worktree *worktree = NULL;
12010 char *cwd = NULL;
12011 struct got_pathlist_head paths;
12012 struct got_pathlist_entry *pe;
12013 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12014 FILE *patch_script_file = NULL;
12015 const char *patch_script_path = NULL;
12016 struct choose_patch_arg cpa;
12017 int *pack_fds = NULL;
12019 TAILQ_INIT(&paths);
12021 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12022 switch (ch) {
12023 case 'l':
12024 list_stage = 1;
12025 break;
12026 case 'p':
12027 pflag = 1;
12028 break;
12029 case 'F':
12030 patch_script_path = optarg;
12031 break;
12032 case 'S':
12033 allow_bad_symlinks = 1;
12034 break;
12035 default:
12036 usage_stage();
12037 /* NOTREACHED */
12041 argc -= optind;
12042 argv += optind;
12044 #ifndef PROFILE
12045 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12046 "unveil", NULL) == -1)
12047 err(1, "pledge");
12048 #endif
12049 if (list_stage && (pflag || patch_script_path))
12050 errx(1, "-l option cannot be used with other options");
12051 if (patch_script_path && !pflag)
12052 errx(1, "-F option can only be used together with -p option");
12054 cwd = getcwd(NULL, 0);
12055 if (cwd == NULL) {
12056 error = got_error_from_errno("getcwd");
12057 goto done;
12060 error = got_repo_pack_fds_open(&pack_fds);
12061 if (error != NULL)
12062 goto done;
12064 error = got_worktree_open(&worktree, cwd);
12065 if (error) {
12066 if (error->code == GOT_ERR_NOT_WORKTREE)
12067 error = wrap_not_worktree_error(error, "stage", cwd);
12068 goto done;
12071 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12072 NULL, pack_fds);
12073 if (error != NULL)
12074 goto done;
12076 if (patch_script_path) {
12077 patch_script_file = fopen(patch_script_path, "re");
12078 if (patch_script_file == NULL) {
12079 error = got_error_from_errno2("fopen",
12080 patch_script_path);
12081 goto done;
12084 error = apply_unveil(got_repo_get_path(repo), 0,
12085 got_worktree_get_root_path(worktree));
12086 if (error)
12087 goto done;
12089 error = check_merge_in_progress(worktree, repo);
12090 if (error)
12091 goto done;
12093 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12094 if (error)
12095 goto done;
12097 if (list_stage)
12098 error = got_worktree_status(worktree, &paths, repo, 0,
12099 print_stage, NULL, check_cancelled, NULL);
12100 else {
12101 cpa.patch_script_file = patch_script_file;
12102 cpa.action = "stage";
12103 error = got_worktree_stage(worktree, &paths,
12104 pflag ? NULL : print_status, NULL,
12105 pflag ? choose_patch : NULL, &cpa,
12106 allow_bad_symlinks, repo);
12108 done:
12109 if (patch_script_file && fclose(patch_script_file) == EOF &&
12110 error == NULL)
12111 error = got_error_from_errno2("fclose", patch_script_path);
12112 if (repo) {
12113 const struct got_error *close_err = got_repo_close(repo);
12114 if (error == NULL)
12115 error = close_err;
12117 if (worktree)
12118 got_worktree_close(worktree);
12119 if (pack_fds) {
12120 const struct got_error *pack_err =
12121 got_repo_pack_fds_close(pack_fds);
12122 if (error == NULL)
12123 error = pack_err;
12125 TAILQ_FOREACH(pe, &paths, entry)
12126 free((char *)pe->path);
12127 got_pathlist_free(&paths);
12128 free(cwd);
12129 return error;
12132 __dead static void
12133 usage_unstage(void)
12135 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12136 "[file-path ...]\n",
12137 getprogname());
12138 exit(1);
12142 static const struct got_error *
12143 cmd_unstage(int argc, char *argv[])
12145 const struct got_error *error = NULL;
12146 struct got_repository *repo = NULL;
12147 struct got_worktree *worktree = NULL;
12148 char *cwd = NULL;
12149 struct got_pathlist_head paths;
12150 struct got_pathlist_entry *pe;
12151 int ch, pflag = 0;
12152 struct got_update_progress_arg upa;
12153 FILE *patch_script_file = NULL;
12154 const char *patch_script_path = NULL;
12155 struct choose_patch_arg cpa;
12156 int *pack_fds = NULL;
12158 TAILQ_INIT(&paths);
12160 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12161 switch (ch) {
12162 case 'p':
12163 pflag = 1;
12164 break;
12165 case 'F':
12166 patch_script_path = optarg;
12167 break;
12168 default:
12169 usage_unstage();
12170 /* NOTREACHED */
12174 argc -= optind;
12175 argv += optind;
12177 #ifndef PROFILE
12178 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12179 "unveil", NULL) == -1)
12180 err(1, "pledge");
12181 #endif
12182 if (patch_script_path && !pflag)
12183 errx(1, "-F option can only be used together with -p option");
12185 cwd = getcwd(NULL, 0);
12186 if (cwd == NULL) {
12187 error = got_error_from_errno("getcwd");
12188 goto done;
12191 error = got_repo_pack_fds_open(&pack_fds);
12192 if (error != NULL)
12193 goto done;
12195 error = got_worktree_open(&worktree, cwd);
12196 if (error) {
12197 if (error->code == GOT_ERR_NOT_WORKTREE)
12198 error = wrap_not_worktree_error(error, "unstage", cwd);
12199 goto done;
12202 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12203 NULL, pack_fds);
12204 if (error != NULL)
12205 goto done;
12207 if (patch_script_path) {
12208 patch_script_file = fopen(patch_script_path, "re");
12209 if (patch_script_file == NULL) {
12210 error = got_error_from_errno2("fopen",
12211 patch_script_path);
12212 goto done;
12216 error = apply_unveil(got_repo_get_path(repo), 0,
12217 got_worktree_get_root_path(worktree));
12218 if (error)
12219 goto done;
12221 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12222 if (error)
12223 goto done;
12225 cpa.patch_script_file = patch_script_file;
12226 cpa.action = "unstage";
12227 memset(&upa, 0, sizeof(upa));
12228 error = got_worktree_unstage(worktree, &paths, update_progress,
12229 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12230 if (!error)
12231 print_merge_progress_stats(&upa);
12232 done:
12233 if (patch_script_file && fclose(patch_script_file) == EOF &&
12234 error == NULL)
12235 error = got_error_from_errno2("fclose", patch_script_path);
12236 if (repo) {
12237 const struct got_error *close_err = got_repo_close(repo);
12238 if (error == NULL)
12239 error = close_err;
12241 if (worktree)
12242 got_worktree_close(worktree);
12243 if (pack_fds) {
12244 const struct got_error *pack_err =
12245 got_repo_pack_fds_close(pack_fds);
12246 if (error == NULL)
12247 error = pack_err;
12249 TAILQ_FOREACH(pe, &paths, entry)
12250 free((char *)pe->path);
12251 got_pathlist_free(&paths);
12252 free(cwd);
12253 return error;
12256 __dead static void
12257 usage_cat(void)
12259 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12260 "arg1 [arg2 ...]\n", getprogname());
12261 exit(1);
12264 static const struct got_error *
12265 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12267 const struct got_error *err;
12268 struct got_blob_object *blob;
12269 int fd = -1;
12271 fd = got_opentempfd();
12272 if (fd == -1)
12273 return got_error_from_errno("got_opentempfd");
12275 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12276 if (err)
12277 goto done;
12279 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12280 done:
12281 if (fd != -1 && close(fd) == -1 && err == NULL)
12282 err = got_error_from_errno("close");
12283 if (blob)
12284 got_object_blob_close(blob);
12285 return err;
12288 static const struct got_error *
12289 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12291 const struct got_error *err;
12292 struct got_tree_object *tree;
12293 int nentries, i;
12295 err = got_object_open_as_tree(&tree, repo, id);
12296 if (err)
12297 return err;
12299 nentries = got_object_tree_get_nentries(tree);
12300 for (i = 0; i < nentries; i++) {
12301 struct got_tree_entry *te;
12302 char *id_str;
12303 if (sigint_received || sigpipe_received)
12304 break;
12305 te = got_object_tree_get_entry(tree, i);
12306 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12307 if (err)
12308 break;
12309 fprintf(outfile, "%s %.7o %s\n", id_str,
12310 got_tree_entry_get_mode(te),
12311 got_tree_entry_get_name(te));
12312 free(id_str);
12315 got_object_tree_close(tree);
12316 return err;
12319 static void
12320 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12322 long long h, m;
12323 char sign = '+';
12325 if (gmtoff < 0) {
12326 sign = '-';
12327 gmtoff = -gmtoff;
12330 h = (long long)gmtoff / 3600;
12331 m = ((long long)gmtoff - h*3600) / 60;
12332 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12335 static const struct got_error *
12336 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12338 const struct got_error *err;
12339 struct got_commit_object *commit;
12340 const struct got_object_id_queue *parent_ids;
12341 struct got_object_qid *pid;
12342 char *id_str = NULL;
12343 const char *logmsg = NULL;
12344 char gmtoff[6];
12346 err = got_object_open_as_commit(&commit, repo, id);
12347 if (err)
12348 return err;
12350 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12351 if (err)
12352 goto done;
12354 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12355 parent_ids = got_object_commit_get_parent_ids(commit);
12356 fprintf(outfile, "numparents %d\n",
12357 got_object_commit_get_nparents(commit));
12358 STAILQ_FOREACH(pid, parent_ids, entry) {
12359 char *pid_str;
12360 err = got_object_id_str(&pid_str, &pid->id);
12361 if (err)
12362 goto done;
12363 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12364 free(pid_str);
12366 format_gmtoff(gmtoff, sizeof(gmtoff),
12367 got_object_commit_get_author_gmtoff(commit));
12368 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12369 got_object_commit_get_author(commit),
12370 (long long)got_object_commit_get_author_time(commit),
12371 gmtoff);
12373 format_gmtoff(gmtoff, sizeof(gmtoff),
12374 got_object_commit_get_committer_gmtoff(commit));
12375 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12376 got_object_commit_get_author(commit),
12377 (long long)got_object_commit_get_committer_time(commit),
12378 gmtoff);
12380 logmsg = got_object_commit_get_logmsg_raw(commit);
12381 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12382 fprintf(outfile, "%s", logmsg);
12383 done:
12384 free(id_str);
12385 got_object_commit_close(commit);
12386 return err;
12389 static const struct got_error *
12390 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12392 const struct got_error *err;
12393 struct got_tag_object *tag;
12394 char *id_str = NULL;
12395 const char *tagmsg = NULL;
12396 char gmtoff[6];
12398 err = got_object_open_as_tag(&tag, repo, id);
12399 if (err)
12400 return err;
12402 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12403 if (err)
12404 goto done;
12406 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12408 switch (got_object_tag_get_object_type(tag)) {
12409 case GOT_OBJ_TYPE_BLOB:
12410 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12411 GOT_OBJ_LABEL_BLOB);
12412 break;
12413 case GOT_OBJ_TYPE_TREE:
12414 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12415 GOT_OBJ_LABEL_TREE);
12416 break;
12417 case GOT_OBJ_TYPE_COMMIT:
12418 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12419 GOT_OBJ_LABEL_COMMIT);
12420 break;
12421 case GOT_OBJ_TYPE_TAG:
12422 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12423 GOT_OBJ_LABEL_TAG);
12424 break;
12425 default:
12426 break;
12429 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12430 got_object_tag_get_name(tag));
12432 format_gmtoff(gmtoff, sizeof(gmtoff),
12433 got_object_tag_get_tagger_gmtoff(tag));
12434 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12435 got_object_tag_get_tagger(tag),
12436 (long long)got_object_tag_get_tagger_time(tag),
12437 gmtoff);
12439 tagmsg = got_object_tag_get_message(tag);
12440 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12441 fprintf(outfile, "%s", tagmsg);
12442 done:
12443 free(id_str);
12444 got_object_tag_close(tag);
12445 return err;
12448 static const struct got_error *
12449 cmd_cat(int argc, char *argv[])
12451 const struct got_error *error;
12452 struct got_repository *repo = NULL;
12453 struct got_worktree *worktree = NULL;
12454 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12455 const char *commit_id_str = NULL;
12456 struct got_object_id *id = NULL, *commit_id = NULL;
12457 struct got_commit_object *commit = NULL;
12458 int ch, obj_type, i, force_path = 0;
12459 struct got_reflist_head refs;
12460 int *pack_fds = NULL;
12462 TAILQ_INIT(&refs);
12464 #ifndef PROFILE
12465 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12466 NULL) == -1)
12467 err(1, "pledge");
12468 #endif
12470 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12471 switch (ch) {
12472 case 'c':
12473 commit_id_str = optarg;
12474 break;
12475 case 'r':
12476 repo_path = realpath(optarg, NULL);
12477 if (repo_path == NULL)
12478 return got_error_from_errno2("realpath",
12479 optarg);
12480 got_path_strip_trailing_slashes(repo_path);
12481 break;
12482 case 'P':
12483 force_path = 1;
12484 break;
12485 default:
12486 usage_cat();
12487 /* NOTREACHED */
12491 argc -= optind;
12492 argv += optind;
12494 cwd = getcwd(NULL, 0);
12495 if (cwd == NULL) {
12496 error = got_error_from_errno("getcwd");
12497 goto done;
12500 error = got_repo_pack_fds_open(&pack_fds);
12501 if (error != NULL)
12502 goto done;
12504 if (repo_path == NULL) {
12505 error = got_worktree_open(&worktree, cwd);
12506 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12507 goto done;
12508 if (worktree) {
12509 repo_path = strdup(
12510 got_worktree_get_repo_path(worktree));
12511 if (repo_path == NULL) {
12512 error = got_error_from_errno("strdup");
12513 goto done;
12516 /* Release work tree lock. */
12517 got_worktree_close(worktree);
12518 worktree = NULL;
12522 if (repo_path == NULL) {
12523 repo_path = strdup(cwd);
12524 if (repo_path == NULL)
12525 return got_error_from_errno("strdup");
12528 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12529 free(repo_path);
12530 if (error != NULL)
12531 goto done;
12533 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12534 if (error)
12535 goto done;
12537 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12538 if (error)
12539 goto done;
12541 if (commit_id_str == NULL)
12542 commit_id_str = GOT_REF_HEAD;
12543 error = got_repo_match_object_id(&commit_id, NULL,
12544 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12545 if (error)
12546 goto done;
12548 error = got_object_open_as_commit(&commit, repo, commit_id);
12549 if (error)
12550 goto done;
12552 for (i = 0; i < argc; i++) {
12553 if (force_path) {
12554 error = got_object_id_by_path(&id, repo, commit,
12555 argv[i]);
12556 if (error)
12557 break;
12558 } else {
12559 error = got_repo_match_object_id(&id, &label, argv[i],
12560 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12561 repo);
12562 if (error) {
12563 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12564 error->code != GOT_ERR_NOT_REF)
12565 break;
12566 error = got_object_id_by_path(&id, repo,
12567 commit, argv[i]);
12568 if (error)
12569 break;
12573 error = got_object_get_type(&obj_type, repo, id);
12574 if (error)
12575 break;
12577 switch (obj_type) {
12578 case GOT_OBJ_TYPE_BLOB:
12579 error = cat_blob(id, repo, stdout);
12580 break;
12581 case GOT_OBJ_TYPE_TREE:
12582 error = cat_tree(id, repo, stdout);
12583 break;
12584 case GOT_OBJ_TYPE_COMMIT:
12585 error = cat_commit(id, repo, stdout);
12586 break;
12587 case GOT_OBJ_TYPE_TAG:
12588 error = cat_tag(id, repo, stdout);
12589 break;
12590 default:
12591 error = got_error(GOT_ERR_OBJ_TYPE);
12592 break;
12594 if (error)
12595 break;
12596 free(label);
12597 label = NULL;
12598 free(id);
12599 id = NULL;
12601 done:
12602 free(label);
12603 free(id);
12604 free(commit_id);
12605 if (commit)
12606 got_object_commit_close(commit);
12607 if (worktree)
12608 got_worktree_close(worktree);
12609 if (repo) {
12610 const struct got_error *close_err = got_repo_close(repo);
12611 if (error == NULL)
12612 error = close_err;
12614 if (pack_fds) {
12615 const struct got_error *pack_err =
12616 got_repo_pack_fds_close(pack_fds);
12617 if (error == NULL)
12618 error = pack_err;
12621 got_ref_list_free(&refs);
12622 return error;
12625 __dead static void
12626 usage_info(void)
12628 fprintf(stderr, "usage: %s info [path ...]\n",
12629 getprogname());
12630 exit(1);
12633 static const struct got_error *
12634 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12635 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12636 struct got_object_id *commit_id)
12638 const struct got_error *err = NULL;
12639 char *id_str = NULL;
12640 char datebuf[128];
12641 struct tm mytm, *tm;
12642 struct got_pathlist_head *paths = arg;
12643 struct got_pathlist_entry *pe;
12646 * Clear error indication from any of the path arguments which
12647 * would cause this file index entry to be displayed.
12649 TAILQ_FOREACH(pe, paths, entry) {
12650 if (got_path_cmp(path, pe->path, strlen(path),
12651 pe->path_len) == 0 ||
12652 got_path_is_child(path, pe->path, pe->path_len))
12653 pe->data = NULL; /* no error */
12656 printf(GOT_COMMIT_SEP_STR);
12657 if (S_ISLNK(mode))
12658 printf("symlink: %s\n", path);
12659 else if (S_ISREG(mode)) {
12660 printf("file: %s\n", path);
12661 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12662 } else if (S_ISDIR(mode))
12663 printf("directory: %s\n", path);
12664 else
12665 printf("something: %s\n", path);
12667 tm = localtime_r(&mtime, &mytm);
12668 if (tm == NULL)
12669 return NULL;
12670 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12671 return got_error(GOT_ERR_NO_SPACE);
12672 printf("timestamp: %s\n", datebuf);
12674 if (blob_id) {
12675 err = got_object_id_str(&id_str, blob_id);
12676 if (err)
12677 return err;
12678 printf("based on blob: %s\n", id_str);
12679 free(id_str);
12682 if (staged_blob_id) {
12683 err = got_object_id_str(&id_str, staged_blob_id);
12684 if (err)
12685 return err;
12686 printf("based on staged blob: %s\n", id_str);
12687 free(id_str);
12690 if (commit_id) {
12691 err = got_object_id_str(&id_str, commit_id);
12692 if (err)
12693 return err;
12694 printf("based on commit: %s\n", id_str);
12695 free(id_str);
12698 return NULL;
12701 static const struct got_error *
12702 cmd_info(int argc, char *argv[])
12704 const struct got_error *error = NULL;
12705 struct got_worktree *worktree = NULL;
12706 char *cwd = NULL, *id_str = NULL;
12707 struct got_pathlist_head paths;
12708 struct got_pathlist_entry *pe;
12709 char *uuidstr = NULL;
12710 int ch, show_files = 0;
12711 int *pack_fds = NULL;
12713 TAILQ_INIT(&paths);
12715 while ((ch = getopt(argc, argv, "")) != -1) {
12716 switch (ch) {
12717 default:
12718 usage_info();
12719 /* NOTREACHED */
12723 argc -= optind;
12724 argv += optind;
12726 #ifndef PROFILE
12727 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12728 NULL) == -1)
12729 err(1, "pledge");
12730 #endif
12731 cwd = getcwd(NULL, 0);
12732 if (cwd == NULL) {
12733 error = got_error_from_errno("getcwd");
12734 goto done;
12737 error = got_repo_pack_fds_open(&pack_fds);
12738 if (error != NULL)
12739 goto done;
12741 error = got_worktree_open(&worktree, cwd);
12742 if (error) {
12743 if (error->code == GOT_ERR_NOT_WORKTREE)
12744 error = wrap_not_worktree_error(error, "info", cwd);
12745 goto done;
12748 #ifndef PROFILE
12749 /* Remove "cpath" promise. */
12750 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12751 NULL) == -1)
12752 err(1, "pledge");
12753 #endif
12754 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12755 if (error)
12756 goto done;
12758 if (argc >= 1) {
12759 error = get_worktree_paths_from_argv(&paths, argc, argv,
12760 worktree);
12761 if (error)
12762 goto done;
12763 show_files = 1;
12766 error = got_object_id_str(&id_str,
12767 got_worktree_get_base_commit_id(worktree));
12768 if (error)
12769 goto done;
12771 error = got_worktree_get_uuid(&uuidstr, worktree);
12772 if (error)
12773 goto done;
12775 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12776 printf("work tree base commit: %s\n", id_str);
12777 printf("work tree path prefix: %s\n",
12778 got_worktree_get_path_prefix(worktree));
12779 printf("work tree branch reference: %s\n",
12780 got_worktree_get_head_ref_name(worktree));
12781 printf("work tree UUID: %s\n", uuidstr);
12782 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12784 if (show_files) {
12785 struct got_pathlist_entry *pe;
12786 TAILQ_FOREACH(pe, &paths, entry) {
12787 if (pe->path_len == 0)
12788 continue;
12790 * Assume this path will fail. This will be corrected
12791 * in print_path_info() in case the path does suceeed.
12793 pe->data = (void *)got_error_path(pe->path,
12794 GOT_ERR_BAD_PATH);
12796 error = got_worktree_path_info(worktree, &paths,
12797 print_path_info, &paths, check_cancelled, NULL);
12798 if (error)
12799 goto done;
12800 TAILQ_FOREACH(pe, &paths, entry) {
12801 if (pe->data != NULL) {
12802 error = pe->data; /* bad path */
12803 break;
12807 done:
12808 if (pack_fds) {
12809 const struct got_error *pack_err =
12810 got_repo_pack_fds_close(pack_fds);
12811 if (error == NULL)
12812 error = pack_err;
12814 TAILQ_FOREACH(pe, &paths, entry)
12815 free((char *)pe->path);
12816 got_pathlist_free(&paths);
12817 free(cwd);
12818 free(id_str);
12819 free(uuidstr);
12820 return error;