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;
3552 if (blob_id1) {
3553 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3554 if (err)
3555 goto done;
3556 f1 = got_opentemp();
3557 if (f1 == NULL) {
3558 err = got_error_from_errno("got_opentemp");
3559 goto done;
3563 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3564 if (err)
3565 goto done;
3567 f2 = got_opentemp();
3568 if (f2 == NULL) {
3569 err = got_error_from_errno("got_opentemp");
3570 goto done;
3573 while (path[0] == '/')
3574 path++;
3575 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3576 diff_context, ignore_whitespace, force_text_diff, outfile);
3577 done:
3578 if (blob1)
3579 got_object_blob_close(blob1);
3580 got_object_blob_close(blob2);
3581 if (f1 && fclose(f1) == EOF && err == NULL)
3582 err = got_error_from_errno("fclose");
3583 if (f2 && fclose(f2) == EOF && err == NULL)
3584 err = got_error_from_errno("fclose");
3585 return err;
3588 static const struct got_error *
3589 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3590 const char *path, int diff_context, int ignore_whitespace,
3591 int force_text_diff, struct got_repository *repo, FILE *outfile)
3593 const struct got_error *err = NULL;
3594 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3595 struct got_diff_blob_output_unidiff_arg arg;
3596 FILE *f1 = NULL, *f2 = NULL;
3598 if (tree_id1) {
3599 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3600 if (err)
3601 goto done;
3602 f1 = got_opentemp();
3603 if (f1 == NULL) {
3604 err = got_error_from_errno("got_opentemp");
3605 goto done;
3609 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3610 if (err)
3611 goto done;
3613 f2 = got_opentemp();
3614 if (f2 == NULL) {
3615 err = got_error_from_errno("got_opentemp");
3616 goto done;
3619 arg.diff_context = diff_context;
3620 arg.ignore_whitespace = ignore_whitespace;
3621 arg.force_text_diff = force_text_diff;
3622 arg.outfile = outfile;
3623 arg.line_offsets = NULL;
3624 arg.nlines = 0;
3625 while (path[0] == '/')
3626 path++;
3627 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3628 got_diff_blob_output_unidiff, &arg, 1);
3629 done:
3630 if (tree1)
3631 got_object_tree_close(tree1);
3632 if (tree2)
3633 got_object_tree_close(tree2);
3634 if (f1 && fclose(f1) == EOF && err == NULL)
3635 err = got_error_from_errno("fclose");
3636 if (f2 && fclose(f2) == EOF && err == NULL)
3637 err = got_error_from_errno("fclose");
3638 return err;
3641 static const struct got_error *
3642 get_changed_paths(struct got_pathlist_head *paths,
3643 struct got_commit_object *commit, struct got_repository *repo)
3645 const struct got_error *err = NULL;
3646 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3647 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3648 struct got_object_qid *qid;
3650 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3651 if (qid != NULL) {
3652 struct got_commit_object *pcommit;
3653 err = got_object_open_as_commit(&pcommit, repo,
3654 &qid->id);
3655 if (err)
3656 return err;
3658 tree_id1 = got_object_id_dup(
3659 got_object_commit_get_tree_id(pcommit));
3660 if (tree_id1 == NULL) {
3661 got_object_commit_close(pcommit);
3662 return got_error_from_errno("got_object_id_dup");
3664 got_object_commit_close(pcommit);
3668 if (tree_id1) {
3669 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3670 if (err)
3671 goto done;
3674 tree_id2 = got_object_commit_get_tree_id(commit);
3675 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3676 if (err)
3677 goto done;
3679 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3680 got_diff_tree_collect_changed_paths, paths, 0);
3681 done:
3682 if (tree1)
3683 got_object_tree_close(tree1);
3684 if (tree2)
3685 got_object_tree_close(tree2);
3686 free(tree_id1);
3687 return err;
3690 static const struct got_error *
3691 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3692 const char *path, int diff_context, struct got_repository *repo,
3693 FILE *outfile)
3695 const struct got_error *err = NULL;
3696 struct got_commit_object *pcommit = NULL;
3697 char *id_str1 = NULL, *id_str2 = NULL;
3698 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3699 struct got_object_qid *qid;
3701 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3702 if (qid != NULL) {
3703 err = got_object_open_as_commit(&pcommit, repo,
3704 &qid->id);
3705 if (err)
3706 return err;
3707 err = got_object_id_str(&id_str1, &qid->id);
3708 if (err)
3709 goto done;
3712 err = got_object_id_str(&id_str2, id);
3713 if (err)
3714 goto done;
3716 if (path && path[0] != '\0') {
3717 int obj_type;
3718 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3719 if (err)
3720 goto done;
3721 if (pcommit) {
3722 err = got_object_id_by_path(&obj_id1, repo,
3723 pcommit, path);
3724 if (err) {
3725 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3726 free(obj_id2);
3727 goto done;
3731 err = got_object_get_type(&obj_type, repo, obj_id2);
3732 if (err) {
3733 free(obj_id2);
3734 goto done;
3736 fprintf(outfile,
3737 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3738 fprintf(outfile, "commit - %s\n",
3739 id_str1 ? id_str1 : "/dev/null");
3740 fprintf(outfile, "commit + %s\n", id_str2);
3741 switch (obj_type) {
3742 case GOT_OBJ_TYPE_BLOB:
3743 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3744 0, 0, repo, outfile);
3745 break;
3746 case GOT_OBJ_TYPE_TREE:
3747 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3748 0, 0, repo, outfile);
3749 break;
3750 default:
3751 err = got_error(GOT_ERR_OBJ_TYPE);
3752 break;
3754 free(obj_id1);
3755 free(obj_id2);
3756 } else {
3757 obj_id2 = got_object_commit_get_tree_id(commit);
3758 if (pcommit)
3759 obj_id1 = got_object_commit_get_tree_id(pcommit);
3760 fprintf(outfile,
3761 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3762 fprintf(outfile, "commit - %s\n",
3763 id_str1 ? id_str1 : "/dev/null");
3764 fprintf(outfile, "commit + %s\n", id_str2);
3765 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3766 repo, outfile);
3768 done:
3769 free(id_str1);
3770 free(id_str2);
3771 if (pcommit)
3772 got_object_commit_close(pcommit);
3773 return err;
3776 static char *
3777 get_datestr(time_t *time, char *datebuf)
3779 struct tm mytm, *tm;
3780 char *p, *s;
3782 tm = gmtime_r(time, &mytm);
3783 if (tm == NULL)
3784 return NULL;
3785 s = asctime_r(tm, datebuf);
3786 if (s == NULL)
3787 return NULL;
3788 p = strchr(s, '\n');
3789 if (p)
3790 *p = '\0';
3791 return s;
3794 static const struct got_error *
3795 match_commit(int *have_match, struct got_object_id *id,
3796 struct got_commit_object *commit, regex_t *regex)
3798 const struct got_error *err = NULL;
3799 regmatch_t regmatch;
3800 char *id_str = NULL, *logmsg = NULL;
3802 *have_match = 0;
3804 err = got_object_id_str(&id_str, id);
3805 if (err)
3806 return err;
3808 err = got_object_commit_get_logmsg(&logmsg, commit);
3809 if (err)
3810 goto done;
3812 if (regexec(regex, got_object_commit_get_author(commit), 1,
3813 &regmatch, 0) == 0 ||
3814 regexec(regex, got_object_commit_get_committer(commit), 1,
3815 &regmatch, 0) == 0 ||
3816 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3817 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3818 *have_match = 1;
3819 done:
3820 free(id_str);
3821 free(logmsg);
3822 return err;
3825 static void
3826 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3827 regex_t *regex)
3829 regmatch_t regmatch;
3830 struct got_pathlist_entry *pe;
3832 *have_match = 0;
3834 TAILQ_FOREACH(pe, changed_paths, entry) {
3835 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3836 *have_match = 1;
3837 break;
3842 static const struct got_error *
3843 match_patch(int *have_match, struct got_commit_object *commit,
3844 struct got_object_id *id, const char *path, int diff_context,
3845 struct got_repository *repo, regex_t *regex, FILE *f)
3847 const struct got_error *err = NULL;
3848 char *line = NULL;
3849 size_t linesize = 0;
3850 ssize_t linelen;
3851 regmatch_t regmatch;
3853 *have_match = 0;
3855 err = got_opentemp_truncate(f);
3856 if (err)
3857 return err;
3859 err = print_patch(commit, id, path, diff_context, repo, f);
3860 if (err)
3861 goto done;
3863 if (fseeko(f, 0L, SEEK_SET) == -1) {
3864 err = got_error_from_errno("fseeko");
3865 goto done;
3868 while ((linelen = getline(&line, &linesize, f)) != -1) {
3869 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3870 *have_match = 1;
3871 break;
3874 done:
3875 free(line);
3876 return err;
3879 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3881 static const struct got_error*
3882 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3883 struct got_object_id *id, struct got_repository *repo,
3884 int local_only)
3886 static const struct got_error *err = NULL;
3887 struct got_reflist_entry *re;
3888 char *s;
3889 const char *name;
3891 *refs_str = NULL;
3893 TAILQ_FOREACH(re, refs, entry) {
3894 struct got_tag_object *tag = NULL;
3895 struct got_object_id *ref_id;
3896 int cmp;
3898 name = got_ref_get_name(re->ref);
3899 if (strcmp(name, GOT_REF_HEAD) == 0)
3900 continue;
3901 if (strncmp(name, "refs/", 5) == 0)
3902 name += 5;
3903 if (strncmp(name, "got/", 4) == 0)
3904 continue;
3905 if (strncmp(name, "heads/", 6) == 0)
3906 name += 6;
3907 if (strncmp(name, "remotes/", 8) == 0) {
3908 if (local_only)
3909 continue;
3910 name += 8;
3911 s = strstr(name, "/" GOT_REF_HEAD);
3912 if (s != NULL && s[strlen(s)] == '\0')
3913 continue;
3915 err = got_ref_resolve(&ref_id, repo, re->ref);
3916 if (err)
3917 break;
3918 if (strncmp(name, "tags/", 5) == 0) {
3919 err = got_object_open_as_tag(&tag, repo, ref_id);
3920 if (err) {
3921 if (err->code != GOT_ERR_OBJ_TYPE) {
3922 free(ref_id);
3923 break;
3925 /* Ref points at something other than a tag. */
3926 err = NULL;
3927 tag = NULL;
3930 cmp = got_object_id_cmp(tag ?
3931 got_object_tag_get_object_id(tag) : ref_id, id);
3932 free(ref_id);
3933 if (tag)
3934 got_object_tag_close(tag);
3935 if (cmp != 0)
3936 continue;
3937 s = *refs_str;
3938 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3939 s ? ", " : "", name) == -1) {
3940 err = got_error_from_errno("asprintf");
3941 free(s);
3942 *refs_str = NULL;
3943 break;
3945 free(s);
3948 return err;
3951 static const struct got_error *
3952 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3953 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3955 const struct got_error *err = NULL;
3956 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3957 char *comma, *s, *nl;
3958 struct got_reflist_head *refs;
3959 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3960 struct tm tm;
3961 time_t committer_time;
3963 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3964 if (refs) {
3965 err = build_refs_str(&ref_str, refs, id, repo, 1);
3966 if (err)
3967 return err;
3969 /* Display the first matching ref only. */
3970 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3971 *comma = '\0';
3974 if (ref_str == NULL) {
3975 err = got_object_id_str(&id_str, id);
3976 if (err)
3977 return err;
3980 committer_time = got_object_commit_get_committer_time(commit);
3981 if (gmtime_r(&committer_time, &tm) == NULL) {
3982 err = got_error_from_errno("gmtime_r");
3983 goto done;
3985 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3986 err = got_error(GOT_ERR_NO_SPACE);
3987 goto done;
3990 err = got_object_commit_get_logmsg(&logmsg0, commit);
3991 if (err)
3992 goto done;
3994 s = logmsg0;
3995 while (isspace((unsigned char)s[0]))
3996 s++;
3998 nl = strchr(s, '\n');
3999 if (nl) {
4000 *nl = '\0';
4003 if (ref_str)
4004 printf("%s%-7s %s\n", datebuf, ref_str, s);
4005 else
4006 printf("%s%.7s %s\n", datebuf, id_str, s);
4008 if (fflush(stdout) != 0 && err == NULL)
4009 err = got_error_from_errno("fflush");
4010 done:
4011 free(id_str);
4012 free(ref_str);
4013 free(logmsg0);
4014 return err;
4017 static const struct got_error *
4018 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4019 struct got_repository *repo, const char *path,
4020 struct got_pathlist_head *changed_paths, int show_patch,
4021 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4022 const char *custom_refs_str)
4024 const struct got_error *err = NULL;
4025 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4026 char datebuf[26];
4027 time_t committer_time;
4028 const char *author, *committer;
4029 char *refs_str = NULL;
4031 err = got_object_id_str(&id_str, id);
4032 if (err)
4033 return err;
4035 if (custom_refs_str == NULL) {
4036 struct got_reflist_head *refs;
4037 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4038 if (refs) {
4039 err = build_refs_str(&refs_str, refs, id, repo, 0);
4040 if (err)
4041 goto done;
4045 printf(GOT_COMMIT_SEP_STR);
4046 if (custom_refs_str)
4047 printf("commit %s (%s)\n", id_str, custom_refs_str);
4048 else
4049 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4050 refs_str ? refs_str : "", refs_str ? ")" : "");
4051 free(id_str);
4052 id_str = NULL;
4053 free(refs_str);
4054 refs_str = NULL;
4055 printf("from: %s\n", got_object_commit_get_author(commit));
4056 committer_time = got_object_commit_get_committer_time(commit);
4057 datestr = get_datestr(&committer_time, datebuf);
4058 if (datestr)
4059 printf("date: %s UTC\n", datestr);
4060 author = got_object_commit_get_author(commit);
4061 committer = got_object_commit_get_committer(commit);
4062 if (strcmp(author, committer) != 0)
4063 printf("via: %s\n", committer);
4064 if (got_object_commit_get_nparents(commit) > 1) {
4065 const struct got_object_id_queue *parent_ids;
4066 struct got_object_qid *qid;
4067 int n = 1;
4068 parent_ids = got_object_commit_get_parent_ids(commit);
4069 STAILQ_FOREACH(qid, parent_ids, entry) {
4070 err = got_object_id_str(&id_str, &qid->id);
4071 if (err)
4072 goto done;
4073 printf("parent %d: %s\n", n++, id_str);
4074 free(id_str);
4075 id_str = NULL;
4079 err = got_object_commit_get_logmsg(&logmsg0, commit);
4080 if (err)
4081 goto done;
4083 logmsg = logmsg0;
4084 do {
4085 line = strsep(&logmsg, "\n");
4086 if (line)
4087 printf(" %s\n", line);
4088 } while (line);
4089 free(logmsg0);
4091 if (changed_paths) {
4092 struct got_pathlist_entry *pe;
4093 TAILQ_FOREACH(pe, changed_paths, entry) {
4094 struct got_diff_changed_path *cp = pe->data;
4095 printf(" %c %s\n", cp->status, pe->path);
4097 printf("\n");
4099 if (show_patch) {
4100 err = print_patch(commit, id, path, diff_context, repo, stdout);
4101 if (err == 0)
4102 printf("\n");
4105 if (fflush(stdout) != 0 && err == NULL)
4106 err = got_error_from_errno("fflush");
4107 done:
4108 free(id_str);
4109 free(refs_str);
4110 return err;
4113 static const struct got_error *
4114 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4115 struct got_repository *repo, const char *path, int show_changed_paths,
4116 int show_patch, const char *search_pattern, int diff_context, int limit,
4117 int log_branches, int reverse_display_order,
4118 struct got_reflist_object_id_map *refs_idmap, int one_line,
4119 FILE *tmpfile)
4121 const struct got_error *err;
4122 struct got_commit_graph *graph;
4123 regex_t regex;
4124 int have_match;
4125 struct got_object_id_queue reversed_commits;
4126 struct got_object_qid *qid;
4127 struct got_commit_object *commit;
4128 struct got_pathlist_head changed_paths;
4129 struct got_pathlist_entry *pe;
4131 STAILQ_INIT(&reversed_commits);
4132 TAILQ_INIT(&changed_paths);
4134 if (search_pattern && regcomp(&regex, search_pattern,
4135 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4136 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4138 err = got_commit_graph_open(&graph, path, !log_branches);
4139 if (err)
4140 return err;
4141 err = got_commit_graph_iter_start(graph, root_id, repo,
4142 check_cancelled, NULL);
4143 if (err)
4144 goto done;
4145 for (;;) {
4146 struct got_object_id *id;
4148 if (sigint_received || sigpipe_received)
4149 break;
4151 err = got_commit_graph_iter_next(&id, graph, repo,
4152 check_cancelled, NULL);
4153 if (err) {
4154 if (err->code == GOT_ERR_ITER_COMPLETED)
4155 err = NULL;
4156 break;
4158 if (id == NULL)
4159 break;
4161 err = got_object_open_as_commit(&commit, repo, id);
4162 if (err)
4163 break;
4165 if (show_changed_paths && !reverse_display_order) {
4166 err = get_changed_paths(&changed_paths, commit, repo);
4167 if (err)
4168 break;
4171 if (search_pattern) {
4172 err = match_commit(&have_match, id, commit, &regex);
4173 if (err) {
4174 got_object_commit_close(commit);
4175 break;
4177 if (have_match == 0 && show_changed_paths)
4178 match_changed_paths(&have_match,
4179 &changed_paths, &regex);
4180 if (have_match == 0 && show_patch) {
4181 err = match_patch(&have_match, commit, id,
4182 path, diff_context, repo, &regex,
4183 tmpfile);
4184 if (err)
4185 break;
4187 if (have_match == 0) {
4188 got_object_commit_close(commit);
4189 TAILQ_FOREACH(pe, &changed_paths, entry) {
4190 free((char *)pe->path);
4191 free(pe->data);
4193 got_pathlist_free(&changed_paths);
4194 continue;
4198 if (reverse_display_order) {
4199 err = got_object_qid_alloc(&qid, id);
4200 if (err)
4201 break;
4202 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4203 got_object_commit_close(commit);
4204 } else {
4205 if (one_line)
4206 err = print_commit_oneline(commit, id,
4207 repo, refs_idmap);
4208 else
4209 err = print_commit(commit, id, repo, path,
4210 show_changed_paths ? &changed_paths : NULL,
4211 show_patch, diff_context, refs_idmap, NULL);
4212 got_object_commit_close(commit);
4213 if (err)
4214 break;
4216 if ((limit && --limit == 0) ||
4217 (end_id && got_object_id_cmp(id, end_id) == 0))
4218 break;
4220 TAILQ_FOREACH(pe, &changed_paths, entry) {
4221 free((char *)pe->path);
4222 free(pe->data);
4224 got_pathlist_free(&changed_paths);
4226 if (reverse_display_order) {
4227 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4228 err = got_object_open_as_commit(&commit, repo,
4229 &qid->id);
4230 if (err)
4231 break;
4232 if (show_changed_paths) {
4233 err = get_changed_paths(&changed_paths,
4234 commit, repo);
4235 if (err)
4236 break;
4238 if (one_line)
4239 err = print_commit_oneline(commit, &qid->id,
4240 repo, refs_idmap);
4241 else
4242 err = print_commit(commit, &qid->id, repo, path,
4243 show_changed_paths ? &changed_paths : NULL,
4244 show_patch, diff_context, refs_idmap, NULL);
4245 got_object_commit_close(commit);
4246 if (err)
4247 break;
4248 TAILQ_FOREACH(pe, &changed_paths, entry) {
4249 free((char *)pe->path);
4250 free(pe->data);
4252 got_pathlist_free(&changed_paths);
4255 done:
4256 while (!STAILQ_EMPTY(&reversed_commits)) {
4257 qid = STAILQ_FIRST(&reversed_commits);
4258 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4259 got_object_qid_free(qid);
4261 TAILQ_FOREACH(pe, &changed_paths, entry) {
4262 free((char *)pe->path);
4263 free(pe->data);
4265 got_pathlist_free(&changed_paths);
4266 if (search_pattern)
4267 regfree(&regex);
4268 got_commit_graph_close(graph);
4269 return err;
4272 __dead static void
4273 usage_log(void)
4275 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4276 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4277 "[-r repository-path] [-R] [path]\n", getprogname());
4278 exit(1);
4281 static int
4282 get_default_log_limit(void)
4284 const char *got_default_log_limit;
4285 long long n;
4286 const char *errstr;
4288 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4289 if (got_default_log_limit == NULL)
4290 return 0;
4291 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4292 if (errstr != NULL)
4293 return 0;
4294 return n;
4297 static const struct got_error *
4298 cmd_log(int argc, char *argv[])
4300 const struct got_error *error;
4301 struct got_repository *repo = NULL;
4302 struct got_worktree *worktree = NULL;
4303 struct got_object_id *start_id = NULL, *end_id = NULL;
4304 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4305 const char *start_commit = NULL, *end_commit = NULL;
4306 const char *search_pattern = NULL;
4307 int diff_context = -1, ch;
4308 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4309 int reverse_display_order = 0, one_line = 0;
4310 const char *errstr;
4311 struct got_reflist_head refs;
4312 struct got_reflist_object_id_map *refs_idmap = NULL;
4313 FILE *tmpfile = NULL;
4314 int *pack_fds = NULL;
4316 TAILQ_INIT(&refs);
4318 #ifndef PROFILE
4319 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4320 NULL)
4321 == -1)
4322 err(1, "pledge");
4323 #endif
4325 limit = get_default_log_limit();
4327 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4328 switch (ch) {
4329 case 'p':
4330 show_patch = 1;
4331 break;
4332 case 'P':
4333 show_changed_paths = 1;
4334 break;
4335 case 'c':
4336 start_commit = optarg;
4337 break;
4338 case 'C':
4339 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4340 &errstr);
4341 if (errstr != NULL)
4342 errx(1, "number of context lines is %s: %s",
4343 errstr, optarg);
4344 break;
4345 case 'l':
4346 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4347 if (errstr != NULL)
4348 errx(1, "number of commits is %s: %s",
4349 errstr, optarg);
4350 break;
4351 case 'b':
4352 log_branches = 1;
4353 break;
4354 case 'r':
4355 repo_path = realpath(optarg, NULL);
4356 if (repo_path == NULL)
4357 return got_error_from_errno2("realpath",
4358 optarg);
4359 got_path_strip_trailing_slashes(repo_path);
4360 break;
4361 case 'R':
4362 reverse_display_order = 1;
4363 break;
4364 case 's':
4365 one_line = 1;
4366 break;
4367 case 'S':
4368 search_pattern = optarg;
4369 break;
4370 case 'x':
4371 end_commit = optarg;
4372 break;
4373 default:
4374 usage_log();
4375 /* NOTREACHED */
4379 argc -= optind;
4380 argv += optind;
4382 if (diff_context == -1)
4383 diff_context = 3;
4384 else if (!show_patch)
4385 errx(1, "-C requires -p");
4387 if (one_line && (show_patch || show_changed_paths))
4388 errx(1, "cannot use -s with -p or -P");
4390 cwd = getcwd(NULL, 0);
4391 if (cwd == NULL) {
4392 error = got_error_from_errno("getcwd");
4393 goto done;
4396 error = got_repo_pack_fds_open(&pack_fds);
4397 if (error != NULL)
4398 goto done;
4400 if (repo_path == NULL) {
4401 error = got_worktree_open(&worktree, cwd);
4402 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4403 goto done;
4404 error = NULL;
4407 if (argc == 1) {
4408 if (worktree) {
4409 error = got_worktree_resolve_path(&path, worktree,
4410 argv[0]);
4411 if (error)
4412 goto done;
4413 } else {
4414 path = strdup(argv[0]);
4415 if (path == NULL) {
4416 error = got_error_from_errno("strdup");
4417 goto done;
4420 } else if (argc != 0)
4421 usage_log();
4423 if (repo_path == NULL) {
4424 repo_path = worktree ?
4425 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4427 if (repo_path == NULL) {
4428 error = got_error_from_errno("strdup");
4429 goto done;
4432 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4433 if (error != NULL)
4434 goto done;
4436 error = apply_unveil(got_repo_get_path(repo), 1,
4437 worktree ? got_worktree_get_root_path(worktree) : NULL);
4438 if (error)
4439 goto done;
4441 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4442 if (error)
4443 goto done;
4445 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4446 if (error)
4447 goto done;
4449 if (start_commit == NULL) {
4450 struct got_reference *head_ref;
4451 struct got_commit_object *commit = NULL;
4452 error = got_ref_open(&head_ref, repo,
4453 worktree ? got_worktree_get_head_ref_name(worktree)
4454 : GOT_REF_HEAD, 0);
4455 if (error != NULL)
4456 goto done;
4457 error = got_ref_resolve(&start_id, repo, head_ref);
4458 got_ref_close(head_ref);
4459 if (error != NULL)
4460 goto done;
4461 error = got_object_open_as_commit(&commit, repo,
4462 start_id);
4463 if (error != NULL)
4464 goto done;
4465 got_object_commit_close(commit);
4466 } else {
4467 error = got_repo_match_object_id(&start_id, NULL,
4468 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4469 if (error != NULL)
4470 goto done;
4472 if (end_commit != NULL) {
4473 error = got_repo_match_object_id(&end_id, NULL,
4474 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4475 if (error != NULL)
4476 goto done;
4479 if (worktree) {
4481 * If a path was specified on the command line it was resolved
4482 * to a path in the work tree above. Prepend the work tree's
4483 * path prefix to obtain the corresponding in-repository path.
4485 if (path) {
4486 const char *prefix;
4487 prefix = got_worktree_get_path_prefix(worktree);
4488 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4489 (path[0] != '\0') ? "/" : "", path) == -1) {
4490 error = got_error_from_errno("asprintf");
4491 goto done;
4494 } else
4495 error = got_repo_map_path(&in_repo_path, repo,
4496 path ? path : "");
4497 if (error != NULL)
4498 goto done;
4499 if (in_repo_path) {
4500 free(path);
4501 path = in_repo_path;
4504 if (worktree) {
4505 /* Release work tree lock. */
4506 got_worktree_close(worktree);
4507 worktree = NULL;
4510 if (search_pattern && show_patch) {
4511 tmpfile = got_opentemp();
4512 if (tmpfile == NULL) {
4513 error = got_error_from_errno("got_opentemp");
4514 goto done;
4518 error = print_commits(start_id, end_id, repo, path ? path : "",
4519 show_changed_paths, show_patch, search_pattern, diff_context,
4520 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4521 tmpfile);
4522 done:
4523 free(path);
4524 free(repo_path);
4525 free(cwd);
4526 if (worktree)
4527 got_worktree_close(worktree);
4528 if (repo) {
4529 const struct got_error *close_err = got_repo_close(repo);
4530 if (error == NULL)
4531 error = close_err;
4533 if (pack_fds) {
4534 const struct got_error *pack_err =
4535 got_repo_pack_fds_close(pack_fds);
4536 if (error == NULL)
4537 error = pack_err;
4539 if (refs_idmap)
4540 got_reflist_object_id_map_free(refs_idmap);
4541 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4542 error = got_error_from_errno("fclose");
4543 got_ref_list_free(&refs);
4544 return error;
4547 __dead static void
4548 usage_diff(void)
4550 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4551 "[-r repository-path] [-s] [-w] [-P] "
4552 "[object1 object2 | path ...]\n", getprogname());
4553 exit(1);
4556 struct print_diff_arg {
4557 struct got_repository *repo;
4558 struct got_worktree *worktree;
4559 int diff_context;
4560 const char *id_str;
4561 int header_shown;
4562 int diff_staged;
4563 int ignore_whitespace;
4564 int force_text_diff;
4568 * Create a file which contains the target path of a symlink so we can feed
4569 * it as content to the diff engine.
4571 static const struct got_error *
4572 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4573 const char *abspath)
4575 const struct got_error *err = NULL;
4576 char target_path[PATH_MAX];
4577 ssize_t target_len, outlen;
4579 *fd = -1;
4581 if (dirfd != -1) {
4582 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4583 if (target_len == -1)
4584 return got_error_from_errno2("readlinkat", abspath);
4585 } else {
4586 target_len = readlink(abspath, target_path, PATH_MAX);
4587 if (target_len == -1)
4588 return got_error_from_errno2("readlink", abspath);
4591 *fd = got_opentempfd();
4592 if (*fd == -1)
4593 return got_error_from_errno("got_opentempfd");
4595 outlen = write(*fd, target_path, target_len);
4596 if (outlen == -1) {
4597 err = got_error_from_errno("got_opentempfd");
4598 goto done;
4601 if (lseek(*fd, 0, SEEK_SET) == -1) {
4602 err = got_error_from_errno2("lseek", abspath);
4603 goto done;
4605 done:
4606 if (err) {
4607 close(*fd);
4608 *fd = -1;
4610 return err;
4613 static const struct got_error *
4614 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4615 const char *path, struct got_object_id *blob_id,
4616 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4617 int dirfd, const char *de_name)
4619 struct print_diff_arg *a = arg;
4620 const struct got_error *err = NULL;
4621 struct got_blob_object *blob1 = NULL;
4622 int fd = -1;
4623 FILE *f1 = NULL, *f2 = NULL;
4624 char *abspath = NULL, *label1 = NULL;
4625 struct stat sb;
4626 off_t size1 = 0;
4628 if (a->diff_staged) {
4629 if (staged_status != GOT_STATUS_MODIFY &&
4630 staged_status != GOT_STATUS_ADD &&
4631 staged_status != GOT_STATUS_DELETE)
4632 return NULL;
4633 } else {
4634 if (staged_status == GOT_STATUS_DELETE)
4635 return NULL;
4636 if (status == GOT_STATUS_NONEXISTENT)
4637 return got_error_set_errno(ENOENT, path);
4638 if (status != GOT_STATUS_MODIFY &&
4639 status != GOT_STATUS_ADD &&
4640 status != GOT_STATUS_DELETE &&
4641 status != GOT_STATUS_CONFLICT)
4642 return NULL;
4645 if (!a->header_shown) {
4646 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4647 got_worktree_get_root_path(a->worktree));
4648 printf("commit - %s\n", a->id_str);
4649 printf("path + %s%s\n",
4650 got_worktree_get_root_path(a->worktree),
4651 a->diff_staged ? " (staged changes)" : "");
4652 a->header_shown = 1;
4655 if (a->diff_staged) {
4656 const char *label1 = NULL, *label2 = NULL;
4657 switch (staged_status) {
4658 case GOT_STATUS_MODIFY:
4659 label1 = path;
4660 label2 = path;
4661 break;
4662 case GOT_STATUS_ADD:
4663 label2 = path;
4664 break;
4665 case GOT_STATUS_DELETE:
4666 label1 = path;
4667 break;
4668 default:
4669 return got_error(GOT_ERR_FILE_STATUS);
4671 f1 = got_opentemp();
4672 if (f1 == NULL) {
4673 err = got_error_from_errno("got_opentemp");
4674 goto done;
4676 f2 = got_opentemp();
4677 if (f2 == NULL) {
4678 err = got_error_from_errno("got_opentemp");
4679 goto done;
4681 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4682 blob_id, staged_blob_id, label1, label2, a->diff_context,
4683 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4684 goto done;
4687 if (staged_status == GOT_STATUS_ADD ||
4688 staged_status == GOT_STATUS_MODIFY) {
4689 char *id_str;
4690 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4691 8192);
4692 if (err)
4693 goto done;
4694 err = got_object_id_str(&id_str, staged_blob_id);
4695 if (err)
4696 goto done;
4697 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4698 err = got_error_from_errno("asprintf");
4699 free(id_str);
4700 goto done;
4702 free(id_str);
4703 } else if (status != GOT_STATUS_ADD) {
4704 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4705 if (err)
4706 goto done;
4709 if (status != GOT_STATUS_DELETE) {
4710 if (asprintf(&abspath, "%s/%s",
4711 got_worktree_get_root_path(a->worktree), path) == -1) {
4712 err = got_error_from_errno("asprintf");
4713 goto done;
4716 if (dirfd != -1) {
4717 fd = openat(dirfd, de_name,
4718 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4719 if (fd == -1) {
4720 if (!got_err_open_nofollow_on_symlink()) {
4721 err = got_error_from_errno2("openat",
4722 abspath);
4723 goto done;
4725 err = get_symlink_target_file(&fd, dirfd,
4726 de_name, abspath);
4727 if (err)
4728 goto done;
4730 } else {
4731 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4732 if (fd == -1) {
4733 if (!got_err_open_nofollow_on_symlink()) {
4734 err = got_error_from_errno2("open",
4735 abspath);
4736 goto done;
4738 err = get_symlink_target_file(&fd, dirfd,
4739 de_name, abspath);
4740 if (err)
4741 goto done;
4744 if (fstat(fd, &sb) == -1) {
4745 err = got_error_from_errno2("fstat", abspath);
4746 goto done;
4748 f2 = fdopen(fd, "r");
4749 if (f2 == NULL) {
4750 err = got_error_from_errno2("fdopen", abspath);
4751 goto done;
4753 fd = -1;
4754 } else
4755 sb.st_size = 0;
4757 if (blob1) {
4758 f1 = got_opentemp();
4759 if (f1 == NULL) {
4760 err = got_error_from_errno("got_opentemp");
4761 goto done;
4763 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4764 blob1);
4765 if (err)
4766 goto done;
4769 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4770 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4771 stdout);
4772 done:
4773 if (blob1)
4774 got_object_blob_close(blob1);
4775 if (f1 && fclose(f1) == EOF && err == NULL)
4776 err = got_error_from_errno("fclose");
4777 if (f2 && fclose(f2) == EOF && err == NULL)
4778 err = got_error_from_errno("fclose");
4779 if (fd != -1 && close(fd) == -1 && err == NULL)
4780 err = got_error_from_errno("close");
4781 free(abspath);
4782 return err;
4785 static const struct got_error *
4786 cmd_diff(int argc, char *argv[])
4788 const struct got_error *error;
4789 struct got_repository *repo = NULL;
4790 struct got_worktree *worktree = NULL;
4791 char *cwd = NULL, *repo_path = NULL;
4792 const char *commit_args[2] = { NULL, NULL };
4793 int ncommit_args = 0;
4794 struct got_object_id *ids[2] = { NULL, NULL };
4795 char *labels[2] = { NULL, NULL };
4796 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4797 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4798 int force_text_diff = 0, force_path = 0, rflag = 0;
4799 const char *errstr;
4800 struct got_reflist_head refs;
4801 struct got_pathlist_head paths;
4802 struct got_pathlist_entry *pe;
4803 FILE *f1 = NULL, *f2 = NULL;
4804 int *pack_fds = NULL;
4806 TAILQ_INIT(&refs);
4807 TAILQ_INIT(&paths);
4809 #ifndef PROFILE
4810 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4811 NULL) == -1)
4812 err(1, "pledge");
4813 #endif
4815 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4816 switch (ch) {
4817 case 'a':
4818 force_text_diff = 1;
4819 break;
4820 case 'c':
4821 if (ncommit_args >= 2)
4822 errx(1, "too many -c options used");
4823 commit_args[ncommit_args++] = optarg;
4824 break;
4825 case 'C':
4826 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4827 &errstr);
4828 if (errstr != NULL)
4829 errx(1, "number of context lines is %s: %s",
4830 errstr, optarg);
4831 break;
4832 case 'r':
4833 repo_path = realpath(optarg, NULL);
4834 if (repo_path == NULL)
4835 return got_error_from_errno2("realpath",
4836 optarg);
4837 got_path_strip_trailing_slashes(repo_path);
4838 rflag = 1;
4839 break;
4840 case 's':
4841 diff_staged = 1;
4842 break;
4843 case 'w':
4844 ignore_whitespace = 1;
4845 break;
4846 case 'P':
4847 force_path = 1;
4848 break;
4849 default:
4850 usage_diff();
4851 /* NOTREACHED */
4855 argc -= optind;
4856 argv += optind;
4858 cwd = getcwd(NULL, 0);
4859 if (cwd == NULL) {
4860 error = got_error_from_errno("getcwd");
4861 goto done;
4864 error = got_repo_pack_fds_open(&pack_fds);
4865 if (error != NULL)
4866 goto done;
4868 if (repo_path == NULL) {
4869 error = got_worktree_open(&worktree, cwd);
4870 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4871 goto done;
4872 else
4873 error = NULL;
4874 if (worktree) {
4875 repo_path =
4876 strdup(got_worktree_get_repo_path(worktree));
4877 if (repo_path == NULL) {
4878 error = got_error_from_errno("strdup");
4879 goto done;
4881 } else {
4882 repo_path = strdup(cwd);
4883 if (repo_path == NULL) {
4884 error = got_error_from_errno("strdup");
4885 goto done;
4890 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4891 free(repo_path);
4892 if (error != NULL)
4893 goto done;
4895 if (rflag || worktree == NULL || ncommit_args > 0) {
4896 if (force_path) {
4897 error = got_error_msg(GOT_ERR_NOT_IMPL,
4898 "-P option can only be used when diffing "
4899 "a work tree");
4900 goto done;
4902 if (diff_staged) {
4903 error = got_error_msg(GOT_ERR_NOT_IMPL,
4904 "-s option can only be used when diffing "
4905 "a work tree");
4906 goto done;
4910 error = apply_unveil(got_repo_get_path(repo), 1,
4911 worktree ? got_worktree_get_root_path(worktree) : NULL);
4912 if (error)
4913 goto done;
4915 if ((!force_path && argc == 2) || ncommit_args > 0) {
4916 int obj_type = (ncommit_args > 0 ?
4917 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4918 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4919 NULL);
4920 if (error)
4921 goto done;
4922 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4923 const char *arg;
4924 if (ncommit_args > 0)
4925 arg = commit_args[i];
4926 else
4927 arg = argv[i];
4928 error = got_repo_match_object_id(&ids[i], &labels[i],
4929 arg, obj_type, &refs, repo);
4930 if (error) {
4931 if (error->code != GOT_ERR_NOT_REF &&
4932 error->code != GOT_ERR_NO_OBJ)
4933 goto done;
4934 if (ncommit_args > 0)
4935 goto done;
4936 error = NULL;
4937 break;
4942 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4943 struct print_diff_arg arg;
4944 char *id_str;
4946 if (worktree == NULL) {
4947 if (argc == 2 && ids[0] == NULL) {
4948 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4949 goto done;
4950 } else if (argc == 2 && ids[1] == NULL) {
4951 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4952 goto done;
4953 } else if (argc > 0) {
4954 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4955 "%s", "specified paths cannot be resolved");
4956 goto done;
4957 } else {
4958 error = got_error(GOT_ERR_NOT_WORKTREE);
4959 goto done;
4963 error = get_worktree_paths_from_argv(&paths, argc, argv,
4964 worktree);
4965 if (error)
4966 goto done;
4968 error = got_object_id_str(&id_str,
4969 got_worktree_get_base_commit_id(worktree));
4970 if (error)
4971 goto done;
4972 arg.repo = repo;
4973 arg.worktree = worktree;
4974 arg.diff_context = diff_context;
4975 arg.id_str = id_str;
4976 arg.header_shown = 0;
4977 arg.diff_staged = diff_staged;
4978 arg.ignore_whitespace = ignore_whitespace;
4979 arg.force_text_diff = force_text_diff;
4981 error = got_worktree_status(worktree, &paths, repo, 0,
4982 print_diff, &arg, check_cancelled, NULL);
4983 free(id_str);
4984 goto done;
4987 if (ncommit_args == 1) {
4988 struct got_commit_object *commit;
4989 error = got_object_open_as_commit(&commit, repo, ids[0]);
4990 if (error)
4991 goto done;
4993 labels[1] = labels[0];
4994 ids[1] = ids[0];
4995 if (got_object_commit_get_nparents(commit) > 0) {
4996 const struct got_object_id_queue *pids;
4997 struct got_object_qid *pid;
4998 pids = got_object_commit_get_parent_ids(commit);
4999 pid = STAILQ_FIRST(pids);
5000 ids[0] = got_object_id_dup(&pid->id);
5001 if (ids[0] == NULL) {
5002 error = got_error_from_errno(
5003 "got_object_id_dup");
5004 got_object_commit_close(commit);
5005 goto done;
5007 error = got_object_id_str(&labels[0], ids[0]);
5008 if (error) {
5009 got_object_commit_close(commit);
5010 goto done;
5012 } else {
5013 ids[0] = NULL;
5014 labels[0] = strdup("/dev/null");
5015 if (labels[0] == NULL) {
5016 error = got_error_from_errno("strdup");
5017 got_object_commit_close(commit);
5018 goto done;
5022 got_object_commit_close(commit);
5025 if (ncommit_args == 0 && argc > 2) {
5026 error = got_error_msg(GOT_ERR_BAD_PATH,
5027 "path arguments cannot be used when diffing two objects");
5028 goto done;
5031 if (ids[0]) {
5032 error = got_object_get_type(&type1, repo, ids[0]);
5033 if (error)
5034 goto done;
5037 error = got_object_get_type(&type2, repo, ids[1]);
5038 if (error)
5039 goto done;
5040 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5041 error = got_error(GOT_ERR_OBJ_TYPE);
5042 goto done;
5044 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5045 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5046 "path arguments cannot be used when diffing blobs");
5047 goto done;
5050 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5051 char *in_repo_path;
5052 struct got_pathlist_entry *new;
5053 if (worktree) {
5054 const char *prefix;
5055 char *p;
5056 error = got_worktree_resolve_path(&p, worktree,
5057 argv[i]);
5058 if (error)
5059 goto done;
5060 prefix = got_worktree_get_path_prefix(worktree);
5061 while (prefix[0] == '/')
5062 prefix++;
5063 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5064 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5065 p) == -1) {
5066 error = got_error_from_errno("asprintf");
5067 free(p);
5068 goto done;
5070 free(p);
5071 } else {
5072 char *mapped_path, *s;
5073 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5074 if (error)
5075 goto done;
5076 s = mapped_path;
5077 while (s[0] == '/')
5078 s++;
5079 in_repo_path = strdup(s);
5080 if (in_repo_path == NULL) {
5081 error = got_error_from_errno("asprintf");
5082 free(mapped_path);
5083 goto done;
5085 free(mapped_path);
5088 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5089 if (error || new == NULL /* duplicate */)
5090 free(in_repo_path);
5091 if (error)
5092 goto done;
5095 if (worktree) {
5096 /* Release work tree lock. */
5097 got_worktree_close(worktree);
5098 worktree = NULL;
5101 f1 = got_opentemp();
5102 if (f1 == NULL) {
5103 error = got_error_from_errno("got_opentemp");
5104 goto done;
5107 f2 = got_opentemp();
5108 if (f2 == NULL) {
5109 error = got_error_from_errno("got_opentemp");
5110 goto done;
5113 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5114 case GOT_OBJ_TYPE_BLOB:
5115 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5116 ids[0], ids[1], NULL, NULL, diff_context,
5117 ignore_whitespace, force_text_diff, repo, stdout);
5118 break;
5119 case GOT_OBJ_TYPE_TREE:
5120 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5121 ids[0], ids[1], &paths, "", "", diff_context,
5122 ignore_whitespace, force_text_diff, repo, stdout);
5123 break;
5124 case GOT_OBJ_TYPE_COMMIT:
5125 printf("diff %s %s\n", labels[0], labels[1]);
5126 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5127 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5128 force_text_diff, repo, stdout);
5129 break;
5130 default:
5131 error = got_error(GOT_ERR_OBJ_TYPE);
5133 done:
5134 free(labels[0]);
5135 free(labels[1]);
5136 free(ids[0]);
5137 free(ids[1]);
5138 if (worktree)
5139 got_worktree_close(worktree);
5140 if (repo) {
5141 const struct got_error *close_err = got_repo_close(repo);
5142 if (error == NULL)
5143 error = close_err;
5145 if (pack_fds) {
5146 const struct got_error *pack_err =
5147 got_repo_pack_fds_close(pack_fds);
5148 if (error == NULL)
5149 error = pack_err;
5151 TAILQ_FOREACH(pe, &paths, entry)
5152 free((char *)pe->path);
5153 got_pathlist_free(&paths);
5154 got_ref_list_free(&refs);
5155 if (f1 && fclose(f1) == EOF && error == NULL)
5156 error = got_error_from_errno("fclose");
5157 if (f2 && fclose(f2) == EOF && error == NULL)
5158 error = got_error_from_errno("fclose");
5159 return error;
5162 __dead static void
5163 usage_blame(void)
5165 fprintf(stderr,
5166 "usage: %s blame [-c commit] [-r repository-path] path\n",
5167 getprogname());
5168 exit(1);
5171 struct blame_line {
5172 int annotated;
5173 char *id_str;
5174 char *committer;
5175 char datebuf[11]; /* YYYY-MM-DD + NUL */
5178 struct blame_cb_args {
5179 struct blame_line *lines;
5180 int nlines;
5181 int nlines_prec;
5182 int lineno_cur;
5183 off_t *line_offsets;
5184 FILE *f;
5185 struct got_repository *repo;
5188 static const struct got_error *
5189 blame_cb(void *arg, int nlines, int lineno,
5190 struct got_commit_object *commit, struct got_object_id *id)
5192 const struct got_error *err = NULL;
5193 struct blame_cb_args *a = arg;
5194 struct blame_line *bline;
5195 char *line = NULL;
5196 size_t linesize = 0;
5197 off_t offset;
5198 struct tm tm;
5199 time_t committer_time;
5201 if (nlines != a->nlines ||
5202 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5203 return got_error(GOT_ERR_RANGE);
5205 if (sigint_received)
5206 return got_error(GOT_ERR_ITER_COMPLETED);
5208 if (lineno == -1)
5209 return NULL; /* no change in this commit */
5211 /* Annotate this line. */
5212 bline = &a->lines[lineno - 1];
5213 if (bline->annotated)
5214 return NULL;
5215 err = got_object_id_str(&bline->id_str, id);
5216 if (err)
5217 return err;
5219 bline->committer = strdup(got_object_commit_get_committer(commit));
5220 if (bline->committer == NULL) {
5221 err = got_error_from_errno("strdup");
5222 goto done;
5225 committer_time = got_object_commit_get_committer_time(commit);
5226 if (gmtime_r(&committer_time, &tm) == NULL)
5227 return got_error_from_errno("gmtime_r");
5228 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5229 &tm) == 0) {
5230 err = got_error(GOT_ERR_NO_SPACE);
5231 goto done;
5233 bline->annotated = 1;
5235 /* Print lines annotated so far. */
5236 bline = &a->lines[a->lineno_cur - 1];
5237 if (!bline->annotated)
5238 goto done;
5240 offset = a->line_offsets[a->lineno_cur - 1];
5241 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5242 err = got_error_from_errno("fseeko");
5243 goto done;
5246 while (bline->annotated) {
5247 char *smallerthan, *at, *nl, *committer;
5248 size_t len;
5250 if (getline(&line, &linesize, a->f) == -1) {
5251 if (ferror(a->f))
5252 err = got_error_from_errno("getline");
5253 break;
5256 committer = bline->committer;
5257 smallerthan = strchr(committer, '<');
5258 if (smallerthan && smallerthan[1] != '\0')
5259 committer = smallerthan + 1;
5260 at = strchr(committer, '@');
5261 if (at)
5262 *at = '\0';
5263 len = strlen(committer);
5264 if (len >= 9)
5265 committer[8] = '\0';
5267 nl = strchr(line, '\n');
5268 if (nl)
5269 *nl = '\0';
5270 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5271 bline->id_str, bline->datebuf, committer, line);
5273 a->lineno_cur++;
5274 bline = &a->lines[a->lineno_cur - 1];
5276 done:
5277 free(line);
5278 return err;
5281 static const struct got_error *
5282 cmd_blame(int argc, char *argv[])
5284 const struct got_error *error;
5285 struct got_repository *repo = NULL;
5286 struct got_worktree *worktree = NULL;
5287 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5288 char *link_target = NULL;
5289 struct got_object_id *obj_id = NULL;
5290 struct got_object_id *commit_id = NULL;
5291 struct got_commit_object *commit = NULL;
5292 struct got_blob_object *blob = NULL;
5293 char *commit_id_str = NULL;
5294 struct blame_cb_args bca;
5295 int ch, obj_type, i;
5296 off_t filesize;
5297 int *pack_fds = NULL;
5299 memset(&bca, 0, sizeof(bca));
5301 #ifndef PROFILE
5302 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5303 NULL) == -1)
5304 err(1, "pledge");
5305 #endif
5307 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5308 switch (ch) {
5309 case 'c':
5310 commit_id_str = optarg;
5311 break;
5312 case 'r':
5313 repo_path = realpath(optarg, NULL);
5314 if (repo_path == NULL)
5315 return got_error_from_errno2("realpath",
5316 optarg);
5317 got_path_strip_trailing_slashes(repo_path);
5318 break;
5319 default:
5320 usage_blame();
5321 /* NOTREACHED */
5325 argc -= optind;
5326 argv += optind;
5328 if (argc == 1)
5329 path = argv[0];
5330 else
5331 usage_blame();
5333 cwd = getcwd(NULL, 0);
5334 if (cwd == NULL) {
5335 error = got_error_from_errno("getcwd");
5336 goto done;
5339 error = got_repo_pack_fds_open(&pack_fds);
5340 if (error != NULL)
5341 goto done;
5343 if (repo_path == NULL) {
5344 error = got_worktree_open(&worktree, cwd);
5345 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5346 goto done;
5347 else
5348 error = NULL;
5349 if (worktree) {
5350 repo_path =
5351 strdup(got_worktree_get_repo_path(worktree));
5352 if (repo_path == NULL) {
5353 error = got_error_from_errno("strdup");
5354 if (error)
5355 goto done;
5357 } else {
5358 repo_path = strdup(cwd);
5359 if (repo_path == NULL) {
5360 error = got_error_from_errno("strdup");
5361 goto done;
5366 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5367 if (error != NULL)
5368 goto done;
5370 if (worktree) {
5371 const char *prefix = got_worktree_get_path_prefix(worktree);
5372 char *p;
5374 error = got_worktree_resolve_path(&p, worktree, path);
5375 if (error)
5376 goto done;
5377 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5378 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5379 p) == -1) {
5380 error = got_error_from_errno("asprintf");
5381 free(p);
5382 goto done;
5384 free(p);
5385 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5386 } else {
5387 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5388 if (error)
5389 goto done;
5390 error = got_repo_map_path(&in_repo_path, repo, path);
5392 if (error)
5393 goto done;
5395 if (commit_id_str == NULL) {
5396 struct got_reference *head_ref;
5397 error = got_ref_open(&head_ref, repo, worktree ?
5398 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5399 if (error != NULL)
5400 goto done;
5401 error = got_ref_resolve(&commit_id, repo, head_ref);
5402 got_ref_close(head_ref);
5403 if (error != NULL)
5404 goto done;
5405 } else {
5406 struct got_reflist_head refs;
5407 TAILQ_INIT(&refs);
5408 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5409 NULL);
5410 if (error)
5411 goto done;
5412 error = got_repo_match_object_id(&commit_id, NULL,
5413 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5414 got_ref_list_free(&refs);
5415 if (error)
5416 goto done;
5419 if (worktree) {
5420 /* Release work tree lock. */
5421 got_worktree_close(worktree);
5422 worktree = NULL;
5425 error = got_object_open_as_commit(&commit, repo, commit_id);
5426 if (error)
5427 goto done;
5429 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5430 commit, repo);
5431 if (error)
5432 goto done;
5434 error = got_object_id_by_path(&obj_id, repo, commit,
5435 link_target ? link_target : in_repo_path);
5436 if (error)
5437 goto done;
5439 error = got_object_get_type(&obj_type, repo, obj_id);
5440 if (error)
5441 goto done;
5443 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5444 error = got_error_path(link_target ? link_target : in_repo_path,
5445 GOT_ERR_OBJ_TYPE);
5446 goto done;
5449 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5450 if (error)
5451 goto done;
5452 bca.f = got_opentemp();
5453 if (bca.f == NULL) {
5454 error = got_error_from_errno("got_opentemp");
5455 goto done;
5457 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5458 &bca.line_offsets, bca.f, blob);
5459 if (error || bca.nlines == 0)
5460 goto done;
5462 /* Don't include \n at EOF in the blame line count. */
5463 if (bca.line_offsets[bca.nlines - 1] == filesize)
5464 bca.nlines--;
5466 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5467 if (bca.lines == NULL) {
5468 error = got_error_from_errno("calloc");
5469 goto done;
5471 bca.lineno_cur = 1;
5472 bca.nlines_prec = 0;
5473 i = bca.nlines;
5474 while (i > 0) {
5475 i /= 10;
5476 bca.nlines_prec++;
5478 bca.repo = repo;
5480 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5481 repo, blame_cb, &bca, check_cancelled, NULL);
5482 done:
5483 free(in_repo_path);
5484 free(link_target);
5485 free(repo_path);
5486 free(cwd);
5487 free(commit_id);
5488 free(obj_id);
5489 if (commit)
5490 got_object_commit_close(commit);
5491 if (blob)
5492 got_object_blob_close(blob);
5493 if (worktree)
5494 got_worktree_close(worktree);
5495 if (repo) {
5496 const struct got_error *close_err = got_repo_close(repo);
5497 if (error == NULL)
5498 error = close_err;
5500 if (pack_fds) {
5501 const struct got_error *pack_err =
5502 got_repo_pack_fds_close(pack_fds);
5503 if (error == NULL)
5504 error = pack_err;
5506 if (bca.lines) {
5507 for (i = 0; i < bca.nlines; i++) {
5508 struct blame_line *bline = &bca.lines[i];
5509 free(bline->id_str);
5510 free(bline->committer);
5512 free(bca.lines);
5514 free(bca.line_offsets);
5515 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5516 error = got_error_from_errno("fclose");
5517 return error;
5520 __dead static void
5521 usage_tree(void)
5523 fprintf(stderr,
5524 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5525 getprogname());
5526 exit(1);
5529 static const struct got_error *
5530 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5531 const char *root_path, struct got_repository *repo)
5533 const struct got_error *err = NULL;
5534 int is_root_path = (strcmp(path, root_path) == 0);
5535 const char *modestr = "";
5536 mode_t mode = got_tree_entry_get_mode(te);
5537 char *link_target = NULL;
5539 path += strlen(root_path);
5540 while (path[0] == '/')
5541 path++;
5543 if (got_object_tree_entry_is_submodule(te))
5544 modestr = "$";
5545 else if (S_ISLNK(mode)) {
5546 int i;
5548 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5549 if (err)
5550 return err;
5551 for (i = 0; i < strlen(link_target); i++) {
5552 if (!isprint((unsigned char)link_target[i]))
5553 link_target[i] = '?';
5556 modestr = "@";
5558 else if (S_ISDIR(mode))
5559 modestr = "/";
5560 else if (mode & S_IXUSR)
5561 modestr = "*";
5563 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5564 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5565 link_target ? " -> ": "", link_target ? link_target : "");
5567 free(link_target);
5568 return NULL;
5571 static const struct got_error *
5572 print_tree(const char *path, struct got_commit_object *commit,
5573 int show_ids, int recurse, const char *root_path,
5574 struct got_repository *repo)
5576 const struct got_error *err = NULL;
5577 struct got_object_id *tree_id = NULL;
5578 struct got_tree_object *tree = NULL;
5579 int nentries, i;
5581 err = got_object_id_by_path(&tree_id, repo, commit, path);
5582 if (err)
5583 goto done;
5585 err = got_object_open_as_tree(&tree, repo, tree_id);
5586 if (err)
5587 goto done;
5588 nentries = got_object_tree_get_nentries(tree);
5589 for (i = 0; i < nentries; i++) {
5590 struct got_tree_entry *te;
5591 char *id = NULL;
5593 if (sigint_received || sigpipe_received)
5594 break;
5596 te = got_object_tree_get_entry(tree, i);
5597 if (show_ids) {
5598 char *id_str;
5599 err = got_object_id_str(&id_str,
5600 got_tree_entry_get_id(te));
5601 if (err)
5602 goto done;
5603 if (asprintf(&id, "%s ", id_str) == -1) {
5604 err = got_error_from_errno("asprintf");
5605 free(id_str);
5606 goto done;
5608 free(id_str);
5610 err = print_entry(te, id, path, root_path, repo);
5611 free(id);
5612 if (err)
5613 goto done;
5615 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5616 char *child_path;
5617 if (asprintf(&child_path, "%s%s%s", path,
5618 path[0] == '/' && path[1] == '\0' ? "" : "/",
5619 got_tree_entry_get_name(te)) == -1) {
5620 err = got_error_from_errno("asprintf");
5621 goto done;
5623 err = print_tree(child_path, commit, show_ids, 1,
5624 root_path, repo);
5625 free(child_path);
5626 if (err)
5627 goto done;
5630 done:
5631 if (tree)
5632 got_object_tree_close(tree);
5633 free(tree_id);
5634 return err;
5637 static const struct got_error *
5638 cmd_tree(int argc, char *argv[])
5640 const struct got_error *error;
5641 struct got_repository *repo = NULL;
5642 struct got_worktree *worktree = NULL;
5643 const char *path, *refname = NULL;
5644 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5645 struct got_object_id *commit_id = NULL;
5646 struct got_commit_object *commit = NULL;
5647 char *commit_id_str = NULL;
5648 int show_ids = 0, recurse = 0;
5649 int ch;
5650 int *pack_fds = NULL;
5652 #ifndef PROFILE
5653 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5654 NULL) == -1)
5655 err(1, "pledge");
5656 #endif
5658 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5659 switch (ch) {
5660 case 'c':
5661 commit_id_str = optarg;
5662 break;
5663 case 'r':
5664 repo_path = realpath(optarg, NULL);
5665 if (repo_path == NULL)
5666 return got_error_from_errno2("realpath",
5667 optarg);
5668 got_path_strip_trailing_slashes(repo_path);
5669 break;
5670 case 'i':
5671 show_ids = 1;
5672 break;
5673 case 'R':
5674 recurse = 1;
5675 break;
5676 default:
5677 usage_tree();
5678 /* NOTREACHED */
5682 argc -= optind;
5683 argv += optind;
5685 if (argc == 1)
5686 path = argv[0];
5687 else if (argc > 1)
5688 usage_tree();
5689 else
5690 path = NULL;
5692 cwd = getcwd(NULL, 0);
5693 if (cwd == NULL) {
5694 error = got_error_from_errno("getcwd");
5695 goto done;
5698 error = got_repo_pack_fds_open(&pack_fds);
5699 if (error != NULL)
5700 goto done;
5702 if (repo_path == NULL) {
5703 error = got_worktree_open(&worktree, cwd);
5704 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5705 goto done;
5706 else
5707 error = NULL;
5708 if (worktree) {
5709 repo_path =
5710 strdup(got_worktree_get_repo_path(worktree));
5711 if (repo_path == NULL)
5712 error = got_error_from_errno("strdup");
5713 if (error)
5714 goto done;
5715 } else {
5716 repo_path = strdup(cwd);
5717 if (repo_path == NULL) {
5718 error = got_error_from_errno("strdup");
5719 goto done;
5724 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5725 if (error != NULL)
5726 goto done;
5728 if (worktree) {
5729 const char *prefix = got_worktree_get_path_prefix(worktree);
5730 char *p;
5732 if (path == NULL)
5733 path = "";
5734 error = got_worktree_resolve_path(&p, worktree, path);
5735 if (error)
5736 goto done;
5737 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5738 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5739 p) == -1) {
5740 error = got_error_from_errno("asprintf");
5741 free(p);
5742 goto done;
5744 free(p);
5745 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5746 if (error)
5747 goto done;
5748 } else {
5749 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5750 if (error)
5751 goto done;
5752 if (path == NULL)
5753 path = "/";
5754 error = got_repo_map_path(&in_repo_path, repo, path);
5755 if (error != NULL)
5756 goto done;
5759 if (commit_id_str == NULL) {
5760 struct got_reference *head_ref;
5761 if (worktree)
5762 refname = got_worktree_get_head_ref_name(worktree);
5763 else
5764 refname = GOT_REF_HEAD;
5765 error = got_ref_open(&head_ref, repo, refname, 0);
5766 if (error != NULL)
5767 goto done;
5768 error = got_ref_resolve(&commit_id, repo, head_ref);
5769 got_ref_close(head_ref);
5770 if (error != NULL)
5771 goto done;
5772 } else {
5773 struct got_reflist_head refs;
5774 TAILQ_INIT(&refs);
5775 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5776 NULL);
5777 if (error)
5778 goto done;
5779 error = got_repo_match_object_id(&commit_id, NULL,
5780 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5781 got_ref_list_free(&refs);
5782 if (error)
5783 goto done;
5786 if (worktree) {
5787 /* Release work tree lock. */
5788 got_worktree_close(worktree);
5789 worktree = NULL;
5792 error = got_object_open_as_commit(&commit, repo, commit_id);
5793 if (error)
5794 goto done;
5796 error = print_tree(in_repo_path, commit, show_ids, recurse,
5797 in_repo_path, repo);
5798 done:
5799 free(in_repo_path);
5800 free(repo_path);
5801 free(cwd);
5802 free(commit_id);
5803 if (commit)
5804 got_object_commit_close(commit);
5805 if (worktree)
5806 got_worktree_close(worktree);
5807 if (repo) {
5808 const struct got_error *close_err = got_repo_close(repo);
5809 if (error == NULL)
5810 error = close_err;
5812 if (pack_fds) {
5813 const struct got_error *pack_err =
5814 got_repo_pack_fds_close(pack_fds);
5815 if (error == NULL)
5816 error = pack_err;
5818 return error;
5821 __dead static void
5822 usage_status(void)
5824 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5825 "[-S status-codes] [path ...]\n", getprogname());
5826 exit(1);
5829 struct got_status_arg {
5830 char *status_codes;
5831 int suppress;
5834 static const struct got_error *
5835 print_status(void *arg, unsigned char status, unsigned char staged_status,
5836 const char *path, struct got_object_id *blob_id,
5837 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5838 int dirfd, const char *de_name)
5840 struct got_status_arg *st = arg;
5842 if (status == staged_status && (status == GOT_STATUS_DELETE))
5843 status = GOT_STATUS_NO_CHANGE;
5844 if (st != NULL && st->status_codes) {
5845 size_t ncodes = strlen(st->status_codes);
5846 int i, j = 0;
5848 for (i = 0; i < ncodes ; i++) {
5849 if (st->suppress) {
5850 if (status == st->status_codes[i] ||
5851 staged_status == st->status_codes[i]) {
5852 j++;
5853 continue;
5855 } else {
5856 if (status == st->status_codes[i] ||
5857 staged_status == st->status_codes[i])
5858 break;
5862 if (st->suppress && j == 0)
5863 goto print;
5865 if (i == ncodes)
5866 return NULL;
5868 print:
5869 printf("%c%c %s\n", status, staged_status, path);
5870 return NULL;
5873 static const struct got_error *
5874 cmd_status(int argc, char *argv[])
5876 const struct got_error *error = NULL;
5877 struct got_repository *repo = NULL;
5878 struct got_worktree *worktree = NULL;
5879 struct got_status_arg st;
5880 char *cwd = NULL;
5881 struct got_pathlist_head paths;
5882 struct got_pathlist_entry *pe;
5883 int ch, i, no_ignores = 0;
5884 int *pack_fds = NULL;
5886 TAILQ_INIT(&paths);
5888 memset(&st, 0, sizeof(st));
5889 st.status_codes = NULL;
5890 st.suppress = 0;
5892 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5893 switch (ch) {
5894 case 'I':
5895 no_ignores = 1;
5896 break;
5897 case 'S':
5898 if (st.status_codes != NULL && st.suppress == 0)
5899 option_conflict('S', 's');
5900 st.suppress = 1;
5901 /* fallthrough */
5902 case 's':
5903 for (i = 0; i < strlen(optarg); i++) {
5904 switch (optarg[i]) {
5905 case GOT_STATUS_MODIFY:
5906 case GOT_STATUS_ADD:
5907 case GOT_STATUS_DELETE:
5908 case GOT_STATUS_CONFLICT:
5909 case GOT_STATUS_MISSING:
5910 case GOT_STATUS_OBSTRUCTED:
5911 case GOT_STATUS_UNVERSIONED:
5912 case GOT_STATUS_MODE_CHANGE:
5913 case GOT_STATUS_NONEXISTENT:
5914 break;
5915 default:
5916 errx(1, "invalid status code '%c'",
5917 optarg[i]);
5920 if (ch == 's' && st.suppress)
5921 option_conflict('s', 'S');
5922 st.status_codes = optarg;
5923 break;
5924 default:
5925 usage_status();
5926 /* NOTREACHED */
5930 argc -= optind;
5931 argv += optind;
5933 #ifndef PROFILE
5934 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5935 NULL) == -1)
5936 err(1, "pledge");
5937 #endif
5938 cwd = getcwd(NULL, 0);
5939 if (cwd == NULL) {
5940 error = got_error_from_errno("getcwd");
5941 goto done;
5944 error = got_repo_pack_fds_open(&pack_fds);
5945 if (error != NULL)
5946 goto done;
5948 error = got_worktree_open(&worktree, cwd);
5949 if (error) {
5950 if (error->code == GOT_ERR_NOT_WORKTREE)
5951 error = wrap_not_worktree_error(error, "status", cwd);
5952 goto done;
5955 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5956 NULL, pack_fds);
5957 if (error != NULL)
5958 goto done;
5960 error = apply_unveil(got_repo_get_path(repo), 1,
5961 got_worktree_get_root_path(worktree));
5962 if (error)
5963 goto done;
5965 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5966 if (error)
5967 goto done;
5969 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5970 print_status, &st, check_cancelled, NULL);
5971 done:
5972 if (pack_fds) {
5973 const struct got_error *pack_err =
5974 got_repo_pack_fds_close(pack_fds);
5975 if (error == NULL)
5976 error = pack_err;
5979 TAILQ_FOREACH(pe, &paths, entry)
5980 free((char *)pe->path);
5981 got_pathlist_free(&paths);
5982 free(cwd);
5983 return error;
5986 __dead static void
5987 usage_ref(void)
5989 fprintf(stderr,
5990 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5991 "[-s reference] [-d] [name]\n",
5992 getprogname());
5993 exit(1);
5996 static const struct got_error *
5997 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5999 static const struct got_error *err = NULL;
6000 struct got_reflist_head refs;
6001 struct got_reflist_entry *re;
6003 TAILQ_INIT(&refs);
6004 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6005 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6006 repo);
6007 if (err)
6008 return err;
6010 TAILQ_FOREACH(re, &refs, entry) {
6011 char *refstr;
6012 refstr = got_ref_to_str(re->ref);
6013 if (refstr == NULL) {
6014 err = got_error_from_errno("got_ref_to_str");
6015 break;
6017 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6018 free(refstr);
6021 got_ref_list_free(&refs);
6022 return err;
6025 static const struct got_error *
6026 delete_ref_by_name(struct got_repository *repo, const char *refname)
6028 const struct got_error *err;
6029 struct got_reference *ref;
6031 err = got_ref_open(&ref, repo, refname, 0);
6032 if (err)
6033 return err;
6035 err = delete_ref(repo, ref);
6036 got_ref_close(ref);
6037 return err;
6040 static const struct got_error *
6041 add_ref(struct got_repository *repo, const char *refname, const char *target)
6043 const struct got_error *err = NULL;
6044 struct got_object_id *id = NULL;
6045 struct got_reference *ref = NULL;
6046 struct got_reflist_head refs;
6049 * Don't let the user create a reference name with a leading '-'.
6050 * While technically a valid reference name, this case is usually
6051 * an unintended typo.
6053 if (refname[0] == '-')
6054 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6056 TAILQ_INIT(&refs);
6057 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6058 if (err)
6059 goto done;
6060 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6061 &refs, repo);
6062 got_ref_list_free(&refs);
6063 if (err)
6064 goto done;
6066 err = got_ref_alloc(&ref, refname, id);
6067 if (err)
6068 goto done;
6070 err = got_ref_write(ref, repo);
6071 done:
6072 if (ref)
6073 got_ref_close(ref);
6074 free(id);
6075 return err;
6078 static const struct got_error *
6079 add_symref(struct got_repository *repo, const char *refname, const char *target)
6081 const struct got_error *err = NULL;
6082 struct got_reference *ref = NULL;
6083 struct got_reference *target_ref = NULL;
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 err = got_ref_open(&target_ref, repo, target, 0);
6094 if (err)
6095 return err;
6097 err = got_ref_alloc_symref(&ref, refname, target_ref);
6098 if (err)
6099 goto done;
6101 err = got_ref_write(ref, repo);
6102 done:
6103 if (target_ref)
6104 got_ref_close(target_ref);
6105 if (ref)
6106 got_ref_close(ref);
6107 return err;
6110 static const struct got_error *
6111 cmd_ref(int argc, char *argv[])
6113 const struct got_error *error = NULL;
6114 struct got_repository *repo = NULL;
6115 struct got_worktree *worktree = NULL;
6116 char *cwd = NULL, *repo_path = NULL;
6117 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6118 const char *obj_arg = NULL, *symref_target= NULL;
6119 char *refname = NULL;
6120 int *pack_fds = NULL;
6122 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6123 switch (ch) {
6124 case 'c':
6125 obj_arg = optarg;
6126 break;
6127 case 'd':
6128 do_delete = 1;
6129 break;
6130 case 'r':
6131 repo_path = realpath(optarg, NULL);
6132 if (repo_path == NULL)
6133 return got_error_from_errno2("realpath",
6134 optarg);
6135 got_path_strip_trailing_slashes(repo_path);
6136 break;
6137 case 'l':
6138 do_list = 1;
6139 break;
6140 case 's':
6141 symref_target = optarg;
6142 break;
6143 case 't':
6144 sort_by_time = 1;
6145 break;
6146 default:
6147 usage_ref();
6148 /* NOTREACHED */
6152 if (obj_arg && do_list)
6153 option_conflict('c', 'l');
6154 if (obj_arg && do_delete)
6155 option_conflict('c', 'd');
6156 if (obj_arg && symref_target)
6157 option_conflict('c', 's');
6158 if (symref_target && do_delete)
6159 option_conflict('s', 'd');
6160 if (symref_target && do_list)
6161 option_conflict('s', 'l');
6162 if (do_delete && do_list)
6163 option_conflict('d', 'l');
6164 if (sort_by_time && !do_list)
6165 errx(1, "-t option requires -l option");
6167 argc -= optind;
6168 argv += optind;
6170 if (do_list) {
6171 if (argc != 0 && argc != 1)
6172 usage_ref();
6173 if (argc == 1) {
6174 refname = strdup(argv[0]);
6175 if (refname == NULL) {
6176 error = got_error_from_errno("strdup");
6177 goto done;
6180 } else {
6181 if (argc != 1)
6182 usage_ref();
6183 refname = strdup(argv[0]);
6184 if (refname == NULL) {
6185 error = got_error_from_errno("strdup");
6186 goto done;
6190 if (refname)
6191 got_path_strip_trailing_slashes(refname);
6193 #ifndef PROFILE
6194 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6195 "sendfd unveil", NULL) == -1)
6196 err(1, "pledge");
6197 #endif
6198 cwd = getcwd(NULL, 0);
6199 if (cwd == NULL) {
6200 error = got_error_from_errno("getcwd");
6201 goto done;
6204 error = got_repo_pack_fds_open(&pack_fds);
6205 if (error != NULL)
6206 goto done;
6208 if (repo_path == NULL) {
6209 error = got_worktree_open(&worktree, cwd);
6210 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6211 goto done;
6212 else
6213 error = NULL;
6214 if (worktree) {
6215 repo_path =
6216 strdup(got_worktree_get_repo_path(worktree));
6217 if (repo_path == NULL)
6218 error = got_error_from_errno("strdup");
6219 if (error)
6220 goto done;
6221 } else {
6222 repo_path = strdup(cwd);
6223 if (repo_path == NULL) {
6224 error = got_error_from_errno("strdup");
6225 goto done;
6230 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6231 if (error != NULL)
6232 goto done;
6234 #ifndef PROFILE
6235 if (do_list) {
6236 /* Remove "cpath" promise. */
6237 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6238 NULL) == -1)
6239 err(1, "pledge");
6241 #endif
6243 error = apply_unveil(got_repo_get_path(repo), do_list,
6244 worktree ? got_worktree_get_root_path(worktree) : NULL);
6245 if (error)
6246 goto done;
6248 if (do_list)
6249 error = list_refs(repo, refname, sort_by_time);
6250 else if (do_delete)
6251 error = delete_ref_by_name(repo, refname);
6252 else if (symref_target)
6253 error = add_symref(repo, refname, symref_target);
6254 else {
6255 if (obj_arg == NULL)
6256 usage_ref();
6257 error = add_ref(repo, refname, obj_arg);
6259 done:
6260 free(refname);
6261 if (repo) {
6262 const struct got_error *close_err = got_repo_close(repo);
6263 if (error == NULL)
6264 error = close_err;
6266 if (worktree)
6267 got_worktree_close(worktree);
6268 if (pack_fds) {
6269 const struct got_error *pack_err =
6270 got_repo_pack_fds_close(pack_fds);
6271 if (error == NULL)
6272 error = pack_err;
6274 free(cwd);
6275 free(repo_path);
6276 return error;
6279 __dead static void
6280 usage_branch(void)
6282 fprintf(stderr,
6283 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6284 "[-n] [name]\n", getprogname());
6285 exit(1);
6288 static const struct got_error *
6289 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6290 struct got_reference *ref)
6292 const struct got_error *err = NULL;
6293 const char *refname, *marker = " ";
6294 char *refstr;
6296 refname = got_ref_get_name(ref);
6297 if (worktree && strcmp(refname,
6298 got_worktree_get_head_ref_name(worktree)) == 0) {
6299 struct got_object_id *id = NULL;
6301 err = got_ref_resolve(&id, repo, ref);
6302 if (err)
6303 return err;
6304 if (got_object_id_cmp(id,
6305 got_worktree_get_base_commit_id(worktree)) == 0)
6306 marker = "* ";
6307 else
6308 marker = "~ ";
6309 free(id);
6312 if (strncmp(refname, "refs/heads/", 11) == 0)
6313 refname += 11;
6314 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6315 refname += 18;
6316 if (strncmp(refname, "refs/remotes/", 13) == 0)
6317 refname += 13;
6319 refstr = got_ref_to_str(ref);
6320 if (refstr == NULL)
6321 return got_error_from_errno("got_ref_to_str");
6323 printf("%s%s: %s\n", marker, refname, refstr);
6324 free(refstr);
6325 return NULL;
6328 static const struct got_error *
6329 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6331 const char *refname;
6333 if (worktree == NULL)
6334 return got_error(GOT_ERR_NOT_WORKTREE);
6336 refname = got_worktree_get_head_ref_name(worktree);
6338 if (strncmp(refname, "refs/heads/", 11) == 0)
6339 refname += 11;
6340 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6341 refname += 18;
6343 printf("%s\n", refname);
6345 return NULL;
6348 static const struct got_error *
6349 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6350 int sort_by_time)
6352 static const struct got_error *err = NULL;
6353 struct got_reflist_head refs;
6354 struct got_reflist_entry *re;
6355 struct got_reference *temp_ref = NULL;
6356 int rebase_in_progress, histedit_in_progress;
6358 TAILQ_INIT(&refs);
6360 if (worktree) {
6361 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6362 worktree);
6363 if (err)
6364 return err;
6366 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6367 worktree);
6368 if (err)
6369 return err;
6371 if (rebase_in_progress || histedit_in_progress) {
6372 err = got_ref_open(&temp_ref, repo,
6373 got_worktree_get_head_ref_name(worktree), 0);
6374 if (err)
6375 return err;
6376 list_branch(repo, worktree, temp_ref);
6377 got_ref_close(temp_ref);
6381 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6382 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6383 repo);
6384 if (err)
6385 return err;
6387 TAILQ_FOREACH(re, &refs, entry)
6388 list_branch(repo, worktree, re->ref);
6390 got_ref_list_free(&refs);
6392 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6393 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6394 repo);
6395 if (err)
6396 return err;
6398 TAILQ_FOREACH(re, &refs, entry)
6399 list_branch(repo, worktree, re->ref);
6401 got_ref_list_free(&refs);
6403 return NULL;
6406 static const struct got_error *
6407 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6408 const char *branch_name)
6410 const struct got_error *err = NULL;
6411 struct got_reference *ref = NULL;
6412 char *refname, *remote_refname = NULL;
6414 if (strncmp(branch_name, "refs/", 5) == 0)
6415 branch_name += 5;
6416 if (strncmp(branch_name, "heads/", 6) == 0)
6417 branch_name += 6;
6418 else if (strncmp(branch_name, "remotes/", 8) == 0)
6419 branch_name += 8;
6421 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6422 return got_error_from_errno("asprintf");
6424 if (asprintf(&remote_refname, "refs/remotes/%s",
6425 branch_name) == -1) {
6426 err = got_error_from_errno("asprintf");
6427 goto done;
6430 err = got_ref_open(&ref, repo, refname, 0);
6431 if (err) {
6432 const struct got_error *err2;
6433 if (err->code != GOT_ERR_NOT_REF)
6434 goto done;
6436 * Keep 'err' intact such that if neither branch exists
6437 * we report "refs/heads" rather than "refs/remotes" in
6438 * our error message.
6440 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6441 if (err2)
6442 goto done;
6443 err = NULL;
6446 if (worktree &&
6447 strcmp(got_worktree_get_head_ref_name(worktree),
6448 got_ref_get_name(ref)) == 0) {
6449 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6450 "will not delete this work tree's current branch");
6451 goto done;
6454 err = delete_ref(repo, ref);
6455 done:
6456 if (ref)
6457 got_ref_close(ref);
6458 free(refname);
6459 free(remote_refname);
6460 return err;
6463 static const struct got_error *
6464 add_branch(struct got_repository *repo, const char *branch_name,
6465 struct got_object_id *base_commit_id)
6467 const struct got_error *err = NULL;
6468 struct got_reference *ref = NULL;
6469 char *base_refname = NULL, *refname = NULL;
6472 * Don't let the user create a branch name with a leading '-'.
6473 * While technically a valid reference name, this case is usually
6474 * an unintended typo.
6476 if (branch_name[0] == '-')
6477 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6479 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6480 branch_name += 11;
6482 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6483 err = got_error_from_errno("asprintf");
6484 goto done;
6487 err = got_ref_open(&ref, repo, refname, 0);
6488 if (err == NULL) {
6489 err = got_error(GOT_ERR_BRANCH_EXISTS);
6490 goto done;
6491 } else if (err->code != GOT_ERR_NOT_REF)
6492 goto done;
6494 err = got_ref_alloc(&ref, refname, base_commit_id);
6495 if (err)
6496 goto done;
6498 err = got_ref_write(ref, repo);
6499 done:
6500 if (ref)
6501 got_ref_close(ref);
6502 free(base_refname);
6503 free(refname);
6504 return err;
6507 static const struct got_error *
6508 cmd_branch(int argc, char *argv[])
6510 const struct got_error *error = NULL;
6511 struct got_repository *repo = NULL;
6512 struct got_worktree *worktree = NULL;
6513 char *cwd = NULL, *repo_path = NULL;
6514 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6515 const char *delref = NULL, *commit_id_arg = NULL;
6516 struct got_reference *ref = NULL;
6517 struct got_pathlist_head paths;
6518 struct got_pathlist_entry *pe;
6519 struct got_object_id *commit_id = NULL;
6520 char *commit_id_str = NULL;
6521 int *pack_fds = NULL;
6523 TAILQ_INIT(&paths);
6525 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6526 switch (ch) {
6527 case 'c':
6528 commit_id_arg = optarg;
6529 break;
6530 case 'd':
6531 delref = optarg;
6532 break;
6533 case 'r':
6534 repo_path = realpath(optarg, NULL);
6535 if (repo_path == NULL)
6536 return got_error_from_errno2("realpath",
6537 optarg);
6538 got_path_strip_trailing_slashes(repo_path);
6539 break;
6540 case 'l':
6541 do_list = 1;
6542 break;
6543 case 'n':
6544 do_update = 0;
6545 break;
6546 case 't':
6547 sort_by_time = 1;
6548 break;
6549 default:
6550 usage_branch();
6551 /* NOTREACHED */
6555 if (do_list && delref)
6556 option_conflict('l', 'd');
6557 if (sort_by_time && !do_list)
6558 errx(1, "-t option requires -l option");
6560 argc -= optind;
6561 argv += optind;
6563 if (!do_list && !delref && argc == 0)
6564 do_show = 1;
6566 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6567 errx(1, "-c option can only be used when creating a branch");
6569 if (do_list || delref) {
6570 if (argc > 0)
6571 usage_branch();
6572 } else if (!do_show && argc != 1)
6573 usage_branch();
6575 #ifndef PROFILE
6576 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6577 "sendfd unveil", NULL) == -1)
6578 err(1, "pledge");
6579 #endif
6580 cwd = getcwd(NULL, 0);
6581 if (cwd == NULL) {
6582 error = got_error_from_errno("getcwd");
6583 goto done;
6586 error = got_repo_pack_fds_open(&pack_fds);
6587 if (error != NULL)
6588 goto done;
6590 if (repo_path == NULL) {
6591 error = got_worktree_open(&worktree, cwd);
6592 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6593 goto done;
6594 else
6595 error = NULL;
6596 if (worktree) {
6597 repo_path =
6598 strdup(got_worktree_get_repo_path(worktree));
6599 if (repo_path == NULL)
6600 error = got_error_from_errno("strdup");
6601 if (error)
6602 goto done;
6603 } else {
6604 repo_path = strdup(cwd);
6605 if (repo_path == NULL) {
6606 error = got_error_from_errno("strdup");
6607 goto done;
6612 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6613 if (error != NULL)
6614 goto done;
6616 #ifndef PROFILE
6617 if (do_list || do_show) {
6618 /* Remove "cpath" promise. */
6619 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6620 NULL) == -1)
6621 err(1, "pledge");
6623 #endif
6625 error = apply_unveil(got_repo_get_path(repo), do_list,
6626 worktree ? got_worktree_get_root_path(worktree) : NULL);
6627 if (error)
6628 goto done;
6630 if (do_show)
6631 error = show_current_branch(repo, worktree);
6632 else if (do_list)
6633 error = list_branches(repo, worktree, sort_by_time);
6634 else if (delref)
6635 error = delete_branch(repo, worktree, delref);
6636 else {
6637 struct got_reflist_head refs;
6638 TAILQ_INIT(&refs);
6639 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6640 NULL);
6641 if (error)
6642 goto done;
6643 if (commit_id_arg == NULL)
6644 commit_id_arg = worktree ?
6645 got_worktree_get_head_ref_name(worktree) :
6646 GOT_REF_HEAD;
6647 error = got_repo_match_object_id(&commit_id, NULL,
6648 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6649 got_ref_list_free(&refs);
6650 if (error)
6651 goto done;
6652 error = add_branch(repo, argv[0], commit_id);
6653 if (error)
6654 goto done;
6655 if (worktree && do_update) {
6656 struct got_update_progress_arg upa;
6657 char *branch_refname = NULL;
6659 error = got_object_id_str(&commit_id_str, commit_id);
6660 if (error)
6661 goto done;
6662 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6663 worktree);
6664 if (error)
6665 goto done;
6666 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6667 == -1) {
6668 error = got_error_from_errno("asprintf");
6669 goto done;
6671 error = got_ref_open(&ref, repo, branch_refname, 0);
6672 free(branch_refname);
6673 if (error)
6674 goto done;
6675 error = switch_head_ref(ref, commit_id, worktree,
6676 repo);
6677 if (error)
6678 goto done;
6679 error = got_worktree_set_base_commit_id(worktree, repo,
6680 commit_id);
6681 if (error)
6682 goto done;
6683 memset(&upa, 0, sizeof(upa));
6684 error = got_worktree_checkout_files(worktree, &paths,
6685 repo, update_progress, &upa, check_cancelled,
6686 NULL);
6687 if (error)
6688 goto done;
6689 if (upa.did_something) {
6690 printf("Updated to %s: %s\n",
6691 got_worktree_get_head_ref_name(worktree),
6692 commit_id_str);
6694 print_update_progress_stats(&upa);
6697 done:
6698 if (ref)
6699 got_ref_close(ref);
6700 if (repo) {
6701 const struct got_error *close_err = got_repo_close(repo);
6702 if (error == NULL)
6703 error = close_err;
6705 if (worktree)
6706 got_worktree_close(worktree);
6707 if (pack_fds) {
6708 const struct got_error *pack_err =
6709 got_repo_pack_fds_close(pack_fds);
6710 if (error == NULL)
6711 error = pack_err;
6713 free(cwd);
6714 free(repo_path);
6715 free(commit_id);
6716 free(commit_id_str);
6717 TAILQ_FOREACH(pe, &paths, entry)
6718 free((char *)pe->path);
6719 got_pathlist_free(&paths);
6720 return error;
6724 __dead static void
6725 usage_tag(void)
6727 fprintf(stderr,
6728 "usage: %s tag [-c commit] [-r repository] [-l] "
6729 "[-m message] name\n", getprogname());
6730 exit(1);
6733 #if 0
6734 static const struct got_error *
6735 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6737 const struct got_error *err = NULL;
6738 struct got_reflist_entry *re, *se, *new;
6739 struct got_object_id *re_id, *se_id;
6740 struct got_tag_object *re_tag, *se_tag;
6741 time_t re_time, se_time;
6743 STAILQ_FOREACH(re, tags, entry) {
6744 se = STAILQ_FIRST(sorted);
6745 if (se == NULL) {
6746 err = got_reflist_entry_dup(&new, re);
6747 if (err)
6748 return err;
6749 STAILQ_INSERT_HEAD(sorted, new, entry);
6750 continue;
6751 } else {
6752 err = got_ref_resolve(&re_id, repo, re->ref);
6753 if (err)
6754 break;
6755 err = got_object_open_as_tag(&re_tag, repo, re_id);
6756 free(re_id);
6757 if (err)
6758 break;
6759 re_time = got_object_tag_get_tagger_time(re_tag);
6760 got_object_tag_close(re_tag);
6763 while (se) {
6764 err = got_ref_resolve(&se_id, repo, re->ref);
6765 if (err)
6766 break;
6767 err = got_object_open_as_tag(&se_tag, repo, se_id);
6768 free(se_id);
6769 if (err)
6770 break;
6771 se_time = got_object_tag_get_tagger_time(se_tag);
6772 got_object_tag_close(se_tag);
6774 if (se_time > re_time) {
6775 err = got_reflist_entry_dup(&new, re);
6776 if (err)
6777 return err;
6778 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6779 break;
6781 se = STAILQ_NEXT(se, entry);
6782 continue;
6785 done:
6786 return err;
6788 #endif
6790 static const struct got_error *
6791 list_tags(struct got_repository *repo)
6793 static const struct got_error *err = NULL;
6794 struct got_reflist_head refs;
6795 struct got_reflist_entry *re;
6797 TAILQ_INIT(&refs);
6799 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6800 if (err)
6801 return err;
6803 TAILQ_FOREACH(re, &refs, entry) {
6804 const char *refname;
6805 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6806 char datebuf[26];
6807 const char *tagger;
6808 time_t tagger_time;
6809 struct got_object_id *id;
6810 struct got_tag_object *tag;
6811 struct got_commit_object *commit = NULL;
6813 refname = got_ref_get_name(re->ref);
6814 if (strncmp(refname, "refs/tags/", 10) != 0)
6815 continue;
6816 refname += 10;
6817 refstr = got_ref_to_str(re->ref);
6818 if (refstr == NULL) {
6819 err = got_error_from_errno("got_ref_to_str");
6820 break;
6822 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6823 free(refstr);
6825 err = got_ref_resolve(&id, repo, re->ref);
6826 if (err)
6827 break;
6828 err = got_object_open_as_tag(&tag, repo, id);
6829 if (err) {
6830 if (err->code != GOT_ERR_OBJ_TYPE) {
6831 free(id);
6832 break;
6834 /* "lightweight" tag */
6835 err = got_object_open_as_commit(&commit, repo, id);
6836 if (err) {
6837 free(id);
6838 break;
6840 tagger = got_object_commit_get_committer(commit);
6841 tagger_time =
6842 got_object_commit_get_committer_time(commit);
6843 err = got_object_id_str(&id_str, id);
6844 free(id);
6845 if (err)
6846 break;
6847 } else {
6848 free(id);
6849 tagger = got_object_tag_get_tagger(tag);
6850 tagger_time = got_object_tag_get_tagger_time(tag);
6851 err = got_object_id_str(&id_str,
6852 got_object_tag_get_object_id(tag));
6853 if (err)
6854 break;
6856 printf("from: %s\n", tagger);
6857 datestr = get_datestr(&tagger_time, datebuf);
6858 if (datestr)
6859 printf("date: %s UTC\n", datestr);
6860 if (commit)
6861 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6862 else {
6863 switch (got_object_tag_get_object_type(tag)) {
6864 case GOT_OBJ_TYPE_BLOB:
6865 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6866 id_str);
6867 break;
6868 case GOT_OBJ_TYPE_TREE:
6869 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6870 id_str);
6871 break;
6872 case GOT_OBJ_TYPE_COMMIT:
6873 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6874 id_str);
6875 break;
6876 case GOT_OBJ_TYPE_TAG:
6877 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6878 id_str);
6879 break;
6880 default:
6881 break;
6884 free(id_str);
6885 if (commit) {
6886 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6887 if (err)
6888 break;
6889 got_object_commit_close(commit);
6890 } else {
6891 tagmsg0 = strdup(got_object_tag_get_message(tag));
6892 got_object_tag_close(tag);
6893 if (tagmsg0 == NULL) {
6894 err = got_error_from_errno("strdup");
6895 break;
6899 tagmsg = tagmsg0;
6900 do {
6901 line = strsep(&tagmsg, "\n");
6902 if (line)
6903 printf(" %s\n", line);
6904 } while (line);
6905 free(tagmsg0);
6908 got_ref_list_free(&refs);
6909 return NULL;
6912 static const struct got_error *
6913 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6914 const char *tag_name, const char *repo_path)
6916 const struct got_error *err = NULL;
6917 char *template = NULL, *initial_content = NULL;
6918 char *editor = NULL;
6919 int initial_content_len;
6920 int fd = -1;
6922 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6923 err = got_error_from_errno("asprintf");
6924 goto done;
6927 initial_content_len = asprintf(&initial_content,
6928 "\n# tagging commit %s as %s\n",
6929 commit_id_str, tag_name);
6930 if (initial_content_len == -1) {
6931 err = got_error_from_errno("asprintf");
6932 goto done;
6935 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6936 if (err)
6937 goto done;
6939 if (write(fd, initial_content, initial_content_len) == -1) {
6940 err = got_error_from_errno2("write", *tagmsg_path);
6941 goto done;
6944 err = get_editor(&editor);
6945 if (err)
6946 goto done;
6947 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6948 initial_content_len, 1);
6949 done:
6950 free(initial_content);
6951 free(template);
6952 free(editor);
6954 if (fd != -1 && close(fd) == -1 && err == NULL)
6955 err = got_error_from_errno2("close", *tagmsg_path);
6957 /* Editor is done; we can now apply unveil(2) */
6958 if (err == NULL)
6959 err = apply_unveil(repo_path, 0, NULL);
6960 if (err) {
6961 free(*tagmsg);
6962 *tagmsg = NULL;
6964 return err;
6967 static const struct got_error *
6968 add_tag(struct got_repository *repo, const char *tagger,
6969 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6971 const struct got_error *err = NULL;
6972 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6973 char *label = NULL, *commit_id_str = NULL;
6974 struct got_reference *ref = NULL;
6975 char *refname = NULL, *tagmsg = NULL;
6976 char *tagmsg_path = NULL, *tag_id_str = NULL;
6977 int preserve_tagmsg = 0;
6978 struct got_reflist_head refs;
6980 TAILQ_INIT(&refs);
6983 * Don't let the user create a tag name with a leading '-'.
6984 * While technically a valid reference name, this case is usually
6985 * an unintended typo.
6987 if (tag_name[0] == '-')
6988 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6990 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6991 if (err)
6992 goto done;
6994 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6995 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6996 if (err)
6997 goto done;
6999 err = got_object_id_str(&commit_id_str, commit_id);
7000 if (err)
7001 goto done;
7003 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7004 refname = strdup(tag_name);
7005 if (refname == NULL) {
7006 err = got_error_from_errno("strdup");
7007 goto done;
7009 tag_name += 10;
7010 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
7011 err = got_error_from_errno("asprintf");
7012 goto done;
7015 err = got_ref_open(&ref, repo, refname, 0);
7016 if (err == NULL) {
7017 err = got_error(GOT_ERR_TAG_EXISTS);
7018 goto done;
7019 } else if (err->code != GOT_ERR_NOT_REF)
7020 goto done;
7022 if (tagmsg_arg == NULL) {
7023 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7024 tag_name, got_repo_get_path(repo));
7025 if (err) {
7026 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7027 tagmsg_path != NULL)
7028 preserve_tagmsg = 1;
7029 goto done;
7033 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7034 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7035 if (err) {
7036 if (tagmsg_path)
7037 preserve_tagmsg = 1;
7038 goto done;
7041 err = got_ref_alloc(&ref, refname, tag_id);
7042 if (err) {
7043 if (tagmsg_path)
7044 preserve_tagmsg = 1;
7045 goto done;
7048 err = got_ref_write(ref, repo);
7049 if (err) {
7050 if (tagmsg_path)
7051 preserve_tagmsg = 1;
7052 goto done;
7055 err = got_object_id_str(&tag_id_str, tag_id);
7056 if (err) {
7057 if (tagmsg_path)
7058 preserve_tagmsg = 1;
7059 goto done;
7061 printf("Created tag %s\n", tag_id_str);
7062 done:
7063 if (preserve_tagmsg) {
7064 fprintf(stderr, "%s: tag message preserved in %s\n",
7065 getprogname(), tagmsg_path);
7066 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7067 err = got_error_from_errno2("unlink", tagmsg_path);
7068 free(tag_id_str);
7069 if (ref)
7070 got_ref_close(ref);
7071 free(commit_id);
7072 free(commit_id_str);
7073 free(refname);
7074 free(tagmsg);
7075 free(tagmsg_path);
7076 got_ref_list_free(&refs);
7077 return err;
7080 static const struct got_error *
7081 cmd_tag(int argc, char *argv[])
7083 const struct got_error *error = NULL;
7084 struct got_repository *repo = NULL;
7085 struct got_worktree *worktree = NULL;
7086 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7087 char *gitconfig_path = NULL, *tagger = NULL;
7088 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
7089 int ch, do_list = 0;
7090 int *pack_fds = NULL;
7092 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7093 switch (ch) {
7094 case 'c':
7095 commit_id_arg = optarg;
7096 break;
7097 case 'm':
7098 tagmsg = optarg;
7099 break;
7100 case 'r':
7101 repo_path = realpath(optarg, NULL);
7102 if (repo_path == NULL)
7103 return got_error_from_errno2("realpath",
7104 optarg);
7105 got_path_strip_trailing_slashes(repo_path);
7106 break;
7107 case 'l':
7108 do_list = 1;
7109 break;
7110 default:
7111 usage_tag();
7112 /* NOTREACHED */
7116 argc -= optind;
7117 argv += optind;
7119 if (do_list) {
7120 if (commit_id_arg != NULL)
7121 errx(1,
7122 "-c option can only be used when creating a tag");
7123 if (tagmsg)
7124 option_conflict('l', 'm');
7125 if (argc > 0)
7126 usage_tag();
7127 } else if (argc != 1)
7128 usage_tag();
7130 tag_name = argv[0];
7132 #ifndef PROFILE
7133 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7134 "sendfd unveil", NULL) == -1)
7135 err(1, "pledge");
7136 #endif
7137 cwd = getcwd(NULL, 0);
7138 if (cwd == NULL) {
7139 error = got_error_from_errno("getcwd");
7140 goto done;
7143 error = got_repo_pack_fds_open(&pack_fds);
7144 if (error != NULL)
7145 goto done;
7147 if (repo_path == NULL) {
7148 error = got_worktree_open(&worktree, cwd);
7149 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7150 goto done;
7151 else
7152 error = NULL;
7153 if (worktree) {
7154 repo_path =
7155 strdup(got_worktree_get_repo_path(worktree));
7156 if (repo_path == NULL)
7157 error = got_error_from_errno("strdup");
7158 if (error)
7159 goto done;
7160 } else {
7161 repo_path = strdup(cwd);
7162 if (repo_path == NULL) {
7163 error = got_error_from_errno("strdup");
7164 goto done;
7169 if (do_list) {
7170 if (worktree) {
7171 /* Release work tree lock. */
7172 got_worktree_close(worktree);
7173 worktree = NULL;
7175 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7176 if (error != NULL)
7177 goto done;
7179 #ifndef PROFILE
7180 /* Remove "cpath" promise. */
7181 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7182 NULL) == -1)
7183 err(1, "pledge");
7184 #endif
7185 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7186 if (error)
7187 goto done;
7188 error = list_tags(repo);
7189 } else {
7190 error = get_gitconfig_path(&gitconfig_path);
7191 if (error)
7192 goto done;
7193 error = got_repo_open(&repo, repo_path, gitconfig_path,
7194 pack_fds);
7195 if (error != NULL)
7196 goto done;
7198 error = get_author(&tagger, repo, worktree);
7199 if (error)
7200 goto done;
7201 if (worktree) {
7202 /* Release work tree lock. */
7203 got_worktree_close(worktree);
7204 worktree = NULL;
7207 if (tagmsg) {
7208 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7209 if (error)
7210 goto done;
7213 if (commit_id_arg == NULL) {
7214 struct got_reference *head_ref;
7215 struct got_object_id *commit_id;
7216 error = got_ref_open(&head_ref, repo,
7217 worktree ? got_worktree_get_head_ref_name(worktree)
7218 : GOT_REF_HEAD, 0);
7219 if (error)
7220 goto done;
7221 error = got_ref_resolve(&commit_id, repo, head_ref);
7222 got_ref_close(head_ref);
7223 if (error)
7224 goto done;
7225 error = got_object_id_str(&commit_id_str, commit_id);
7226 free(commit_id);
7227 if (error)
7228 goto done;
7231 error = add_tag(repo, tagger, tag_name,
7232 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7234 done:
7235 if (repo) {
7236 const struct got_error *close_err = got_repo_close(repo);
7237 if (error == NULL)
7238 error = close_err;
7240 if (worktree)
7241 got_worktree_close(worktree);
7242 if (pack_fds) {
7243 const struct got_error *pack_err =
7244 got_repo_pack_fds_close(pack_fds);
7245 if (error == NULL)
7246 error = pack_err;
7248 free(cwd);
7249 free(repo_path);
7250 free(gitconfig_path);
7251 free(commit_id_str);
7252 free(tagger);
7253 return error;
7256 __dead static void
7257 usage_add(void)
7259 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7260 getprogname());
7261 exit(1);
7264 static const struct got_error *
7265 add_progress(void *arg, unsigned char status, const char *path)
7267 while (path[0] == '/')
7268 path++;
7269 printf("%c %s\n", status, path);
7270 return NULL;
7273 static const struct got_error *
7274 cmd_add(int argc, char *argv[])
7276 const struct got_error *error = NULL;
7277 struct got_repository *repo = NULL;
7278 struct got_worktree *worktree = NULL;
7279 char *cwd = NULL;
7280 struct got_pathlist_head paths;
7281 struct got_pathlist_entry *pe;
7282 int ch, can_recurse = 0, no_ignores = 0;
7283 int *pack_fds = NULL;
7285 TAILQ_INIT(&paths);
7287 while ((ch = getopt(argc, argv, "IR")) != -1) {
7288 switch (ch) {
7289 case 'I':
7290 no_ignores = 1;
7291 break;
7292 case 'R':
7293 can_recurse = 1;
7294 break;
7295 default:
7296 usage_add();
7297 /* NOTREACHED */
7301 argc -= optind;
7302 argv += optind;
7304 #ifndef PROFILE
7305 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7306 NULL) == -1)
7307 err(1, "pledge");
7308 #endif
7309 if (argc < 1)
7310 usage_add();
7312 cwd = getcwd(NULL, 0);
7313 if (cwd == NULL) {
7314 error = got_error_from_errno("getcwd");
7315 goto done;
7318 error = got_repo_pack_fds_open(&pack_fds);
7319 if (error != NULL)
7320 goto done;
7322 error = got_worktree_open(&worktree, cwd);
7323 if (error) {
7324 if (error->code == GOT_ERR_NOT_WORKTREE)
7325 error = wrap_not_worktree_error(error, "add", cwd);
7326 goto done;
7329 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7330 NULL, pack_fds);
7331 if (error != NULL)
7332 goto done;
7334 error = apply_unveil(got_repo_get_path(repo), 1,
7335 got_worktree_get_root_path(worktree));
7336 if (error)
7337 goto done;
7339 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7340 if (error)
7341 goto done;
7343 if (!can_recurse) {
7344 char *ondisk_path;
7345 struct stat sb;
7346 TAILQ_FOREACH(pe, &paths, entry) {
7347 if (asprintf(&ondisk_path, "%s/%s",
7348 got_worktree_get_root_path(worktree),
7349 pe->path) == -1) {
7350 error = got_error_from_errno("asprintf");
7351 goto done;
7353 if (lstat(ondisk_path, &sb) == -1) {
7354 if (errno == ENOENT) {
7355 free(ondisk_path);
7356 continue;
7358 error = got_error_from_errno2("lstat",
7359 ondisk_path);
7360 free(ondisk_path);
7361 goto done;
7363 free(ondisk_path);
7364 if (S_ISDIR(sb.st_mode)) {
7365 error = got_error_msg(GOT_ERR_BAD_PATH,
7366 "adding directories requires -R option");
7367 goto done;
7372 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7373 NULL, repo, no_ignores);
7374 done:
7375 if (repo) {
7376 const struct got_error *close_err = got_repo_close(repo);
7377 if (error == NULL)
7378 error = close_err;
7380 if (worktree)
7381 got_worktree_close(worktree);
7382 if (pack_fds) {
7383 const struct got_error *pack_err =
7384 got_repo_pack_fds_close(pack_fds);
7385 if (error == NULL)
7386 error = pack_err;
7388 TAILQ_FOREACH(pe, &paths, entry)
7389 free((char *)pe->path);
7390 got_pathlist_free(&paths);
7391 free(cwd);
7392 return error;
7395 __dead static void
7396 usage_remove(void)
7398 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7399 "path ...\n", getprogname());
7400 exit(1);
7403 static const struct got_error *
7404 print_remove_status(void *arg, unsigned char status,
7405 unsigned char staged_status, const char *path)
7407 while (path[0] == '/')
7408 path++;
7409 if (status == GOT_STATUS_NONEXISTENT)
7410 return NULL;
7411 if (status == staged_status && (status == GOT_STATUS_DELETE))
7412 status = GOT_STATUS_NO_CHANGE;
7413 printf("%c%c %s\n", status, staged_status, path);
7414 return NULL;
7417 static const struct got_error *
7418 cmd_remove(int argc, char *argv[])
7420 const struct got_error *error = NULL;
7421 struct got_worktree *worktree = NULL;
7422 struct got_repository *repo = NULL;
7423 const char *status_codes = NULL;
7424 char *cwd = NULL;
7425 struct got_pathlist_head paths;
7426 struct got_pathlist_entry *pe;
7427 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7428 int ignore_missing_paths = 0;
7429 int *pack_fds = NULL;
7431 TAILQ_INIT(&paths);
7433 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7434 switch (ch) {
7435 case 'f':
7436 delete_local_mods = 1;
7437 ignore_missing_paths = 1;
7438 break;
7439 case 'k':
7440 keep_on_disk = 1;
7441 break;
7442 case 'R':
7443 can_recurse = 1;
7444 break;
7445 case 's':
7446 for (i = 0; i < strlen(optarg); i++) {
7447 switch (optarg[i]) {
7448 case GOT_STATUS_MODIFY:
7449 delete_local_mods = 1;
7450 break;
7451 case GOT_STATUS_MISSING:
7452 ignore_missing_paths = 1;
7453 break;
7454 default:
7455 errx(1, "invalid status code '%c'",
7456 optarg[i]);
7459 status_codes = optarg;
7460 break;
7461 default:
7462 usage_remove();
7463 /* NOTREACHED */
7467 argc -= optind;
7468 argv += optind;
7470 #ifndef PROFILE
7471 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7472 NULL) == -1)
7473 err(1, "pledge");
7474 #endif
7475 if (argc < 1)
7476 usage_remove();
7478 cwd = getcwd(NULL, 0);
7479 if (cwd == NULL) {
7480 error = got_error_from_errno("getcwd");
7481 goto done;
7484 error = got_repo_pack_fds_open(&pack_fds);
7485 if (error != NULL)
7486 goto done;
7488 error = got_worktree_open(&worktree, cwd);
7489 if (error) {
7490 if (error->code == GOT_ERR_NOT_WORKTREE)
7491 error = wrap_not_worktree_error(error, "remove", cwd);
7492 goto done;
7495 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7496 NULL, pack_fds);
7497 if (error)
7498 goto done;
7500 error = apply_unveil(got_repo_get_path(repo), 1,
7501 got_worktree_get_root_path(worktree));
7502 if (error)
7503 goto done;
7505 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7506 if (error)
7507 goto done;
7509 if (!can_recurse) {
7510 char *ondisk_path;
7511 struct stat sb;
7512 TAILQ_FOREACH(pe, &paths, entry) {
7513 if (asprintf(&ondisk_path, "%s/%s",
7514 got_worktree_get_root_path(worktree),
7515 pe->path) == -1) {
7516 error = got_error_from_errno("asprintf");
7517 goto done;
7519 if (lstat(ondisk_path, &sb) == -1) {
7520 if (errno == ENOENT) {
7521 free(ondisk_path);
7522 continue;
7524 error = got_error_from_errno2("lstat",
7525 ondisk_path);
7526 free(ondisk_path);
7527 goto done;
7529 free(ondisk_path);
7530 if (S_ISDIR(sb.st_mode)) {
7531 error = got_error_msg(GOT_ERR_BAD_PATH,
7532 "removing directories requires -R option");
7533 goto done;
7538 error = got_worktree_schedule_delete(worktree, &paths,
7539 delete_local_mods, status_codes, print_remove_status, NULL,
7540 repo, keep_on_disk, ignore_missing_paths);
7541 done:
7542 if (repo) {
7543 const struct got_error *close_err = got_repo_close(repo);
7544 if (error == NULL)
7545 error = close_err;
7547 if (worktree)
7548 got_worktree_close(worktree);
7549 if (pack_fds) {
7550 const struct got_error *pack_err =
7551 got_repo_pack_fds_close(pack_fds);
7552 if (error == NULL)
7553 error = pack_err;
7555 TAILQ_FOREACH(pe, &paths, entry)
7556 free((char *)pe->path);
7557 got_pathlist_free(&paths);
7558 free(cwd);
7559 return error;
7562 __dead static void
7563 usage_patch(void)
7565 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7566 "[-R] [patchfile]\n", getprogname());
7567 exit(1);
7570 static const struct got_error *
7571 patch_from_stdin(int *patchfd)
7573 const struct got_error *err = NULL;
7574 ssize_t r;
7575 char *path, buf[BUFSIZ];
7576 sig_t sighup, sigint, sigquit;
7578 err = got_opentemp_named_fd(&path, patchfd,
7579 GOT_TMPDIR_STR "/got-patch");
7580 if (err)
7581 return err;
7582 unlink(path);
7583 free(path);
7585 sighup = signal(SIGHUP, SIG_DFL);
7586 sigint = signal(SIGINT, SIG_DFL);
7587 sigquit = signal(SIGQUIT, SIG_DFL);
7589 for (;;) {
7590 r = read(0, buf, sizeof(buf));
7591 if (r == -1) {
7592 err = got_error_from_errno("read");
7593 break;
7595 if (r == 0)
7596 break;
7597 if (write(*patchfd, buf, r) == -1) {
7598 err = got_error_from_errno("write");
7599 break;
7603 signal(SIGHUP, sighup);
7604 signal(SIGINT, sigint);
7605 signal(SIGQUIT, sigquit);
7607 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7608 err = got_error_from_errno("lseek");
7610 if (err != NULL) {
7611 close(*patchfd);
7612 *patchfd = -1;
7615 return err;
7618 static const struct got_error *
7619 patch_progress(void *arg, const char *old, const char *new,
7620 unsigned char status, const struct got_error *error, long old_from,
7621 long old_lines, long new_from, long new_lines, long offset,
7622 const struct got_error *hunk_err)
7624 const char *path = new == NULL ? old : new;
7626 while (*path == '/')
7627 path++;
7629 if (status != 0)
7630 printf("%c %s\n", status, path);
7632 if (error != NULL)
7633 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7635 if (offset != 0 || hunk_err != NULL) {
7636 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7637 old_lines, new_from, new_lines);
7638 if (hunk_err != NULL)
7639 printf("%s\n", hunk_err->msg);
7640 else
7641 printf("applied with offset %ld\n", offset);
7644 return NULL;
7647 static const struct got_error *
7648 cmd_patch(int argc, char *argv[])
7650 const struct got_error *error = NULL, *close_error = NULL;
7651 struct got_worktree *worktree = NULL;
7652 struct got_repository *repo = NULL;
7653 const char *errstr;
7654 char *cwd = NULL;
7655 int ch, nop = 0, strip = -1, reverse = 0;
7656 int patchfd;
7657 int *pack_fds = NULL;
7659 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7660 switch (ch) {
7661 case 'n':
7662 nop = 1;
7663 break;
7664 case 'p':
7665 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7666 if (errstr != NULL)
7667 errx(1, "pathname strip count is %s: %s",
7668 errstr, optarg);
7669 break;
7670 case 'R':
7671 reverse = 1;
7672 break;
7673 default:
7674 usage_patch();
7675 /* NOTREACHED */
7679 argc -= optind;
7680 argv += optind;
7682 if (argc == 0) {
7683 error = patch_from_stdin(&patchfd);
7684 if (error)
7685 return error;
7686 } else if (argc == 1) {
7687 patchfd = open(argv[0], O_RDONLY);
7688 if (patchfd == -1) {
7689 error = got_error_from_errno2("open", argv[0]);
7690 return error;
7692 } else
7693 usage_patch();
7695 if ((cwd = getcwd(NULL, 0)) == NULL) {
7696 error = got_error_from_errno("getcwd");
7697 goto done;
7700 error = got_repo_pack_fds_open(&pack_fds);
7701 if (error != NULL)
7702 goto done;
7704 error = got_worktree_open(&worktree, cwd);
7705 if (error != NULL)
7706 goto done;
7708 const char *repo_path = got_worktree_get_repo_path(worktree);
7709 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7710 if (error != NULL)
7711 goto done;
7713 error = apply_unveil(got_repo_get_path(repo), 0,
7714 got_worktree_get_root_path(worktree));
7715 if (error != NULL)
7716 goto done;
7718 #ifndef PROFILE
7719 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7720 NULL) == -1)
7721 err(1, "pledge");
7722 #endif
7724 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7725 &patch_progress, NULL, check_cancelled, NULL);
7727 done:
7728 if (repo) {
7729 close_error = got_repo_close(repo);
7730 if (error == NULL)
7731 error = close_error;
7733 if (worktree != NULL) {
7734 close_error = got_worktree_close(worktree);
7735 if (error == NULL)
7736 error = close_error;
7738 if (pack_fds) {
7739 const struct got_error *pack_err =
7740 got_repo_pack_fds_close(pack_fds);
7741 if (error == NULL)
7742 error = pack_err;
7744 free(cwd);
7745 return error;
7748 __dead static void
7749 usage_revert(void)
7751 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7752 "path ...\n", getprogname());
7753 exit(1);
7756 static const struct got_error *
7757 revert_progress(void *arg, unsigned char status, const char *path)
7759 if (status == GOT_STATUS_UNVERSIONED)
7760 return NULL;
7762 while (path[0] == '/')
7763 path++;
7764 printf("%c %s\n", status, path);
7765 return NULL;
7768 struct choose_patch_arg {
7769 FILE *patch_script_file;
7770 const char *action;
7773 static const struct got_error *
7774 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7775 int nchanges, const char *action)
7777 const struct got_error *err;
7778 char *line = NULL;
7779 size_t linesize = 0;
7780 ssize_t linelen;
7782 switch (status) {
7783 case GOT_STATUS_ADD:
7784 printf("A %s\n%s this addition? [y/n] ", path, action);
7785 break;
7786 case GOT_STATUS_DELETE:
7787 printf("D %s\n%s this deletion? [y/n] ", path, action);
7788 break;
7789 case GOT_STATUS_MODIFY:
7790 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7791 return got_error_from_errno("fseek");
7792 printf(GOT_COMMIT_SEP_STR);
7793 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7794 printf("%s", line);
7795 if (linelen == -1 && ferror(patch_file)) {
7796 err = got_error_from_errno("getline");
7797 free(line);
7798 return err;
7800 free(line);
7801 printf(GOT_COMMIT_SEP_STR);
7802 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7803 path, n, nchanges, action);
7804 break;
7805 default:
7806 return got_error_path(path, GOT_ERR_FILE_STATUS);
7809 return NULL;
7812 static const struct got_error *
7813 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7814 FILE *patch_file, int n, int nchanges)
7816 const struct got_error *err = NULL;
7817 char *line = NULL;
7818 size_t linesize = 0;
7819 ssize_t linelen;
7820 int resp = ' ';
7821 struct choose_patch_arg *a = arg;
7823 *choice = GOT_PATCH_CHOICE_NONE;
7825 if (a->patch_script_file) {
7826 char *nl;
7827 err = show_change(status, path, patch_file, n, nchanges,
7828 a->action);
7829 if (err)
7830 return err;
7831 linelen = getline(&line, &linesize, a->patch_script_file);
7832 if (linelen == -1) {
7833 if (ferror(a->patch_script_file))
7834 return got_error_from_errno("getline");
7835 return NULL;
7837 nl = strchr(line, '\n');
7838 if (nl)
7839 *nl = '\0';
7840 if (strcmp(line, "y") == 0) {
7841 *choice = GOT_PATCH_CHOICE_YES;
7842 printf("y\n");
7843 } else if (strcmp(line, "n") == 0) {
7844 *choice = GOT_PATCH_CHOICE_NO;
7845 printf("n\n");
7846 } else if (strcmp(line, "q") == 0 &&
7847 status == GOT_STATUS_MODIFY) {
7848 *choice = GOT_PATCH_CHOICE_QUIT;
7849 printf("q\n");
7850 } else
7851 printf("invalid response '%s'\n", line);
7852 free(line);
7853 return NULL;
7856 while (resp != 'y' && resp != 'n' && resp != 'q') {
7857 err = show_change(status, path, patch_file, n, nchanges,
7858 a->action);
7859 if (err)
7860 return err;
7861 resp = getchar();
7862 if (resp == '\n')
7863 resp = getchar();
7864 if (status == GOT_STATUS_MODIFY) {
7865 if (resp != 'y' && resp != 'n' && resp != 'q') {
7866 printf("invalid response '%c'\n", resp);
7867 resp = ' ';
7869 } else if (resp != 'y' && resp != 'n') {
7870 printf("invalid response '%c'\n", resp);
7871 resp = ' ';
7875 if (resp == 'y')
7876 *choice = GOT_PATCH_CHOICE_YES;
7877 else if (resp == 'n')
7878 *choice = GOT_PATCH_CHOICE_NO;
7879 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7880 *choice = GOT_PATCH_CHOICE_QUIT;
7882 return NULL;
7885 static const struct got_error *
7886 cmd_revert(int argc, char *argv[])
7888 const struct got_error *error = NULL;
7889 struct got_worktree *worktree = NULL;
7890 struct got_repository *repo = NULL;
7891 char *cwd = NULL, *path = NULL;
7892 struct got_pathlist_head paths;
7893 struct got_pathlist_entry *pe;
7894 int ch, can_recurse = 0, pflag = 0;
7895 FILE *patch_script_file = NULL;
7896 const char *patch_script_path = NULL;
7897 struct choose_patch_arg cpa;
7898 int *pack_fds = NULL;
7900 TAILQ_INIT(&paths);
7902 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7903 switch (ch) {
7904 case 'p':
7905 pflag = 1;
7906 break;
7907 case 'F':
7908 patch_script_path = optarg;
7909 break;
7910 case 'R':
7911 can_recurse = 1;
7912 break;
7913 default:
7914 usage_revert();
7915 /* NOTREACHED */
7919 argc -= optind;
7920 argv += optind;
7922 #ifndef PROFILE
7923 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7924 "unveil", NULL) == -1)
7925 err(1, "pledge");
7926 #endif
7927 if (argc < 1)
7928 usage_revert();
7929 if (patch_script_path && !pflag)
7930 errx(1, "-F option can only be used together with -p option");
7932 cwd = getcwd(NULL, 0);
7933 if (cwd == NULL) {
7934 error = got_error_from_errno("getcwd");
7935 goto done;
7938 error = got_repo_pack_fds_open(&pack_fds);
7939 if (error != NULL)
7940 goto done;
7942 error = got_worktree_open(&worktree, cwd);
7943 if (error) {
7944 if (error->code == GOT_ERR_NOT_WORKTREE)
7945 error = wrap_not_worktree_error(error, "revert", cwd);
7946 goto done;
7949 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7950 NULL, pack_fds);
7951 if (error != NULL)
7952 goto done;
7954 if (patch_script_path) {
7955 patch_script_file = fopen(patch_script_path, "re");
7956 if (patch_script_file == NULL) {
7957 error = got_error_from_errno2("fopen",
7958 patch_script_path);
7959 goto done;
7962 error = apply_unveil(got_repo_get_path(repo), 1,
7963 got_worktree_get_root_path(worktree));
7964 if (error)
7965 goto done;
7967 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7968 if (error)
7969 goto done;
7971 if (!can_recurse) {
7972 char *ondisk_path;
7973 struct stat sb;
7974 TAILQ_FOREACH(pe, &paths, entry) {
7975 if (asprintf(&ondisk_path, "%s/%s",
7976 got_worktree_get_root_path(worktree),
7977 pe->path) == -1) {
7978 error = got_error_from_errno("asprintf");
7979 goto done;
7981 if (lstat(ondisk_path, &sb) == -1) {
7982 if (errno == ENOENT) {
7983 free(ondisk_path);
7984 continue;
7986 error = got_error_from_errno2("lstat",
7987 ondisk_path);
7988 free(ondisk_path);
7989 goto done;
7991 free(ondisk_path);
7992 if (S_ISDIR(sb.st_mode)) {
7993 error = got_error_msg(GOT_ERR_BAD_PATH,
7994 "reverting directories requires -R option");
7995 goto done;
8000 cpa.patch_script_file = patch_script_file;
8001 cpa.action = "revert";
8002 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8003 pflag ? choose_patch : NULL, &cpa, repo);
8004 done:
8005 if (patch_script_file && fclose(patch_script_file) == EOF &&
8006 error == NULL)
8007 error = got_error_from_errno2("fclose", patch_script_path);
8008 if (repo) {
8009 const struct got_error *close_err = got_repo_close(repo);
8010 if (error == NULL)
8011 error = close_err;
8013 if (worktree)
8014 got_worktree_close(worktree);
8015 if (pack_fds) {
8016 const struct got_error *pack_err =
8017 got_repo_pack_fds_close(pack_fds);
8018 if (error == NULL)
8019 error = pack_err;
8021 free(path);
8022 free(cwd);
8023 return error;
8026 __dead static void
8027 usage_commit(void)
8029 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8030 "[path ...]\n", getprogname());
8031 exit(1);
8034 struct collect_commit_logmsg_arg {
8035 const char *cmdline_log;
8036 const char *prepared_log;
8037 int non_interactive;
8038 const char *editor;
8039 const char *worktree_path;
8040 const char *branch_name;
8041 const char *repo_path;
8042 char *logmsg_path;
8046 static const struct got_error *
8047 read_prepared_logmsg(char **logmsg, const char *path)
8049 const struct got_error *err = NULL;
8050 FILE *f = NULL;
8051 struct stat sb;
8052 size_t r;
8054 *logmsg = NULL;
8055 memset(&sb, 0, sizeof(sb));
8057 f = fopen(path, "re");
8058 if (f == NULL)
8059 return got_error_from_errno2("fopen", path);
8061 if (fstat(fileno(f), &sb) == -1) {
8062 err = got_error_from_errno2("fstat", path);
8063 goto done;
8065 if (sb.st_size == 0) {
8066 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8067 goto done;
8070 *logmsg = malloc(sb.st_size + 1);
8071 if (*logmsg == NULL) {
8072 err = got_error_from_errno("malloc");
8073 goto done;
8076 r = fread(*logmsg, 1, sb.st_size, f);
8077 if (r != sb.st_size) {
8078 if (ferror(f))
8079 err = got_error_from_errno2("fread", path);
8080 else
8081 err = got_error(GOT_ERR_IO);
8082 goto done;
8084 (*logmsg)[sb.st_size] = '\0';
8085 done:
8086 if (fclose(f) == EOF && err == NULL)
8087 err = got_error_from_errno2("fclose", path);
8088 if (err) {
8089 free(*logmsg);
8090 *logmsg = NULL;
8092 return err;
8096 static const struct got_error *
8097 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8098 void *arg)
8100 char *initial_content = NULL;
8101 struct got_pathlist_entry *pe;
8102 const struct got_error *err = NULL;
8103 char *template = NULL;
8104 struct collect_commit_logmsg_arg *a = arg;
8105 int initial_content_len;
8106 int fd = -1;
8107 size_t len;
8109 /* if a message was specified on the command line, just use it */
8110 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8111 len = strlen(a->cmdline_log) + 1;
8112 *logmsg = malloc(len + 1);
8113 if (*logmsg == NULL)
8114 return got_error_from_errno("malloc");
8115 strlcpy(*logmsg, a->cmdline_log, len);
8116 return NULL;
8117 } else if (a->prepared_log != NULL && a->non_interactive)
8118 return read_prepared_logmsg(logmsg, a->prepared_log);
8120 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8121 return got_error_from_errno("asprintf");
8123 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8124 if (err)
8125 goto done;
8127 if (a->prepared_log) {
8128 char *msg;
8129 err = read_prepared_logmsg(&msg, a->prepared_log);
8130 if (err)
8131 goto done;
8132 if (write(fd, msg, strlen(msg)) == -1) {
8133 err = got_error_from_errno2("write", a->logmsg_path);
8134 free(msg);
8135 goto done;
8137 free(msg);
8140 initial_content_len = asprintf(&initial_content,
8141 "\n# changes to be committed on branch %s:\n",
8142 a->branch_name);
8143 if (initial_content_len == -1) {
8144 err = got_error_from_errno("asprintf");
8145 goto done;
8148 if (write(fd, initial_content, initial_content_len) == -1) {
8149 err = got_error_from_errno2("write", a->logmsg_path);
8150 goto done;
8153 TAILQ_FOREACH(pe, commitable_paths, entry) {
8154 struct got_commitable *ct = pe->data;
8155 dprintf(fd, "# %c %s\n",
8156 got_commitable_get_status(ct),
8157 got_commitable_get_path(ct));
8160 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8161 initial_content_len, a->prepared_log ? 0 : 1);
8162 done:
8163 free(initial_content);
8164 free(template);
8166 if (fd != -1 && close(fd) == -1 && err == NULL)
8167 err = got_error_from_errno2("close", a->logmsg_path);
8169 /* Editor is done; we can now apply unveil(2) */
8170 if (err == NULL)
8171 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8172 if (err) {
8173 free(*logmsg);
8174 *logmsg = NULL;
8176 return err;
8179 static const struct got_error *
8180 cmd_commit(int argc, char *argv[])
8182 const struct got_error *error = NULL;
8183 struct got_worktree *worktree = NULL;
8184 struct got_repository *repo = NULL;
8185 char *cwd = NULL, *id_str = NULL;
8186 struct got_object_id *id = NULL;
8187 const char *logmsg = NULL;
8188 char *prepared_logmsg = NULL;
8189 struct collect_commit_logmsg_arg cl_arg;
8190 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8191 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8192 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8193 struct got_pathlist_head paths;
8194 int *pack_fds = NULL;
8196 TAILQ_INIT(&paths);
8197 cl_arg.logmsg_path = NULL;
8199 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8200 switch (ch) {
8201 case 'F':
8202 if (logmsg != NULL)
8203 option_conflict('F', 'm');
8204 prepared_logmsg = realpath(optarg, NULL);
8205 if (prepared_logmsg == NULL)
8206 return got_error_from_errno2("realpath",
8207 optarg);
8208 break;
8209 case 'm':
8210 if (prepared_logmsg)
8211 option_conflict('m', 'F');
8212 logmsg = optarg;
8213 break;
8214 case 'N':
8215 non_interactive = 1;
8216 break;
8217 case 'S':
8218 allow_bad_symlinks = 1;
8219 break;
8220 default:
8221 usage_commit();
8222 /* NOTREACHED */
8226 argc -= optind;
8227 argv += optind;
8229 #ifndef PROFILE
8230 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8231 "unveil", NULL) == -1)
8232 err(1, "pledge");
8233 #endif
8234 cwd = getcwd(NULL, 0);
8235 if (cwd == NULL) {
8236 error = got_error_from_errno("getcwd");
8237 goto done;
8240 error = got_repo_pack_fds_open(&pack_fds);
8241 if (error != NULL)
8242 goto done;
8244 error = got_worktree_open(&worktree, cwd);
8245 if (error) {
8246 if (error->code == GOT_ERR_NOT_WORKTREE)
8247 error = wrap_not_worktree_error(error, "commit", cwd);
8248 goto done;
8251 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8252 if (error)
8253 goto done;
8254 if (rebase_in_progress) {
8255 error = got_error(GOT_ERR_REBASING);
8256 goto done;
8259 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8260 worktree);
8261 if (error)
8262 goto done;
8264 error = get_gitconfig_path(&gitconfig_path);
8265 if (error)
8266 goto done;
8267 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8268 gitconfig_path, pack_fds);
8269 if (error != NULL)
8270 goto done;
8272 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8273 if (error)
8274 goto done;
8275 if (merge_in_progress) {
8276 error = got_error(GOT_ERR_MERGE_BUSY);
8277 goto done;
8280 error = get_author(&author, repo, worktree);
8281 if (error)
8282 return error;
8285 * unveil(2) traverses exec(2); if an editor is used we have
8286 * to apply unveil after the log message has been written.
8288 if (logmsg == NULL || strlen(logmsg) == 0)
8289 error = get_editor(&editor);
8290 else
8291 error = apply_unveil(got_repo_get_path(repo), 0,
8292 got_worktree_get_root_path(worktree));
8293 if (error)
8294 goto done;
8296 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8297 if (error)
8298 goto done;
8300 cl_arg.editor = editor;
8301 cl_arg.cmdline_log = logmsg;
8302 cl_arg.prepared_log = prepared_logmsg;
8303 cl_arg.non_interactive = non_interactive;
8304 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8305 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8306 if (!histedit_in_progress) {
8307 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8308 error = got_error(GOT_ERR_COMMIT_BRANCH);
8309 goto done;
8311 cl_arg.branch_name += 11;
8313 cl_arg.repo_path = got_repo_get_path(repo);
8314 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8315 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8316 print_status, NULL, repo);
8317 if (error) {
8318 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8319 cl_arg.logmsg_path != NULL)
8320 preserve_logmsg = 1;
8321 goto done;
8324 error = got_object_id_str(&id_str, id);
8325 if (error)
8326 goto done;
8327 printf("Created commit %s\n", id_str);
8328 done:
8329 if (preserve_logmsg) {
8330 fprintf(stderr, "%s: log message preserved in %s\n",
8331 getprogname(), cl_arg.logmsg_path);
8332 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8333 error == NULL)
8334 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8335 free(cl_arg.logmsg_path);
8336 if (repo) {
8337 const struct got_error *close_err = got_repo_close(repo);
8338 if (error == NULL)
8339 error = close_err;
8341 if (worktree)
8342 got_worktree_close(worktree);
8343 if (pack_fds) {
8344 const struct got_error *pack_err =
8345 got_repo_pack_fds_close(pack_fds);
8346 if (error == NULL)
8347 error = pack_err;
8349 free(cwd);
8350 free(id_str);
8351 free(gitconfig_path);
8352 free(editor);
8353 free(author);
8354 free(prepared_logmsg);
8355 return error;
8358 __dead static void
8359 usage_send(void)
8361 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8362 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8363 "[remote-repository]\n", getprogname());
8364 exit(1);
8367 static void
8368 print_load_info(int print_colored, int print_found, int print_trees,
8369 int ncolored, int nfound, int ntrees)
8371 if (print_colored) {
8372 printf("%d commit%s colored", ncolored,
8373 ncolored == 1 ? "" : "s");
8375 if (print_found) {
8376 printf("%s%d object%s found",
8377 ncolored > 0 ? "; " : "",
8378 nfound, nfound == 1 ? "" : "s");
8380 if (print_trees) {
8381 printf("; %d tree%s scanned", ntrees,
8382 ntrees == 1 ? "" : "s");
8386 struct got_send_progress_arg {
8387 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8388 int verbosity;
8389 int last_ncolored;
8390 int last_nfound;
8391 int last_ntrees;
8392 int loading_done;
8393 int last_ncommits;
8394 int last_nobj_total;
8395 int last_p_deltify;
8396 int last_p_written;
8397 int last_p_sent;
8398 int printed_something;
8399 int sent_something;
8400 struct got_pathlist_head *delete_branches;
8403 static const struct got_error *
8404 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8405 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8406 int nobj_written, off_t bytes_sent, const char *refname, int success)
8408 struct got_send_progress_arg *a = arg;
8409 char scaled_packsize[FMT_SCALED_STRSIZE];
8410 char scaled_sent[FMT_SCALED_STRSIZE];
8411 int p_deltify = 0, p_written = 0, p_sent = 0;
8412 int print_colored = 0, print_found = 0, print_trees = 0;
8413 int print_searching = 0, print_total = 0;
8414 int print_deltify = 0, print_written = 0, print_sent = 0;
8416 if (a->verbosity < 0)
8417 return NULL;
8419 if (refname) {
8420 const char *status = success ? "accepted" : "rejected";
8422 if (success) {
8423 struct got_pathlist_entry *pe;
8424 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8425 const char *branchname = pe->path;
8426 if (got_path_cmp(branchname, refname,
8427 strlen(branchname), strlen(refname)) == 0) {
8428 status = "deleted";
8429 a->sent_something = 1;
8430 break;
8435 if (a->printed_something)
8436 putchar('\n');
8437 printf("Server has %s %s", status, refname);
8438 a->printed_something = 1;
8439 return NULL;
8442 if (a->last_ncolored != ncolored) {
8443 print_colored = 1;
8444 a->last_ncolored = ncolored;
8447 if (a->last_nfound != nfound) {
8448 print_colored = 1;
8449 print_found = 1;
8450 a->last_nfound = nfound;
8453 if (a->last_ntrees != ntrees) {
8454 print_colored = 1;
8455 print_found = 1;
8456 print_trees = 1;
8457 a->last_ntrees = ntrees;
8460 if ((print_colored || print_found || print_trees) &&
8461 !a->loading_done) {
8462 printf("\r");
8463 print_load_info(print_colored, print_found, print_trees,
8464 ncolored, nfound, ntrees);
8465 a->printed_something = 1;
8466 fflush(stdout);
8467 return NULL;
8468 } else if (!a->loading_done) {
8469 printf("\r");
8470 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8471 printf("\n");
8472 a->loading_done = 1;
8475 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8476 return got_error_from_errno("fmt_scaled");
8477 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8478 return got_error_from_errno("fmt_scaled");
8480 if (a->last_ncommits != ncommits) {
8481 print_searching = 1;
8482 a->last_ncommits = ncommits;
8485 if (a->last_nobj_total != nobj_total) {
8486 print_searching = 1;
8487 print_total = 1;
8488 a->last_nobj_total = nobj_total;
8491 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8492 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8493 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8494 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8495 return got_error(GOT_ERR_NO_SPACE);
8498 if (nobj_deltify > 0 || nobj_written > 0) {
8499 if (nobj_deltify > 0) {
8500 p_deltify = (nobj_deltify * 100) / nobj_total;
8501 if (p_deltify != a->last_p_deltify) {
8502 a->last_p_deltify = p_deltify;
8503 print_searching = 1;
8504 print_total = 1;
8505 print_deltify = 1;
8508 if (nobj_written > 0) {
8509 p_written = (nobj_written * 100) / nobj_total;
8510 if (p_written != a->last_p_written) {
8511 a->last_p_written = p_written;
8512 print_searching = 1;
8513 print_total = 1;
8514 print_deltify = 1;
8515 print_written = 1;
8520 if (bytes_sent > 0) {
8521 p_sent = (bytes_sent * 100) / packfile_size;
8522 if (p_sent != a->last_p_sent) {
8523 a->last_p_sent = p_sent;
8524 print_searching = 1;
8525 print_total = 1;
8526 print_deltify = 1;
8527 print_written = 1;
8528 print_sent = 1;
8530 a->sent_something = 1;
8533 if (print_searching || print_total || print_deltify || print_written ||
8534 print_sent)
8535 printf("\r");
8536 if (print_searching)
8537 printf("packing %d reference%s", ncommits,
8538 ncommits == 1 ? "" : "s");
8539 if (print_total)
8540 printf("; %d object%s", nobj_total,
8541 nobj_total == 1 ? "" : "s");
8542 if (print_deltify)
8543 printf("; deltify: %d%%", p_deltify);
8544 if (print_sent)
8545 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8546 scaled_packsize, p_sent);
8547 else if (print_written)
8548 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8549 scaled_packsize, p_written);
8550 if (print_searching || print_total || print_deltify ||
8551 print_written || print_sent) {
8552 a->printed_something = 1;
8553 fflush(stdout);
8555 return NULL;
8558 static const struct got_error *
8559 cmd_send(int argc, char *argv[])
8561 const struct got_error *error = NULL;
8562 char *cwd = NULL, *repo_path = NULL;
8563 const char *remote_name;
8564 char *proto = NULL, *host = NULL, *port = NULL;
8565 char *repo_name = NULL, *server_path = NULL;
8566 const struct got_remote_repo *remotes, *remote = NULL;
8567 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8568 struct got_repository *repo = NULL;
8569 struct got_worktree *worktree = NULL;
8570 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8571 struct got_pathlist_head branches;
8572 struct got_pathlist_head tags;
8573 struct got_reflist_head all_branches;
8574 struct got_reflist_head all_tags;
8575 struct got_pathlist_head delete_args;
8576 struct got_pathlist_head delete_branches;
8577 struct got_reflist_entry *re;
8578 struct got_pathlist_entry *pe;
8579 int i, ch, sendfd = -1, sendstatus;
8580 pid_t sendpid = -1;
8581 struct got_send_progress_arg spa;
8582 int verbosity = 0, overwrite_refs = 0;
8583 int send_all_branches = 0, send_all_tags = 0;
8584 struct got_reference *ref = NULL;
8585 int *pack_fds = NULL;
8587 TAILQ_INIT(&branches);
8588 TAILQ_INIT(&tags);
8589 TAILQ_INIT(&all_branches);
8590 TAILQ_INIT(&all_tags);
8591 TAILQ_INIT(&delete_args);
8592 TAILQ_INIT(&delete_branches);
8594 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8595 switch (ch) {
8596 case 'a':
8597 send_all_branches = 1;
8598 break;
8599 case 'b':
8600 error = got_pathlist_append(&branches, optarg, NULL);
8601 if (error)
8602 return error;
8603 nbranches++;
8604 break;
8605 case 'd':
8606 error = got_pathlist_append(&delete_args, optarg, NULL);
8607 if (error)
8608 return error;
8609 break;
8610 case 'f':
8611 overwrite_refs = 1;
8612 break;
8613 case 'r':
8614 repo_path = realpath(optarg, NULL);
8615 if (repo_path == NULL)
8616 return got_error_from_errno2("realpath",
8617 optarg);
8618 got_path_strip_trailing_slashes(repo_path);
8619 break;
8620 case 't':
8621 error = got_pathlist_append(&tags, optarg, NULL);
8622 if (error)
8623 return error;
8624 ntags++;
8625 break;
8626 case 'T':
8627 send_all_tags = 1;
8628 break;
8629 case 'v':
8630 if (verbosity < 0)
8631 verbosity = 0;
8632 else if (verbosity < 3)
8633 verbosity++;
8634 break;
8635 case 'q':
8636 verbosity = -1;
8637 break;
8638 default:
8639 usage_send();
8640 /* NOTREACHED */
8643 argc -= optind;
8644 argv += optind;
8646 if (send_all_branches && !TAILQ_EMPTY(&branches))
8647 option_conflict('a', 'b');
8648 if (send_all_tags && !TAILQ_EMPTY(&tags))
8649 option_conflict('T', 't');
8652 if (argc == 0)
8653 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8654 else if (argc == 1)
8655 remote_name = argv[0];
8656 else
8657 usage_send();
8659 cwd = getcwd(NULL, 0);
8660 if (cwd == NULL) {
8661 error = got_error_from_errno("getcwd");
8662 goto done;
8665 error = got_repo_pack_fds_open(&pack_fds);
8666 if (error != NULL)
8667 goto done;
8669 if (repo_path == NULL) {
8670 error = got_worktree_open(&worktree, cwd);
8671 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8672 goto done;
8673 else
8674 error = NULL;
8675 if (worktree) {
8676 repo_path =
8677 strdup(got_worktree_get_repo_path(worktree));
8678 if (repo_path == NULL)
8679 error = got_error_from_errno("strdup");
8680 if (error)
8681 goto done;
8682 } else {
8683 repo_path = strdup(cwd);
8684 if (repo_path == NULL) {
8685 error = got_error_from_errno("strdup");
8686 goto done;
8691 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8692 if (error)
8693 goto done;
8695 if (worktree) {
8696 worktree_conf = got_worktree_get_gotconfig(worktree);
8697 if (worktree_conf) {
8698 got_gotconfig_get_remotes(&nremotes, &remotes,
8699 worktree_conf);
8700 for (i = 0; i < nremotes; i++) {
8701 if (strcmp(remotes[i].name, remote_name) == 0) {
8702 remote = &remotes[i];
8703 break;
8708 if (remote == NULL) {
8709 repo_conf = got_repo_get_gotconfig(repo);
8710 if (repo_conf) {
8711 got_gotconfig_get_remotes(&nremotes, &remotes,
8712 repo_conf);
8713 for (i = 0; i < nremotes; i++) {
8714 if (strcmp(remotes[i].name, remote_name) == 0) {
8715 remote = &remotes[i];
8716 break;
8721 if (remote == NULL) {
8722 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8723 for (i = 0; i < nremotes; i++) {
8724 if (strcmp(remotes[i].name, remote_name) == 0) {
8725 remote = &remotes[i];
8726 break;
8730 if (remote == NULL) {
8731 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8732 goto done;
8735 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8736 &repo_name, remote->send_url);
8737 if (error)
8738 goto done;
8740 if (strcmp(proto, "git") == 0) {
8741 #ifndef PROFILE
8742 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8743 "sendfd dns inet unveil", NULL) == -1)
8744 err(1, "pledge");
8745 #endif
8746 } else if (strcmp(proto, "git+ssh") == 0 ||
8747 strcmp(proto, "ssh") == 0) {
8748 #ifndef PROFILE
8749 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8750 "sendfd unveil", NULL) == -1)
8751 err(1, "pledge");
8752 #endif
8753 } else if (strcmp(proto, "http") == 0 ||
8754 strcmp(proto, "git+http") == 0) {
8755 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8756 goto done;
8757 } else {
8758 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8759 goto done;
8762 error = got_dial_apply_unveil(proto);
8763 if (error)
8764 goto done;
8766 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8767 if (error)
8768 goto done;
8770 if (send_all_branches) {
8771 error = got_ref_list(&all_branches, repo, "refs/heads",
8772 got_ref_cmp_by_name, NULL);
8773 if (error)
8774 goto done;
8775 TAILQ_FOREACH(re, &all_branches, entry) {
8776 const char *branchname = got_ref_get_name(re->ref);
8777 error = got_pathlist_append(&branches,
8778 branchname, NULL);
8779 if (error)
8780 goto done;
8781 nbranches++;
8783 } else if (nbranches == 0) {
8784 for (i = 0; i < remote->nsend_branches; i++) {
8785 got_pathlist_append(&branches,
8786 remote->send_branches[i], NULL);
8790 if (send_all_tags) {
8791 error = got_ref_list(&all_tags, repo, "refs/tags",
8792 got_ref_cmp_by_name, NULL);
8793 if (error)
8794 goto done;
8795 TAILQ_FOREACH(re, &all_tags, entry) {
8796 const char *tagname = got_ref_get_name(re->ref);
8797 error = got_pathlist_append(&tags,
8798 tagname, NULL);
8799 if (error)
8800 goto done;
8801 ntags++;
8806 * To prevent accidents only branches in refs/heads/ can be deleted
8807 * with 'got send -d'.
8808 * Deleting anything else requires local repository access or Git.
8810 TAILQ_FOREACH(pe, &delete_args, entry) {
8811 const char *branchname = pe->path;
8812 char *s;
8813 struct got_pathlist_entry *new;
8814 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8815 s = strdup(branchname);
8816 if (s == NULL) {
8817 error = got_error_from_errno("strdup");
8818 goto done;
8820 } else {
8821 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8822 error = got_error_from_errno("asprintf");
8823 goto done;
8826 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8827 if (error || new == NULL /* duplicate */)
8828 free(s);
8829 if (error)
8830 goto done;
8831 ndelete_branches++;
8834 if (nbranches == 0 && ndelete_branches == 0) {
8835 struct got_reference *head_ref;
8836 if (worktree)
8837 error = got_ref_open(&head_ref, repo,
8838 got_worktree_get_head_ref_name(worktree), 0);
8839 else
8840 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8841 if (error)
8842 goto done;
8843 if (got_ref_is_symbolic(head_ref)) {
8844 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8845 got_ref_close(head_ref);
8846 if (error)
8847 goto done;
8848 } else
8849 ref = head_ref;
8850 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8851 NULL);
8852 if (error)
8853 goto done;
8854 nbranches++;
8857 if (verbosity >= 0)
8858 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8859 port ? ":" : "", port ? port : "");
8861 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8862 server_path, verbosity);
8863 if (error)
8864 goto done;
8866 memset(&spa, 0, sizeof(spa));
8867 spa.last_scaled_packsize[0] = '\0';
8868 spa.last_p_deltify = -1;
8869 spa.last_p_written = -1;
8870 spa.verbosity = verbosity;
8871 spa.delete_branches = &delete_branches;
8872 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8873 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8874 check_cancelled, NULL);
8875 if (spa.printed_something)
8876 putchar('\n');
8877 if (error)
8878 goto done;
8879 if (!spa.sent_something && verbosity >= 0)
8880 printf("Already up-to-date\n");
8881 done:
8882 if (sendpid > 0) {
8883 if (kill(sendpid, SIGTERM) == -1)
8884 error = got_error_from_errno("kill");
8885 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8886 error = got_error_from_errno("waitpid");
8888 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8889 error = got_error_from_errno("close");
8890 if (repo) {
8891 const struct got_error *close_err = got_repo_close(repo);
8892 if (error == NULL)
8893 error = close_err;
8895 if (worktree)
8896 got_worktree_close(worktree);
8897 if (pack_fds) {
8898 const struct got_error *pack_err =
8899 got_repo_pack_fds_close(pack_fds);
8900 if (error == NULL)
8901 error = pack_err;
8903 if (ref)
8904 got_ref_close(ref);
8905 got_pathlist_free(&branches);
8906 got_pathlist_free(&tags);
8907 got_ref_list_free(&all_branches);
8908 got_ref_list_free(&all_tags);
8909 got_pathlist_free(&delete_args);
8910 TAILQ_FOREACH(pe, &delete_branches, entry)
8911 free((char *)pe->path);
8912 got_pathlist_free(&delete_branches);
8913 free(cwd);
8914 free(repo_path);
8915 free(proto);
8916 free(host);
8917 free(port);
8918 free(server_path);
8919 free(repo_name);
8920 return error;
8923 __dead static void
8924 usage_cherrypick(void)
8926 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8927 exit(1);
8930 static const struct got_error *
8931 cmd_cherrypick(int argc, char *argv[])
8933 const struct got_error *error = NULL;
8934 struct got_worktree *worktree = NULL;
8935 struct got_repository *repo = NULL;
8936 char *cwd = NULL, *commit_id_str = NULL;
8937 struct got_object_id *commit_id = NULL;
8938 struct got_commit_object *commit = NULL;
8939 struct got_object_qid *pid;
8940 int ch;
8941 struct got_update_progress_arg upa;
8942 int *pack_fds = NULL;
8944 while ((ch = getopt(argc, argv, "")) != -1) {
8945 switch (ch) {
8946 default:
8947 usage_cherrypick();
8948 /* NOTREACHED */
8952 argc -= optind;
8953 argv += optind;
8955 #ifndef PROFILE
8956 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8957 "unveil", NULL) == -1)
8958 err(1, "pledge");
8959 #endif
8960 if (argc != 1)
8961 usage_cherrypick();
8963 cwd = getcwd(NULL, 0);
8964 if (cwd == NULL) {
8965 error = got_error_from_errno("getcwd");
8966 goto done;
8969 error = got_repo_pack_fds_open(&pack_fds);
8970 if (error != NULL)
8971 goto done;
8973 error = got_worktree_open(&worktree, cwd);
8974 if (error) {
8975 if (error->code == GOT_ERR_NOT_WORKTREE)
8976 error = wrap_not_worktree_error(error, "cherrypick",
8977 cwd);
8978 goto done;
8981 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8982 NULL, pack_fds);
8983 if (error != NULL)
8984 goto done;
8986 error = apply_unveil(got_repo_get_path(repo), 0,
8987 got_worktree_get_root_path(worktree));
8988 if (error)
8989 goto done;
8991 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8992 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8993 if (error)
8994 goto done;
8995 error = got_object_id_str(&commit_id_str, commit_id);
8996 if (error)
8997 goto done;
8999 error = got_object_open_as_commit(&commit, repo, commit_id);
9000 if (error)
9001 goto done;
9002 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9003 memset(&upa, 0, sizeof(upa));
9004 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9005 commit_id, repo, update_progress, &upa, check_cancelled,
9006 NULL);
9007 if (error != NULL)
9008 goto done;
9010 if (upa.did_something)
9011 printf("Merged commit %s\n", commit_id_str);
9012 print_merge_progress_stats(&upa);
9013 done:
9014 if (commit)
9015 got_object_commit_close(commit);
9016 free(commit_id_str);
9017 if (worktree)
9018 got_worktree_close(worktree);
9019 if (repo) {
9020 const struct got_error *close_err = got_repo_close(repo);
9021 if (error == NULL)
9022 error = close_err;
9024 if (pack_fds) {
9025 const struct got_error *pack_err =
9026 got_repo_pack_fds_close(pack_fds);
9027 if (error == NULL)
9028 error = pack_err;
9031 return error;
9034 __dead static void
9035 usage_backout(void)
9037 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9038 exit(1);
9041 static const struct got_error *
9042 cmd_backout(int argc, char *argv[])
9044 const struct got_error *error = NULL;
9045 struct got_worktree *worktree = NULL;
9046 struct got_repository *repo = NULL;
9047 char *cwd = NULL, *commit_id_str = NULL;
9048 struct got_object_id *commit_id = NULL;
9049 struct got_commit_object *commit = NULL;
9050 struct got_object_qid *pid;
9051 int ch;
9052 struct got_update_progress_arg upa;
9053 int *pack_fds = NULL;
9055 while ((ch = getopt(argc, argv, "")) != -1) {
9056 switch (ch) {
9057 default:
9058 usage_backout();
9059 /* NOTREACHED */
9063 argc -= optind;
9064 argv += optind;
9066 #ifndef PROFILE
9067 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9068 "unveil", NULL) == -1)
9069 err(1, "pledge");
9070 #endif
9071 if (argc != 1)
9072 usage_backout();
9074 cwd = getcwd(NULL, 0);
9075 if (cwd == NULL) {
9076 error = got_error_from_errno("getcwd");
9077 goto done;
9080 error = got_repo_pack_fds_open(&pack_fds);
9081 if (error != NULL)
9082 goto done;
9084 error = got_worktree_open(&worktree, cwd);
9085 if (error) {
9086 if (error->code == GOT_ERR_NOT_WORKTREE)
9087 error = wrap_not_worktree_error(error, "backout", cwd);
9088 goto done;
9091 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9092 NULL, pack_fds);
9093 if (error != NULL)
9094 goto done;
9096 error = apply_unveil(got_repo_get_path(repo), 0,
9097 got_worktree_get_root_path(worktree));
9098 if (error)
9099 goto done;
9101 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9102 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9103 if (error)
9104 goto done;
9105 error = got_object_id_str(&commit_id_str, commit_id);
9106 if (error)
9107 goto done;
9109 error = got_object_open_as_commit(&commit, repo, commit_id);
9110 if (error)
9111 goto done;
9112 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9113 if (pid == NULL) {
9114 error = got_error(GOT_ERR_ROOT_COMMIT);
9115 goto done;
9118 memset(&upa, 0, sizeof(upa));
9119 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9120 repo, update_progress, &upa, check_cancelled, NULL);
9121 if (error != NULL)
9122 goto done;
9124 if (upa.did_something)
9125 printf("Backed out commit %s\n", commit_id_str);
9126 print_merge_progress_stats(&upa);
9127 done:
9128 if (commit)
9129 got_object_commit_close(commit);
9130 free(commit_id_str);
9131 if (worktree)
9132 got_worktree_close(worktree);
9133 if (repo) {
9134 const struct got_error *close_err = got_repo_close(repo);
9135 if (error == NULL)
9136 error = close_err;
9138 if (pack_fds) {
9139 const struct got_error *pack_err =
9140 got_repo_pack_fds_close(pack_fds);
9141 if (error == NULL)
9142 error = pack_err;
9144 return error;
9147 __dead static void
9148 usage_rebase(void)
9150 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9151 getprogname());
9152 exit(1);
9155 static void
9156 trim_logmsg(char *logmsg, int limit)
9158 char *nl;
9159 size_t len;
9161 len = strlen(logmsg);
9162 if (len > limit)
9163 len = limit;
9164 logmsg[len] = '\0';
9165 nl = strchr(logmsg, '\n');
9166 if (nl)
9167 *nl = '\0';
9170 static const struct got_error *
9171 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9173 const struct got_error *err;
9174 char *logmsg0 = NULL;
9175 const char *s;
9177 err = got_object_commit_get_logmsg(&logmsg0, commit);
9178 if (err)
9179 return err;
9181 s = logmsg0;
9182 while (isspace((unsigned char)s[0]))
9183 s++;
9185 *logmsg = strdup(s);
9186 if (*logmsg == NULL) {
9187 err = got_error_from_errno("strdup");
9188 goto done;
9191 trim_logmsg(*logmsg, limit);
9192 done:
9193 free(logmsg0);
9194 return err;
9197 static const struct got_error *
9198 show_rebase_merge_conflict(struct got_object_id *id,
9199 struct got_repository *repo)
9201 const struct got_error *err;
9202 struct got_commit_object *commit = NULL;
9203 char *id_str = NULL, *logmsg = NULL;
9205 err = got_object_open_as_commit(&commit, repo, id);
9206 if (err)
9207 return err;
9209 err = got_object_id_str(&id_str, id);
9210 if (err)
9211 goto done;
9213 id_str[12] = '\0';
9215 err = get_short_logmsg(&logmsg, 42, commit);
9216 if (err)
9217 goto done;
9219 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9220 done:
9221 free(id_str);
9222 got_object_commit_close(commit);
9223 free(logmsg);
9224 return err;
9227 static const struct got_error *
9228 show_rebase_progress(struct got_commit_object *commit,
9229 struct got_object_id *old_id, struct got_object_id *new_id)
9231 const struct got_error *err;
9232 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9234 err = got_object_id_str(&old_id_str, old_id);
9235 if (err)
9236 goto done;
9238 if (new_id) {
9239 err = got_object_id_str(&new_id_str, new_id);
9240 if (err)
9241 goto done;
9244 old_id_str[12] = '\0';
9245 if (new_id_str)
9246 new_id_str[12] = '\0';
9248 err = get_short_logmsg(&logmsg, 42, commit);
9249 if (err)
9250 goto done;
9252 printf("%s -> %s: %s\n", old_id_str,
9253 new_id_str ? new_id_str : "no-op change", logmsg);
9254 done:
9255 free(old_id_str);
9256 free(new_id_str);
9257 free(logmsg);
9258 return err;
9261 static const struct got_error *
9262 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9263 struct got_reference *branch, struct got_reference *new_base_branch,
9264 struct got_reference *tmp_branch, struct got_repository *repo,
9265 int create_backup)
9267 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9268 return got_worktree_rebase_complete(worktree, fileindex,
9269 new_base_branch, tmp_branch, branch, repo, create_backup);
9272 static const struct got_error *
9273 rebase_commit(struct got_pathlist_head *merged_paths,
9274 struct got_worktree *worktree, struct got_fileindex *fileindex,
9275 struct got_reference *tmp_branch,
9276 struct got_object_id *commit_id, struct got_repository *repo)
9278 const struct got_error *error;
9279 struct got_commit_object *commit;
9280 struct got_object_id *new_commit_id;
9282 error = got_object_open_as_commit(&commit, repo, commit_id);
9283 if (error)
9284 return error;
9286 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9287 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9288 if (error) {
9289 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9290 goto done;
9291 error = show_rebase_progress(commit, commit_id, NULL);
9292 } else {
9293 error = show_rebase_progress(commit, commit_id, new_commit_id);
9294 free(new_commit_id);
9296 done:
9297 got_object_commit_close(commit);
9298 return error;
9301 struct check_path_prefix_arg {
9302 const char *path_prefix;
9303 size_t len;
9304 int errcode;
9307 static const struct got_error *
9308 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9309 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9310 struct got_object_id *id1, struct got_object_id *id2,
9311 const char *path1, const char *path2,
9312 mode_t mode1, mode_t mode2, struct got_repository *repo)
9314 struct check_path_prefix_arg *a = arg;
9316 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9317 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9318 return got_error(a->errcode);
9320 return NULL;
9323 static const struct got_error *
9324 check_path_prefix(struct got_object_id *parent_id,
9325 struct got_object_id *commit_id, const char *path_prefix,
9326 int errcode, struct got_repository *repo)
9328 const struct got_error *err;
9329 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9330 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9331 struct check_path_prefix_arg cpp_arg;
9333 if (got_path_is_root_dir(path_prefix))
9334 return NULL;
9336 err = got_object_open_as_commit(&commit, repo, commit_id);
9337 if (err)
9338 goto done;
9340 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9341 if (err)
9342 goto done;
9344 err = got_object_open_as_tree(&tree1, repo,
9345 got_object_commit_get_tree_id(parent_commit));
9346 if (err)
9347 goto done;
9349 err = got_object_open_as_tree(&tree2, repo,
9350 got_object_commit_get_tree_id(commit));
9351 if (err)
9352 goto done;
9354 cpp_arg.path_prefix = path_prefix;
9355 while (cpp_arg.path_prefix[0] == '/')
9356 cpp_arg.path_prefix++;
9357 cpp_arg.len = strlen(cpp_arg.path_prefix);
9358 cpp_arg.errcode = errcode;
9359 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9360 check_path_prefix_in_diff, &cpp_arg, 0);
9361 done:
9362 if (tree1)
9363 got_object_tree_close(tree1);
9364 if (tree2)
9365 got_object_tree_close(tree2);
9366 if (commit)
9367 got_object_commit_close(commit);
9368 if (parent_commit)
9369 got_object_commit_close(parent_commit);
9370 return err;
9373 static const struct got_error *
9374 collect_commits(struct got_object_id_queue *commits,
9375 struct got_object_id *initial_commit_id,
9376 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9377 const char *path_prefix, int path_prefix_errcode,
9378 struct got_repository *repo)
9380 const struct got_error *err = NULL;
9381 struct got_commit_graph *graph = NULL;
9382 struct got_object_id *parent_id = NULL;
9383 struct got_object_qid *qid;
9384 struct got_object_id *commit_id = initial_commit_id;
9386 err = got_commit_graph_open(&graph, "/", 1);
9387 if (err)
9388 return err;
9390 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9391 check_cancelled, NULL);
9392 if (err)
9393 goto done;
9394 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9395 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9396 check_cancelled, NULL);
9397 if (err) {
9398 if (err->code == GOT_ERR_ITER_COMPLETED) {
9399 err = got_error_msg(GOT_ERR_ANCESTRY,
9400 "ran out of commits to rebase before "
9401 "youngest common ancestor commit has "
9402 "been reached?!?");
9404 goto done;
9405 } else {
9406 err = check_path_prefix(parent_id, commit_id,
9407 path_prefix, path_prefix_errcode, repo);
9408 if (err)
9409 goto done;
9411 err = got_object_qid_alloc(&qid, commit_id);
9412 if (err)
9413 goto done;
9414 STAILQ_INSERT_HEAD(commits, qid, entry);
9415 commit_id = parent_id;
9418 done:
9419 got_commit_graph_close(graph);
9420 return err;
9423 static const struct got_error *
9424 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9426 const struct got_error *err = NULL;
9427 time_t committer_time;
9428 struct tm tm;
9429 char datebuf[11]; /* YYYY-MM-DD + NUL */
9430 char *author0 = NULL, *author, *smallerthan;
9431 char *logmsg0 = NULL, *logmsg, *newline;
9433 committer_time = got_object_commit_get_committer_time(commit);
9434 if (gmtime_r(&committer_time, &tm) == NULL)
9435 return got_error_from_errno("gmtime_r");
9436 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9437 return got_error(GOT_ERR_NO_SPACE);
9439 author0 = strdup(got_object_commit_get_author(commit));
9440 if (author0 == NULL)
9441 return got_error_from_errno("strdup");
9442 author = author0;
9443 smallerthan = strchr(author, '<');
9444 if (smallerthan && smallerthan[1] != '\0')
9445 author = smallerthan + 1;
9446 author[strcspn(author, "@>")] = '\0';
9448 err = got_object_commit_get_logmsg(&logmsg0, commit);
9449 if (err)
9450 goto done;
9451 logmsg = logmsg0;
9452 while (*logmsg == '\n')
9453 logmsg++;
9454 newline = strchr(logmsg, '\n');
9455 if (newline)
9456 *newline = '\0';
9458 if (asprintf(brief_str, "%s %s %s",
9459 datebuf, author, logmsg) == -1)
9460 err = got_error_from_errno("asprintf");
9461 done:
9462 free(author0);
9463 free(logmsg0);
9464 return err;
9467 static const struct got_error *
9468 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9469 struct got_repository *repo)
9471 const struct got_error *err;
9472 char *id_str;
9474 err = got_object_id_str(&id_str, id);
9475 if (err)
9476 return err;
9478 err = got_ref_delete(ref, repo);
9479 if (err)
9480 goto done;
9482 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9483 done:
9484 free(id_str);
9485 return err;
9488 static const struct got_error *
9489 print_backup_ref(const char *branch_name, const char *new_id_str,
9490 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9491 struct got_reflist_object_id_map *refs_idmap,
9492 struct got_repository *repo)
9494 const struct got_error *err = NULL;
9495 struct got_reflist_head *refs;
9496 char *refs_str = NULL;
9497 struct got_object_id *new_commit_id = NULL;
9498 struct got_commit_object *new_commit = NULL;
9499 char *new_commit_brief_str = NULL;
9500 struct got_object_id *yca_id = NULL;
9501 struct got_commit_object *yca_commit = NULL;
9502 char *yca_id_str = NULL, *yca_brief_str = NULL;
9503 char *custom_refs_str;
9505 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9506 return got_error_from_errno("asprintf");
9508 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9509 0, 0, refs_idmap, custom_refs_str);
9510 if (err)
9511 goto done;
9513 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9514 if (err)
9515 goto done;
9517 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9518 if (refs) {
9519 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9520 if (err)
9521 goto done;
9524 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9525 if (err)
9526 goto done;
9528 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9529 if (err)
9530 goto done;
9532 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9533 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9534 if (err)
9535 goto done;
9537 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9538 refs_str ? " (" : "", refs_str ? refs_str : "",
9539 refs_str ? ")" : "", new_commit_brief_str);
9540 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9541 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9542 free(refs_str);
9543 refs_str = NULL;
9545 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9546 if (err)
9547 goto done;
9549 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9550 if (err)
9551 goto done;
9553 err = got_object_id_str(&yca_id_str, yca_id);
9554 if (err)
9555 goto done;
9557 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9558 if (refs) {
9559 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9560 if (err)
9561 goto done;
9563 printf("history forked at %s%s%s%s\n %s\n",
9564 yca_id_str,
9565 refs_str ? " (" : "", refs_str ? refs_str : "",
9566 refs_str ? ")" : "", yca_brief_str);
9568 done:
9569 free(custom_refs_str);
9570 free(new_commit_id);
9571 free(refs_str);
9572 free(yca_id);
9573 free(yca_id_str);
9574 free(yca_brief_str);
9575 if (new_commit)
9576 got_object_commit_close(new_commit);
9577 if (yca_commit)
9578 got_object_commit_close(yca_commit);
9580 return NULL;
9583 static const struct got_error *
9584 process_backup_refs(const char *backup_ref_prefix,
9585 const char *wanted_branch_name,
9586 int delete, struct got_repository *repo)
9588 const struct got_error *err;
9589 struct got_reflist_head refs, backup_refs;
9590 struct got_reflist_entry *re;
9591 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9592 struct got_object_id *old_commit_id = NULL;
9593 char *branch_name = NULL;
9594 struct got_commit_object *old_commit = NULL;
9595 struct got_reflist_object_id_map *refs_idmap = NULL;
9596 int wanted_branch_found = 0;
9598 TAILQ_INIT(&refs);
9599 TAILQ_INIT(&backup_refs);
9601 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9602 if (err)
9603 return err;
9605 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9606 if (err)
9607 goto done;
9609 if (wanted_branch_name) {
9610 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9611 wanted_branch_name += 11;
9614 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9615 got_ref_cmp_by_commit_timestamp_descending, repo);
9616 if (err)
9617 goto done;
9619 TAILQ_FOREACH(re, &backup_refs, entry) {
9620 const char *refname = got_ref_get_name(re->ref);
9621 char *slash;
9623 err = check_cancelled(NULL);
9624 if (err)
9625 break;
9627 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9628 if (err)
9629 break;
9631 err = got_object_open_as_commit(&old_commit, repo,
9632 old_commit_id);
9633 if (err)
9634 break;
9636 if (strncmp(backup_ref_prefix, refname,
9637 backup_ref_prefix_len) == 0)
9638 refname += backup_ref_prefix_len;
9640 while (refname[0] == '/')
9641 refname++;
9643 branch_name = strdup(refname);
9644 if (branch_name == NULL) {
9645 err = got_error_from_errno("strdup");
9646 break;
9648 slash = strrchr(branch_name, '/');
9649 if (slash) {
9650 *slash = '\0';
9651 refname += strlen(branch_name) + 1;
9654 if (wanted_branch_name == NULL ||
9655 strcmp(wanted_branch_name, branch_name) == 0) {
9656 wanted_branch_found = 1;
9657 if (delete) {
9658 err = delete_backup_ref(re->ref,
9659 old_commit_id, repo);
9660 } else {
9661 err = print_backup_ref(branch_name, refname,
9662 old_commit_id, old_commit, refs_idmap,
9663 repo);
9665 if (err)
9666 break;
9669 free(old_commit_id);
9670 old_commit_id = NULL;
9671 free(branch_name);
9672 branch_name = NULL;
9673 got_object_commit_close(old_commit);
9674 old_commit = NULL;
9677 if (wanted_branch_name && !wanted_branch_found) {
9678 err = got_error_fmt(GOT_ERR_NOT_REF,
9679 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9681 done:
9682 if (refs_idmap)
9683 got_reflist_object_id_map_free(refs_idmap);
9684 got_ref_list_free(&refs);
9685 got_ref_list_free(&backup_refs);
9686 free(old_commit_id);
9687 free(branch_name);
9688 if (old_commit)
9689 got_object_commit_close(old_commit);
9690 return err;
9693 static const struct got_error *
9694 abort_progress(void *arg, unsigned char status, const char *path)
9697 * Unversioned files should not clutter progress output when
9698 * an operation is aborted.
9700 if (status == GOT_STATUS_UNVERSIONED)
9701 return NULL;
9703 return update_progress(arg, status, path);
9706 static const struct got_error *
9707 cmd_rebase(int argc, char *argv[])
9709 const struct got_error *error = NULL;
9710 struct got_worktree *worktree = NULL;
9711 struct got_repository *repo = NULL;
9712 struct got_fileindex *fileindex = NULL;
9713 char *cwd = NULL;
9714 struct got_reference *branch = NULL;
9715 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9716 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9717 struct got_object_id *resume_commit_id = NULL;
9718 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9719 struct got_commit_object *commit = NULL;
9720 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9721 int histedit_in_progress = 0, merge_in_progress = 0;
9722 int create_backup = 1, list_backups = 0, delete_backups = 0;
9723 struct got_object_id_queue commits;
9724 struct got_pathlist_head merged_paths;
9725 const struct got_object_id_queue *parent_ids;
9726 struct got_object_qid *qid, *pid;
9727 struct got_update_progress_arg upa;
9728 int *pack_fds = NULL;
9730 STAILQ_INIT(&commits);
9731 TAILQ_INIT(&merged_paths);
9732 memset(&upa, 0, sizeof(upa));
9734 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9735 switch (ch) {
9736 case 'a':
9737 abort_rebase = 1;
9738 break;
9739 case 'c':
9740 continue_rebase = 1;
9741 break;
9742 case 'l':
9743 list_backups = 1;
9744 break;
9745 case 'X':
9746 delete_backups = 1;
9747 break;
9748 default:
9749 usage_rebase();
9750 /* NOTREACHED */
9754 argc -= optind;
9755 argv += optind;
9757 #ifndef PROFILE
9758 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9759 "unveil", NULL) == -1)
9760 err(1, "pledge");
9761 #endif
9762 if (list_backups) {
9763 if (abort_rebase)
9764 option_conflict('l', 'a');
9765 if (continue_rebase)
9766 option_conflict('l', 'c');
9767 if (delete_backups)
9768 option_conflict('l', 'X');
9769 if (argc != 0 && argc != 1)
9770 usage_rebase();
9771 } else if (delete_backups) {
9772 if (abort_rebase)
9773 option_conflict('X', 'a');
9774 if (continue_rebase)
9775 option_conflict('X', 'c');
9776 if (list_backups)
9777 option_conflict('l', 'X');
9778 if (argc != 0 && argc != 1)
9779 usage_rebase();
9780 } else {
9781 if (abort_rebase && continue_rebase)
9782 usage_rebase();
9783 else if (abort_rebase || continue_rebase) {
9784 if (argc != 0)
9785 usage_rebase();
9786 } else if (argc != 1)
9787 usage_rebase();
9790 cwd = getcwd(NULL, 0);
9791 if (cwd == NULL) {
9792 error = got_error_from_errno("getcwd");
9793 goto done;
9796 error = got_repo_pack_fds_open(&pack_fds);
9797 if (error != NULL)
9798 goto done;
9800 error = got_worktree_open(&worktree, cwd);
9801 if (error) {
9802 if (list_backups || delete_backups) {
9803 if (error->code != GOT_ERR_NOT_WORKTREE)
9804 goto done;
9805 } else {
9806 if (error->code == GOT_ERR_NOT_WORKTREE)
9807 error = wrap_not_worktree_error(error,
9808 "rebase", cwd);
9809 goto done;
9813 error = got_repo_open(&repo,
9814 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9815 pack_fds);
9816 if (error != NULL)
9817 goto done;
9819 error = apply_unveil(got_repo_get_path(repo), 0,
9820 worktree ? got_worktree_get_root_path(worktree) : NULL);
9821 if (error)
9822 goto done;
9824 if (list_backups || delete_backups) {
9825 error = process_backup_refs(
9826 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9827 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9828 goto done; /* nothing else to do */
9831 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9832 worktree);
9833 if (error)
9834 goto done;
9835 if (histedit_in_progress) {
9836 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9837 goto done;
9840 error = got_worktree_merge_in_progress(&merge_in_progress,
9841 worktree, repo);
9842 if (error)
9843 goto done;
9844 if (merge_in_progress) {
9845 error = got_error(GOT_ERR_MERGE_BUSY);
9846 goto done;
9849 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9850 if (error)
9851 goto done;
9853 if (abort_rebase) {
9854 if (!rebase_in_progress) {
9855 error = got_error(GOT_ERR_NOT_REBASING);
9856 goto done;
9858 error = got_worktree_rebase_continue(&resume_commit_id,
9859 &new_base_branch, &tmp_branch, &branch, &fileindex,
9860 worktree, repo);
9861 if (error)
9862 goto done;
9863 printf("Switching work tree to %s\n",
9864 got_ref_get_symref_target(new_base_branch));
9865 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9866 new_base_branch, abort_progress, &upa);
9867 if (error)
9868 goto done;
9869 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9870 print_merge_progress_stats(&upa);
9871 goto done; /* nothing else to do */
9874 if (continue_rebase) {
9875 if (!rebase_in_progress) {
9876 error = got_error(GOT_ERR_NOT_REBASING);
9877 goto done;
9879 error = got_worktree_rebase_continue(&resume_commit_id,
9880 &new_base_branch, &tmp_branch, &branch, &fileindex,
9881 worktree, repo);
9882 if (error)
9883 goto done;
9885 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9886 resume_commit_id, repo);
9887 if (error)
9888 goto done;
9890 yca_id = got_object_id_dup(resume_commit_id);
9891 if (yca_id == NULL) {
9892 error = got_error_from_errno("got_object_id_dup");
9893 goto done;
9895 } else {
9896 error = got_ref_open(&branch, repo, argv[0], 0);
9897 if (error != NULL)
9898 goto done;
9901 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9902 if (error)
9903 goto done;
9905 if (!continue_rebase) {
9906 struct got_object_id *base_commit_id;
9908 base_commit_id = got_worktree_get_base_commit_id(worktree);
9909 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9910 base_commit_id, branch_head_commit_id, 1, repo,
9911 check_cancelled, NULL);
9912 if (error)
9913 goto done;
9914 if (yca_id == NULL) {
9915 error = got_error_msg(GOT_ERR_ANCESTRY,
9916 "specified branch shares no common ancestry "
9917 "with work tree's branch");
9918 goto done;
9921 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9922 if (error) {
9923 if (error->code != GOT_ERR_ANCESTRY)
9924 goto done;
9925 error = NULL;
9926 } else {
9927 struct got_pathlist_head paths;
9928 printf("%s is already based on %s\n",
9929 got_ref_get_name(branch),
9930 got_worktree_get_head_ref_name(worktree));
9931 error = switch_head_ref(branch, branch_head_commit_id,
9932 worktree, repo);
9933 if (error)
9934 goto done;
9935 error = got_worktree_set_base_commit_id(worktree, repo,
9936 branch_head_commit_id);
9937 if (error)
9938 goto done;
9939 TAILQ_INIT(&paths);
9940 error = got_pathlist_append(&paths, "", NULL);
9941 if (error)
9942 goto done;
9943 error = got_worktree_checkout_files(worktree,
9944 &paths, repo, update_progress, &upa,
9945 check_cancelled, NULL);
9946 got_pathlist_free(&paths);
9947 if (error)
9948 goto done;
9949 if (upa.did_something) {
9950 char *id_str;
9951 error = got_object_id_str(&id_str,
9952 branch_head_commit_id);
9953 if (error)
9954 goto done;
9955 printf("Updated to %s: %s\n",
9956 got_worktree_get_head_ref_name(worktree),
9957 id_str);
9958 free(id_str);
9959 } else
9960 printf("Already up-to-date\n");
9961 print_update_progress_stats(&upa);
9962 goto done;
9966 commit_id = branch_head_commit_id;
9967 error = got_object_open_as_commit(&commit, repo, commit_id);
9968 if (error)
9969 goto done;
9971 parent_ids = got_object_commit_get_parent_ids(commit);
9972 pid = STAILQ_FIRST(parent_ids);
9973 if (pid == NULL) {
9974 error = got_error(GOT_ERR_EMPTY_REBASE);
9975 goto done;
9977 error = collect_commits(&commits, commit_id, &pid->id,
9978 yca_id, got_worktree_get_path_prefix(worktree),
9979 GOT_ERR_REBASE_PATH, repo);
9980 got_object_commit_close(commit);
9981 commit = NULL;
9982 if (error)
9983 goto done;
9985 if (!continue_rebase) {
9986 error = got_worktree_rebase_prepare(&new_base_branch,
9987 &tmp_branch, &fileindex, worktree, branch, repo);
9988 if (error)
9989 goto done;
9992 if (STAILQ_EMPTY(&commits)) {
9993 if (continue_rebase) {
9994 error = rebase_complete(worktree, fileindex,
9995 branch, new_base_branch, tmp_branch, repo,
9996 create_backup);
9997 goto done;
9998 } else {
9999 /* Fast-forward the reference of the branch. */
10000 struct got_object_id *new_head_commit_id;
10001 char *id_str;
10002 error = got_ref_resolve(&new_head_commit_id, repo,
10003 new_base_branch);
10004 if (error)
10005 goto done;
10006 error = got_object_id_str(&id_str, new_head_commit_id);
10007 printf("Forwarding %s to commit %s\n",
10008 got_ref_get_name(branch), id_str);
10009 free(id_str);
10010 error = got_ref_change_ref(branch,
10011 new_head_commit_id);
10012 if (error)
10013 goto done;
10014 /* No backup needed since objects did not change. */
10015 create_backup = 0;
10019 pid = NULL;
10020 STAILQ_FOREACH(qid, &commits, entry) {
10022 commit_id = &qid->id;
10023 parent_id = pid ? &pid->id : yca_id;
10024 pid = qid;
10026 memset(&upa, 0, sizeof(upa));
10027 error = got_worktree_rebase_merge_files(&merged_paths,
10028 worktree, fileindex, parent_id, commit_id, repo,
10029 update_progress, &upa, check_cancelled, NULL);
10030 if (error)
10031 goto done;
10033 print_merge_progress_stats(&upa);
10034 if (upa.conflicts > 0 || upa.missing > 0 ||
10035 upa.not_deleted > 0 || upa.unversioned > 0) {
10036 if (upa.conflicts > 0) {
10037 error = show_rebase_merge_conflict(&qid->id,
10038 repo);
10039 if (error)
10040 goto done;
10042 got_worktree_rebase_pathlist_free(&merged_paths);
10043 break;
10046 error = rebase_commit(&merged_paths, worktree, fileindex,
10047 tmp_branch, commit_id, repo);
10048 got_worktree_rebase_pathlist_free(&merged_paths);
10049 if (error)
10050 goto done;
10053 if (upa.conflicts > 0 || upa.missing > 0 ||
10054 upa.not_deleted > 0 || upa.unversioned > 0) {
10055 error = got_worktree_rebase_postpone(worktree, fileindex);
10056 if (error)
10057 goto done;
10058 if (upa.conflicts > 0 && upa.missing == 0 &&
10059 upa.not_deleted == 0 && upa.unversioned == 0) {
10060 error = got_error_msg(GOT_ERR_CONFLICTS,
10061 "conflicts must be resolved before rebasing "
10062 "can continue");
10063 } else if (upa.conflicts > 0) {
10064 error = got_error_msg(GOT_ERR_CONFLICTS,
10065 "conflicts must be resolved before rebasing "
10066 "can continue; changes destined for some "
10067 "files were not yet merged and should be "
10068 "merged manually if required before the "
10069 "rebase operation is continued");
10070 } else {
10071 error = got_error_msg(GOT_ERR_CONFLICTS,
10072 "changes destined for some files were not "
10073 "yet merged and should be merged manually "
10074 "if required before the rebase operation "
10075 "is continued");
10077 } else
10078 error = rebase_complete(worktree, fileindex, branch,
10079 new_base_branch, tmp_branch, repo, create_backup);
10080 done:
10081 got_object_id_queue_free(&commits);
10082 free(branch_head_commit_id);
10083 free(resume_commit_id);
10084 free(yca_id);
10085 if (commit)
10086 got_object_commit_close(commit);
10087 if (branch)
10088 got_ref_close(branch);
10089 if (new_base_branch)
10090 got_ref_close(new_base_branch);
10091 if (tmp_branch)
10092 got_ref_close(tmp_branch);
10093 if (worktree)
10094 got_worktree_close(worktree);
10095 if (repo) {
10096 const struct got_error *close_err = got_repo_close(repo);
10097 if (error == NULL)
10098 error = close_err;
10100 if (pack_fds) {
10101 const struct got_error *pack_err =
10102 got_repo_pack_fds_close(pack_fds);
10103 if (error == NULL)
10104 error = pack_err;
10106 return error;
10109 __dead static void
10110 usage_histedit(void)
10112 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10113 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10114 getprogname());
10115 exit(1);
10118 #define GOT_HISTEDIT_PICK 'p'
10119 #define GOT_HISTEDIT_EDIT 'e'
10120 #define GOT_HISTEDIT_FOLD 'f'
10121 #define GOT_HISTEDIT_DROP 'd'
10122 #define GOT_HISTEDIT_MESG 'm'
10124 static const struct got_histedit_cmd {
10125 unsigned char code;
10126 const char *name;
10127 const char *desc;
10128 } got_histedit_cmds[] = {
10129 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10130 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10131 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10132 "be used" },
10133 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10134 { GOT_HISTEDIT_MESG, "mesg",
10135 "single-line log message for commit above (open editor if empty)" },
10138 struct got_histedit_list_entry {
10139 TAILQ_ENTRY(got_histedit_list_entry) entry;
10140 struct got_object_id *commit_id;
10141 const struct got_histedit_cmd *cmd;
10142 char *logmsg;
10144 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10146 static const struct got_error *
10147 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10148 FILE *f, struct got_repository *repo)
10150 const struct got_error *err = NULL;
10151 char *logmsg = NULL, *id_str = NULL;
10152 struct got_commit_object *commit = NULL;
10153 int n;
10155 err = got_object_open_as_commit(&commit, repo, commit_id);
10156 if (err)
10157 goto done;
10159 err = get_short_logmsg(&logmsg, 34, commit);
10160 if (err)
10161 goto done;
10163 err = got_object_id_str(&id_str, commit_id);
10164 if (err)
10165 goto done;
10167 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10168 if (n < 0)
10169 err = got_ferror(f, GOT_ERR_IO);
10170 done:
10171 if (commit)
10172 got_object_commit_close(commit);
10173 free(id_str);
10174 free(logmsg);
10175 return err;
10178 static const struct got_error *
10179 histedit_write_commit_list(struct got_object_id_queue *commits,
10180 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10181 struct got_repository *repo)
10183 const struct got_error *err = NULL;
10184 struct got_object_qid *qid;
10185 const char *histedit_cmd = NULL;
10187 if (STAILQ_EMPTY(commits))
10188 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10190 STAILQ_FOREACH(qid, commits, entry) {
10191 histedit_cmd = got_histedit_cmds[0].name;
10192 if (edit_only)
10193 histedit_cmd = "edit";
10194 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10195 histedit_cmd = "fold";
10196 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10197 if (err)
10198 break;
10199 if (edit_logmsg_only) {
10200 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10201 if (n < 0) {
10202 err = got_ferror(f, GOT_ERR_IO);
10203 break;
10208 return err;
10211 static const struct got_error *
10212 write_cmd_list(FILE *f, const char *branch_name,
10213 struct got_object_id_queue *commits)
10215 const struct got_error *err = NULL;
10216 size_t i;
10217 int n;
10218 char *id_str;
10219 struct got_object_qid *qid;
10221 qid = STAILQ_FIRST(commits);
10222 err = got_object_id_str(&id_str, &qid->id);
10223 if (err)
10224 return err;
10226 n = fprintf(f,
10227 "# Editing the history of branch '%s' starting at\n"
10228 "# commit %s\n"
10229 "# Commits will be processed in order from top to "
10230 "bottom of this file.\n", branch_name, id_str);
10231 if (n < 0) {
10232 err = got_ferror(f, GOT_ERR_IO);
10233 goto done;
10236 n = fprintf(f, "# Available histedit commands:\n");
10237 if (n < 0) {
10238 err = got_ferror(f, GOT_ERR_IO);
10239 goto done;
10242 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10243 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10244 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10245 cmd->desc);
10246 if (n < 0) {
10247 err = got_ferror(f, GOT_ERR_IO);
10248 break;
10251 done:
10252 free(id_str);
10253 return err;
10256 static const struct got_error *
10257 histedit_syntax_error(int lineno)
10259 static char msg[42];
10260 int ret;
10262 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10263 lineno);
10264 if (ret == -1 || ret >= sizeof(msg))
10265 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10267 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10270 static const struct got_error *
10271 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10272 char *logmsg, struct got_repository *repo)
10274 const struct got_error *err;
10275 struct got_commit_object *folded_commit = NULL;
10276 char *id_str, *folded_logmsg = NULL;
10278 err = got_object_id_str(&id_str, hle->commit_id);
10279 if (err)
10280 return err;
10282 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10283 if (err)
10284 goto done;
10286 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10287 if (err)
10288 goto done;
10289 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10290 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10291 folded_logmsg) == -1) {
10292 err = got_error_from_errno("asprintf");
10294 done:
10295 if (folded_commit)
10296 got_object_commit_close(folded_commit);
10297 free(id_str);
10298 free(folded_logmsg);
10299 return err;
10302 static struct got_histedit_list_entry *
10303 get_folded_commits(struct got_histedit_list_entry *hle)
10305 struct got_histedit_list_entry *prev, *folded = NULL;
10307 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10308 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10309 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10310 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10311 folded = prev;
10312 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10315 return folded;
10318 static const struct got_error *
10319 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10320 struct got_repository *repo)
10322 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10323 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10324 const struct got_error *err = NULL;
10325 struct got_commit_object *commit = NULL;
10326 int logmsg_len;
10327 int fd;
10328 struct got_histedit_list_entry *folded = NULL;
10330 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10331 if (err)
10332 return err;
10334 folded = get_folded_commits(hle);
10335 if (folded) {
10336 while (folded != hle) {
10337 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10338 folded = TAILQ_NEXT(folded, entry);
10339 continue;
10341 err = append_folded_commit_msg(&new_msg, folded,
10342 logmsg, repo);
10343 if (err)
10344 goto done;
10345 free(logmsg);
10346 logmsg = new_msg;
10347 folded = TAILQ_NEXT(folded, entry);
10351 err = got_object_id_str(&id_str, hle->commit_id);
10352 if (err)
10353 goto done;
10354 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10355 if (err)
10356 goto done;
10357 logmsg_len = asprintf(&new_msg,
10358 "%s\n# original log message of commit %s: %s",
10359 logmsg ? logmsg : "", id_str, orig_logmsg);
10360 if (logmsg_len == -1) {
10361 err = got_error_from_errno("asprintf");
10362 goto done;
10364 free(logmsg);
10365 logmsg = new_msg;
10367 err = got_object_id_str(&id_str, hle->commit_id);
10368 if (err)
10369 goto done;
10371 err = got_opentemp_named_fd(&logmsg_path, &fd,
10372 GOT_TMPDIR_STR "/got-logmsg");
10373 if (err)
10374 goto done;
10376 write(fd, logmsg, logmsg_len);
10377 close(fd);
10379 err = get_editor(&editor);
10380 if (err)
10381 goto done;
10383 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10384 logmsg_len, 0);
10385 if (err) {
10386 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10387 goto done;
10388 err = NULL;
10389 hle->logmsg = strdup(new_msg);
10390 if (hle->logmsg == NULL)
10391 err = got_error_from_errno("strdup");
10393 done:
10394 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10395 err = got_error_from_errno2("unlink", logmsg_path);
10396 free(logmsg_path);
10397 free(logmsg);
10398 free(orig_logmsg);
10399 free(editor);
10400 if (commit)
10401 got_object_commit_close(commit);
10402 return err;
10405 static const struct got_error *
10406 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10407 FILE *f, struct got_repository *repo)
10409 const struct got_error *err = NULL;
10410 char *line = NULL, *p, *end;
10411 size_t i, size;
10412 ssize_t len;
10413 int lineno = 0;
10414 const struct got_histedit_cmd *cmd;
10415 struct got_object_id *commit_id = NULL;
10416 struct got_histedit_list_entry *hle = NULL;
10418 for (;;) {
10419 len = getline(&line, &size, f);
10420 if (len == -1) {
10421 const struct got_error *getline_err;
10422 if (feof(f))
10423 break;
10424 getline_err = got_error_from_errno("getline");
10425 err = got_ferror(f, getline_err->code);
10426 break;
10428 lineno++;
10429 p = line;
10430 while (isspace((unsigned char)p[0]))
10431 p++;
10432 if (p[0] == '#' || p[0] == '\0') {
10433 free(line);
10434 line = NULL;
10435 continue;
10437 cmd = NULL;
10438 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10439 cmd = &got_histedit_cmds[i];
10440 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10441 isspace((unsigned char)p[strlen(cmd->name)])) {
10442 p += strlen(cmd->name);
10443 break;
10445 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10446 p++;
10447 break;
10450 if (i == nitems(got_histedit_cmds)) {
10451 err = histedit_syntax_error(lineno);
10452 break;
10454 while (isspace((unsigned char)p[0]))
10455 p++;
10456 if (cmd->code == GOT_HISTEDIT_MESG) {
10457 if (hle == NULL || hle->logmsg != NULL) {
10458 err = got_error(GOT_ERR_HISTEDIT_CMD);
10459 break;
10461 if (p[0] == '\0') {
10462 err = histedit_edit_logmsg(hle, repo);
10463 if (err)
10464 break;
10465 } else {
10466 hle->logmsg = strdup(p);
10467 if (hle->logmsg == NULL) {
10468 err = got_error_from_errno("strdup");
10469 break;
10472 free(line);
10473 line = NULL;
10474 continue;
10475 } else {
10476 end = p;
10477 while (end[0] && !isspace((unsigned char)end[0]))
10478 end++;
10479 *end = '\0';
10481 err = got_object_resolve_id_str(&commit_id, repo, p);
10482 if (err) {
10483 /* override error code */
10484 err = histedit_syntax_error(lineno);
10485 break;
10488 hle = malloc(sizeof(*hle));
10489 if (hle == NULL) {
10490 err = got_error_from_errno("malloc");
10491 break;
10493 hle->cmd = cmd;
10494 hle->commit_id = commit_id;
10495 hle->logmsg = NULL;
10496 commit_id = NULL;
10497 free(line);
10498 line = NULL;
10499 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10502 free(line);
10503 free(commit_id);
10504 return err;
10507 static const struct got_error *
10508 histedit_check_script(struct got_histedit_list *histedit_cmds,
10509 struct got_object_id_queue *commits, struct got_repository *repo)
10511 const struct got_error *err = NULL;
10512 struct got_object_qid *qid;
10513 struct got_histedit_list_entry *hle;
10514 static char msg[92];
10515 char *id_str;
10517 if (TAILQ_EMPTY(histedit_cmds))
10518 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10519 "histedit script contains no commands");
10520 if (STAILQ_EMPTY(commits))
10521 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10523 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10524 struct got_histedit_list_entry *hle2;
10525 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10526 if (hle == hle2)
10527 continue;
10528 if (got_object_id_cmp(hle->commit_id,
10529 hle2->commit_id) != 0)
10530 continue;
10531 err = got_object_id_str(&id_str, hle->commit_id);
10532 if (err)
10533 return err;
10534 snprintf(msg, sizeof(msg), "commit %s is listed "
10535 "more than once in histedit script", id_str);
10536 free(id_str);
10537 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10541 STAILQ_FOREACH(qid, commits, entry) {
10542 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10543 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10544 break;
10546 if (hle == NULL) {
10547 err = got_object_id_str(&id_str, &qid->id);
10548 if (err)
10549 return err;
10550 snprintf(msg, sizeof(msg),
10551 "commit %s missing from histedit script", id_str);
10552 free(id_str);
10553 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10557 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10558 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10559 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10560 "last commit in histedit script cannot be folded");
10562 return NULL;
10565 static const struct got_error *
10566 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10567 const char *path, struct got_object_id_queue *commits,
10568 struct got_repository *repo)
10570 const struct got_error *err = NULL;
10571 char *editor;
10572 FILE *f = NULL;
10574 err = get_editor(&editor);
10575 if (err)
10576 return err;
10578 if (spawn_editor(editor, path) == -1) {
10579 err = got_error_from_errno("failed spawning editor");
10580 goto done;
10583 f = fopen(path, "re");
10584 if (f == NULL) {
10585 err = got_error_from_errno("fopen");
10586 goto done;
10588 err = histedit_parse_list(histedit_cmds, f, repo);
10589 if (err)
10590 goto done;
10592 err = histedit_check_script(histedit_cmds, commits, repo);
10593 done:
10594 if (f && fclose(f) == EOF && err == NULL)
10595 err = got_error_from_errno("fclose");
10596 free(editor);
10597 return err;
10600 static const struct got_error *
10601 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10602 struct got_object_id_queue *, const char *, const char *,
10603 struct got_repository *);
10605 static const struct got_error *
10606 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10607 struct got_object_id_queue *commits, const char *branch_name,
10608 int edit_logmsg_only, int fold_only, int edit_only,
10609 struct got_repository *repo)
10611 const struct got_error *err;
10612 FILE *f = NULL;
10613 char *path = NULL;
10615 err = got_opentemp_named(&path, &f, "got-histedit");
10616 if (err)
10617 return err;
10619 err = write_cmd_list(f, branch_name, commits);
10620 if (err)
10621 goto done;
10623 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10624 fold_only, edit_only, repo);
10625 if (err)
10626 goto done;
10628 if (edit_logmsg_only || fold_only || edit_only) {
10629 rewind(f);
10630 err = histedit_parse_list(histedit_cmds, f, repo);
10631 } else {
10632 if (fclose(f) == EOF) {
10633 err = got_error_from_errno("fclose");
10634 goto done;
10636 f = NULL;
10637 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10638 if (err) {
10639 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10640 err->code != GOT_ERR_HISTEDIT_CMD)
10641 goto done;
10642 err = histedit_edit_list_retry(histedit_cmds, err,
10643 commits, path, branch_name, repo);
10646 done:
10647 if (f && fclose(f) == EOF && err == NULL)
10648 err = got_error_from_errno("fclose");
10649 if (path && unlink(path) != 0 && err == NULL)
10650 err = got_error_from_errno2("unlink", path);
10651 free(path);
10652 return err;
10655 static const struct got_error *
10656 histedit_save_list(struct got_histedit_list *histedit_cmds,
10657 struct got_worktree *worktree, struct got_repository *repo)
10659 const struct got_error *err = NULL;
10660 char *path = NULL;
10661 FILE *f = NULL;
10662 struct got_histedit_list_entry *hle;
10663 struct got_commit_object *commit = NULL;
10665 err = got_worktree_get_histedit_script_path(&path, worktree);
10666 if (err)
10667 return err;
10669 f = fopen(path, "we");
10670 if (f == NULL) {
10671 err = got_error_from_errno2("fopen", path);
10672 goto done;
10674 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10675 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10676 repo);
10677 if (err)
10678 break;
10680 if (hle->logmsg) {
10681 int n = fprintf(f, "%c %s\n",
10682 GOT_HISTEDIT_MESG, hle->logmsg);
10683 if (n < 0) {
10684 err = got_ferror(f, GOT_ERR_IO);
10685 break;
10689 done:
10690 if (f && fclose(f) == EOF && err == NULL)
10691 err = got_error_from_errno("fclose");
10692 free(path);
10693 if (commit)
10694 got_object_commit_close(commit);
10695 return err;
10698 static void
10699 histedit_free_list(struct got_histedit_list *histedit_cmds)
10701 struct got_histedit_list_entry *hle;
10703 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10704 TAILQ_REMOVE(histedit_cmds, hle, entry);
10705 free(hle);
10709 static const struct got_error *
10710 histedit_load_list(struct got_histedit_list *histedit_cmds,
10711 const char *path, struct got_repository *repo)
10713 const struct got_error *err = NULL;
10714 FILE *f = NULL;
10716 f = fopen(path, "re");
10717 if (f == NULL) {
10718 err = got_error_from_errno2("fopen", path);
10719 goto done;
10722 err = histedit_parse_list(histedit_cmds, f, repo);
10723 done:
10724 if (f && fclose(f) == EOF && err == NULL)
10725 err = got_error_from_errno("fclose");
10726 return err;
10729 static const struct got_error *
10730 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10731 const struct got_error *edit_err, struct got_object_id_queue *commits,
10732 const char *path, const char *branch_name, struct got_repository *repo)
10734 const struct got_error *err = NULL, *prev_err = edit_err;
10735 int resp = ' ';
10737 while (resp != 'c' && resp != 'r' && resp != 'a') {
10738 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10739 "or (a)bort: ", getprogname(), prev_err->msg);
10740 resp = getchar();
10741 if (resp == '\n')
10742 resp = getchar();
10743 if (resp == 'c') {
10744 histedit_free_list(histedit_cmds);
10745 err = histedit_run_editor(histedit_cmds, path, commits,
10746 repo);
10747 if (err) {
10748 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10749 err->code != GOT_ERR_HISTEDIT_CMD)
10750 break;
10751 prev_err = err;
10752 resp = ' ';
10753 continue;
10755 break;
10756 } else if (resp == 'r') {
10757 histedit_free_list(histedit_cmds);
10758 err = histedit_edit_script(histedit_cmds,
10759 commits, branch_name, 0, 0, 0, repo);
10760 if (err) {
10761 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10762 err->code != GOT_ERR_HISTEDIT_CMD)
10763 break;
10764 prev_err = err;
10765 resp = ' ';
10766 continue;
10768 break;
10769 } else if (resp == 'a') {
10770 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10771 break;
10772 } else
10773 printf("invalid response '%c'\n", resp);
10776 return err;
10779 static const struct got_error *
10780 histedit_complete(struct got_worktree *worktree,
10781 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10782 struct got_reference *branch, struct got_repository *repo)
10784 printf("Switching work tree to %s\n",
10785 got_ref_get_symref_target(branch));
10786 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10787 branch, repo);
10790 static const struct got_error *
10791 show_histedit_progress(struct got_commit_object *commit,
10792 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10794 const struct got_error *err;
10795 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10797 err = got_object_id_str(&old_id_str, hle->commit_id);
10798 if (err)
10799 goto done;
10801 if (new_id) {
10802 err = got_object_id_str(&new_id_str, new_id);
10803 if (err)
10804 goto done;
10807 old_id_str[12] = '\0';
10808 if (new_id_str)
10809 new_id_str[12] = '\0';
10811 if (hle->logmsg) {
10812 logmsg = strdup(hle->logmsg);
10813 if (logmsg == NULL) {
10814 err = got_error_from_errno("strdup");
10815 goto done;
10817 trim_logmsg(logmsg, 42);
10818 } else {
10819 err = get_short_logmsg(&logmsg, 42, commit);
10820 if (err)
10821 goto done;
10824 switch (hle->cmd->code) {
10825 case GOT_HISTEDIT_PICK:
10826 case GOT_HISTEDIT_EDIT:
10827 printf("%s -> %s: %s\n", old_id_str,
10828 new_id_str ? new_id_str : "no-op change", logmsg);
10829 break;
10830 case GOT_HISTEDIT_DROP:
10831 case GOT_HISTEDIT_FOLD:
10832 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10833 logmsg);
10834 break;
10835 default:
10836 break;
10838 done:
10839 free(old_id_str);
10840 free(new_id_str);
10841 return err;
10844 static const struct got_error *
10845 histedit_commit(struct got_pathlist_head *merged_paths,
10846 struct got_worktree *worktree, struct got_fileindex *fileindex,
10847 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10848 struct got_repository *repo)
10850 const struct got_error *err;
10851 struct got_commit_object *commit;
10852 struct got_object_id *new_commit_id;
10854 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10855 && hle->logmsg == NULL) {
10856 err = histedit_edit_logmsg(hle, repo);
10857 if (err)
10858 return err;
10861 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10862 if (err)
10863 return err;
10865 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10866 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10867 hle->logmsg, repo);
10868 if (err) {
10869 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10870 goto done;
10871 err = show_histedit_progress(commit, hle, NULL);
10872 } else {
10873 err = show_histedit_progress(commit, hle, new_commit_id);
10874 free(new_commit_id);
10876 done:
10877 got_object_commit_close(commit);
10878 return err;
10881 static const struct got_error *
10882 histedit_skip_commit(struct got_histedit_list_entry *hle,
10883 struct got_worktree *worktree, struct got_repository *repo)
10885 const struct got_error *error;
10886 struct got_commit_object *commit;
10888 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10889 repo);
10890 if (error)
10891 return error;
10893 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10894 if (error)
10895 return error;
10897 error = show_histedit_progress(commit, hle, NULL);
10898 got_object_commit_close(commit);
10899 return error;
10902 static const struct got_error *
10903 check_local_changes(void *arg, unsigned char status,
10904 unsigned char staged_status, const char *path,
10905 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10906 struct got_object_id *commit_id, int dirfd, const char *de_name)
10908 int *have_local_changes = arg;
10910 switch (status) {
10911 case GOT_STATUS_ADD:
10912 case GOT_STATUS_DELETE:
10913 case GOT_STATUS_MODIFY:
10914 case GOT_STATUS_CONFLICT:
10915 *have_local_changes = 1;
10916 return got_error(GOT_ERR_CANCELLED);
10917 default:
10918 break;
10921 switch (staged_status) {
10922 case GOT_STATUS_ADD:
10923 case GOT_STATUS_DELETE:
10924 case GOT_STATUS_MODIFY:
10925 *have_local_changes = 1;
10926 return got_error(GOT_ERR_CANCELLED);
10927 default:
10928 break;
10931 return NULL;
10934 static const struct got_error *
10935 cmd_histedit(int argc, char *argv[])
10937 const struct got_error *error = NULL;
10938 struct got_worktree *worktree = NULL;
10939 struct got_fileindex *fileindex = NULL;
10940 struct got_repository *repo = NULL;
10941 char *cwd = NULL;
10942 struct got_reference *branch = NULL;
10943 struct got_reference *tmp_branch = NULL;
10944 struct got_object_id *resume_commit_id = NULL;
10945 struct got_object_id *base_commit_id = NULL;
10946 struct got_object_id *head_commit_id = NULL;
10947 struct got_commit_object *commit = NULL;
10948 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10949 struct got_update_progress_arg upa;
10950 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10951 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10952 int list_backups = 0, delete_backups = 0;
10953 const char *edit_script_path = NULL;
10954 struct got_object_id_queue commits;
10955 struct got_pathlist_head merged_paths;
10956 const struct got_object_id_queue *parent_ids;
10957 struct got_object_qid *pid;
10958 struct got_histedit_list histedit_cmds;
10959 struct got_histedit_list_entry *hle;
10960 int *pack_fds = NULL;
10962 STAILQ_INIT(&commits);
10963 TAILQ_INIT(&histedit_cmds);
10964 TAILQ_INIT(&merged_paths);
10965 memset(&upa, 0, sizeof(upa));
10967 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10968 switch (ch) {
10969 case 'a':
10970 abort_edit = 1;
10971 break;
10972 case 'c':
10973 continue_edit = 1;
10974 break;
10975 case 'e':
10976 edit_only = 1;
10977 break;
10978 case 'f':
10979 fold_only = 1;
10980 break;
10981 case 'F':
10982 edit_script_path = optarg;
10983 break;
10984 case 'm':
10985 edit_logmsg_only = 1;
10986 break;
10987 case 'l':
10988 list_backups = 1;
10989 break;
10990 case 'X':
10991 delete_backups = 1;
10992 break;
10993 default:
10994 usage_histedit();
10995 /* NOTREACHED */
10999 argc -= optind;
11000 argv += optind;
11002 #ifndef PROFILE
11003 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11004 "unveil", NULL) == -1)
11005 err(1, "pledge");
11006 #endif
11007 if (abort_edit && continue_edit)
11008 option_conflict('a', 'c');
11009 if (edit_script_path && edit_logmsg_only)
11010 option_conflict('F', 'm');
11011 if (abort_edit && edit_logmsg_only)
11012 option_conflict('a', 'm');
11013 if (continue_edit && edit_logmsg_only)
11014 option_conflict('c', 'm');
11015 if (abort_edit && fold_only)
11016 option_conflict('a', 'f');
11017 if (continue_edit && fold_only)
11018 option_conflict('c', 'f');
11019 if (fold_only && edit_logmsg_only)
11020 option_conflict('f', 'm');
11021 if (edit_script_path && fold_only)
11022 option_conflict('F', 'f');
11023 if (abort_edit && edit_only)
11024 option_conflict('a', 'e');
11025 if (continue_edit && edit_only)
11026 option_conflict('c', 'e');
11027 if (edit_only && edit_logmsg_only)
11028 option_conflict('e', 'm');
11029 if (edit_script_path && edit_only)
11030 option_conflict('F', 'e');
11031 if (list_backups) {
11032 if (abort_edit)
11033 option_conflict('l', 'a');
11034 if (continue_edit)
11035 option_conflict('l', 'c');
11036 if (edit_script_path)
11037 option_conflict('l', 'F');
11038 if (edit_logmsg_only)
11039 option_conflict('l', 'm');
11040 if (fold_only)
11041 option_conflict('l', 'f');
11042 if (edit_only)
11043 option_conflict('l', 'e');
11044 if (delete_backups)
11045 option_conflict('l', 'X');
11046 if (argc != 0 && argc != 1)
11047 usage_histedit();
11048 } else if (delete_backups) {
11049 if (abort_edit)
11050 option_conflict('X', 'a');
11051 if (continue_edit)
11052 option_conflict('X', 'c');
11053 if (edit_script_path)
11054 option_conflict('X', 'F');
11055 if (edit_logmsg_only)
11056 option_conflict('X', 'm');
11057 if (fold_only)
11058 option_conflict('X', 'f');
11059 if (edit_only)
11060 option_conflict('X', 'e');
11061 if (list_backups)
11062 option_conflict('X', 'l');
11063 if (argc != 0 && argc != 1)
11064 usage_histedit();
11065 } else if (argc != 0)
11066 usage_histedit();
11069 * This command cannot apply unveil(2) in all cases because the
11070 * user may choose to run an editor to edit the histedit script
11071 * and to edit individual commit log messages.
11072 * unveil(2) traverses exec(2); if an editor is used we have to
11073 * apply unveil after edit script and log messages have been written.
11074 * XXX TODO: Make use of unveil(2) where possible.
11077 cwd = getcwd(NULL, 0);
11078 if (cwd == NULL) {
11079 error = got_error_from_errno("getcwd");
11080 goto done;
11083 error = got_repo_pack_fds_open(&pack_fds);
11084 if (error != NULL)
11085 goto done;
11087 error = got_worktree_open(&worktree, cwd);
11088 if (error) {
11089 if (list_backups || delete_backups) {
11090 if (error->code != GOT_ERR_NOT_WORKTREE)
11091 goto done;
11092 } else {
11093 if (error->code == GOT_ERR_NOT_WORKTREE)
11094 error = wrap_not_worktree_error(error,
11095 "histedit", cwd);
11096 goto done;
11100 if (list_backups || delete_backups) {
11101 error = got_repo_open(&repo,
11102 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11103 NULL, pack_fds);
11104 if (error != NULL)
11105 goto done;
11106 error = apply_unveil(got_repo_get_path(repo), 0,
11107 worktree ? got_worktree_get_root_path(worktree) : NULL);
11108 if (error)
11109 goto done;
11110 error = process_backup_refs(
11111 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11112 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11113 goto done; /* nothing else to do */
11116 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11117 NULL, pack_fds);
11118 if (error != NULL)
11119 goto done;
11121 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11122 if (error)
11123 goto done;
11124 if (rebase_in_progress) {
11125 error = got_error(GOT_ERR_REBASING);
11126 goto done;
11129 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11130 repo);
11131 if (error)
11132 goto done;
11133 if (merge_in_progress) {
11134 error = got_error(GOT_ERR_MERGE_BUSY);
11135 goto done;
11138 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11139 if (error)
11140 goto done;
11142 if (edit_in_progress && edit_logmsg_only) {
11143 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11144 "histedit operation is in progress in this "
11145 "work tree and must be continued or aborted "
11146 "before the -m option can be used");
11147 goto done;
11149 if (edit_in_progress && fold_only) {
11150 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11151 "histedit operation is in progress in this "
11152 "work tree and must be continued or aborted "
11153 "before the -f option can be used");
11154 goto done;
11156 if (edit_in_progress && edit_only) {
11157 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11158 "histedit operation is in progress in this "
11159 "work tree and must be continued or aborted "
11160 "before the -e option can be used");
11161 goto done;
11164 if (edit_in_progress && abort_edit) {
11165 error = got_worktree_histedit_continue(&resume_commit_id,
11166 &tmp_branch, &branch, &base_commit_id, &fileindex,
11167 worktree, repo);
11168 if (error)
11169 goto done;
11170 printf("Switching work tree to %s\n",
11171 got_ref_get_symref_target(branch));
11172 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11173 branch, base_commit_id, abort_progress, &upa);
11174 if (error)
11175 goto done;
11176 printf("Histedit of %s aborted\n",
11177 got_ref_get_symref_target(branch));
11178 print_merge_progress_stats(&upa);
11179 goto done; /* nothing else to do */
11180 } else if (abort_edit) {
11181 error = got_error(GOT_ERR_NOT_HISTEDIT);
11182 goto done;
11185 if (continue_edit) {
11186 char *path;
11188 if (!edit_in_progress) {
11189 error = got_error(GOT_ERR_NOT_HISTEDIT);
11190 goto done;
11193 error = got_worktree_get_histedit_script_path(&path, worktree);
11194 if (error)
11195 goto done;
11197 error = histedit_load_list(&histedit_cmds, path, repo);
11198 free(path);
11199 if (error)
11200 goto done;
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;
11208 error = got_ref_resolve(&head_commit_id, repo, branch);
11209 if (error)
11210 goto done;
11212 error = got_object_open_as_commit(&commit, repo,
11213 head_commit_id);
11214 if (error)
11215 goto done;
11216 parent_ids = got_object_commit_get_parent_ids(commit);
11217 pid = STAILQ_FIRST(parent_ids);
11218 if (pid == NULL) {
11219 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11220 goto done;
11222 error = collect_commits(&commits, head_commit_id, &pid->id,
11223 base_commit_id, got_worktree_get_path_prefix(worktree),
11224 GOT_ERR_HISTEDIT_PATH, repo);
11225 got_object_commit_close(commit);
11226 commit = NULL;
11227 if (error)
11228 goto done;
11229 } else {
11230 if (edit_in_progress) {
11231 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11232 goto done;
11235 error = got_ref_open(&branch, repo,
11236 got_worktree_get_head_ref_name(worktree), 0);
11237 if (error != NULL)
11238 goto done;
11240 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11241 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11242 "will not edit commit history of a branch outside "
11243 "the \"refs/heads/\" reference namespace");
11244 goto done;
11247 error = got_ref_resolve(&head_commit_id, repo, branch);
11248 got_ref_close(branch);
11249 branch = NULL;
11250 if (error)
11251 goto done;
11253 error = got_object_open_as_commit(&commit, repo,
11254 head_commit_id);
11255 if (error)
11256 goto done;
11257 parent_ids = got_object_commit_get_parent_ids(commit);
11258 pid = STAILQ_FIRST(parent_ids);
11259 if (pid == NULL) {
11260 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11261 goto done;
11263 error = collect_commits(&commits, head_commit_id, &pid->id,
11264 got_worktree_get_base_commit_id(worktree),
11265 got_worktree_get_path_prefix(worktree),
11266 GOT_ERR_HISTEDIT_PATH, repo);
11267 got_object_commit_close(commit);
11268 commit = NULL;
11269 if (error)
11270 goto done;
11272 if (STAILQ_EMPTY(&commits)) {
11273 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11274 goto done;
11277 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11278 &base_commit_id, &fileindex, worktree, repo);
11279 if (error)
11280 goto done;
11282 if (edit_script_path) {
11283 error = histedit_load_list(&histedit_cmds,
11284 edit_script_path, repo);
11285 if (error) {
11286 got_worktree_histedit_abort(worktree, fileindex,
11287 repo, branch, base_commit_id,
11288 abort_progress, &upa);
11289 print_merge_progress_stats(&upa);
11290 goto done;
11292 } else {
11293 const char *branch_name;
11294 branch_name = got_ref_get_symref_target(branch);
11295 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11296 branch_name += 11;
11297 error = histedit_edit_script(&histedit_cmds, &commits,
11298 branch_name, edit_logmsg_only, fold_only,
11299 edit_only, repo);
11300 if (error) {
11301 got_worktree_histedit_abort(worktree, fileindex,
11302 repo, branch, base_commit_id,
11303 abort_progress, &upa);
11304 print_merge_progress_stats(&upa);
11305 goto done;
11310 error = histedit_save_list(&histedit_cmds, worktree,
11311 repo);
11312 if (error) {
11313 got_worktree_histedit_abort(worktree, fileindex,
11314 repo, branch, base_commit_id,
11315 abort_progress, &upa);
11316 print_merge_progress_stats(&upa);
11317 goto done;
11322 error = histedit_check_script(&histedit_cmds, &commits, repo);
11323 if (error)
11324 goto done;
11326 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11327 if (resume_commit_id) {
11328 if (got_object_id_cmp(hle->commit_id,
11329 resume_commit_id) != 0)
11330 continue;
11332 resume_commit_id = NULL;
11333 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11334 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11335 error = histedit_skip_commit(hle, worktree,
11336 repo);
11337 if (error)
11338 goto done;
11339 } else {
11340 struct got_pathlist_head paths;
11341 int have_changes = 0;
11343 TAILQ_INIT(&paths);
11344 error = got_pathlist_append(&paths, "", NULL);
11345 if (error)
11346 goto done;
11347 error = got_worktree_status(worktree, &paths,
11348 repo, 0, check_local_changes, &have_changes,
11349 check_cancelled, NULL);
11350 got_pathlist_free(&paths);
11351 if (error) {
11352 if (error->code != GOT_ERR_CANCELLED)
11353 goto done;
11354 if (sigint_received || sigpipe_received)
11355 goto done;
11357 if (have_changes) {
11358 error = histedit_commit(NULL, worktree,
11359 fileindex, tmp_branch, hle, repo);
11360 if (error)
11361 goto done;
11362 } else {
11363 error = got_object_open_as_commit(
11364 &commit, repo, hle->commit_id);
11365 if (error)
11366 goto done;
11367 error = show_histedit_progress(commit,
11368 hle, NULL);
11369 got_object_commit_close(commit);
11370 commit = NULL;
11371 if (error)
11372 goto done;
11375 continue;
11378 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11379 error = histedit_skip_commit(hle, worktree, repo);
11380 if (error)
11381 goto done;
11382 continue;
11385 error = got_object_open_as_commit(&commit, repo,
11386 hle->commit_id);
11387 if (error)
11388 goto done;
11389 parent_ids = got_object_commit_get_parent_ids(commit);
11390 pid = STAILQ_FIRST(parent_ids);
11392 error = got_worktree_histedit_merge_files(&merged_paths,
11393 worktree, fileindex, &pid->id, hle->commit_id, repo,
11394 update_progress, &upa, check_cancelled, NULL);
11395 if (error)
11396 goto done;
11397 got_object_commit_close(commit);
11398 commit = NULL;
11400 print_merge_progress_stats(&upa);
11401 if (upa.conflicts > 0 || upa.missing > 0 ||
11402 upa.not_deleted > 0 || upa.unversioned > 0) {
11403 if (upa.conflicts > 0) {
11404 error = show_rebase_merge_conflict(
11405 hle->commit_id, repo);
11406 if (error)
11407 goto done;
11409 got_worktree_rebase_pathlist_free(&merged_paths);
11410 break;
11413 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11414 char *id_str;
11415 error = got_object_id_str(&id_str, hle->commit_id);
11416 if (error)
11417 goto done;
11418 printf("Stopping histedit for amending commit %s\n",
11419 id_str);
11420 free(id_str);
11421 got_worktree_rebase_pathlist_free(&merged_paths);
11422 error = got_worktree_histedit_postpone(worktree,
11423 fileindex);
11424 goto done;
11427 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11428 error = histedit_skip_commit(hle, worktree, repo);
11429 if (error)
11430 goto done;
11431 continue;
11434 error = histedit_commit(&merged_paths, worktree, fileindex,
11435 tmp_branch, hle, repo);
11436 got_worktree_rebase_pathlist_free(&merged_paths);
11437 if (error)
11438 goto done;
11441 if (upa.conflicts > 0 || upa.missing > 0 ||
11442 upa.not_deleted > 0 || upa.unversioned > 0) {
11443 error = got_worktree_histedit_postpone(worktree, fileindex);
11444 if (error)
11445 goto done;
11446 if (upa.conflicts > 0 && upa.missing == 0 &&
11447 upa.not_deleted == 0 && upa.unversioned == 0) {
11448 error = got_error_msg(GOT_ERR_CONFLICTS,
11449 "conflicts must be resolved before histedit "
11450 "can continue");
11451 } else if (upa.conflicts > 0) {
11452 error = got_error_msg(GOT_ERR_CONFLICTS,
11453 "conflicts must be resolved before histedit "
11454 "can continue; changes destined for some "
11455 "files were not yet merged and should be "
11456 "merged manually if required before the "
11457 "histedit operation is continued");
11458 } else {
11459 error = got_error_msg(GOT_ERR_CONFLICTS,
11460 "changes destined for some files were not "
11461 "yet merged and should be merged manually "
11462 "if required before the histedit operation "
11463 "is continued");
11465 } else
11466 error = histedit_complete(worktree, fileindex, tmp_branch,
11467 branch, repo);
11468 done:
11469 got_object_id_queue_free(&commits);
11470 histedit_free_list(&histedit_cmds);
11471 free(head_commit_id);
11472 free(base_commit_id);
11473 free(resume_commit_id);
11474 if (commit)
11475 got_object_commit_close(commit);
11476 if (branch)
11477 got_ref_close(branch);
11478 if (tmp_branch)
11479 got_ref_close(tmp_branch);
11480 if (worktree)
11481 got_worktree_close(worktree);
11482 if (repo) {
11483 const struct got_error *close_err = got_repo_close(repo);
11484 if (error == NULL)
11485 error = close_err;
11487 if (pack_fds) {
11488 const struct got_error *pack_err =
11489 got_repo_pack_fds_close(pack_fds);
11490 if (error == NULL)
11491 error = pack_err;
11493 return error;
11496 __dead static void
11497 usage_integrate(void)
11499 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11500 exit(1);
11503 static const struct got_error *
11504 cmd_integrate(int argc, char *argv[])
11506 const struct got_error *error = NULL;
11507 struct got_repository *repo = NULL;
11508 struct got_worktree *worktree = NULL;
11509 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11510 const char *branch_arg = NULL;
11511 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11512 struct got_fileindex *fileindex = NULL;
11513 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11514 int ch;
11515 struct got_update_progress_arg upa;
11516 int *pack_fds = NULL;
11518 while ((ch = getopt(argc, argv, "")) != -1) {
11519 switch (ch) {
11520 default:
11521 usage_integrate();
11522 /* NOTREACHED */
11526 argc -= optind;
11527 argv += optind;
11529 if (argc != 1)
11530 usage_integrate();
11531 branch_arg = argv[0];
11532 #ifndef PROFILE
11533 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11534 "unveil", NULL) == -1)
11535 err(1, "pledge");
11536 #endif
11537 cwd = getcwd(NULL, 0);
11538 if (cwd == NULL) {
11539 error = got_error_from_errno("getcwd");
11540 goto done;
11543 error = got_repo_pack_fds_open(&pack_fds);
11544 if (error != NULL)
11545 goto done;
11547 error = got_worktree_open(&worktree, cwd);
11548 if (error) {
11549 if (error->code == GOT_ERR_NOT_WORKTREE)
11550 error = wrap_not_worktree_error(error, "integrate",
11551 cwd);
11552 goto done;
11555 error = check_rebase_or_histedit_in_progress(worktree);
11556 if (error)
11557 goto done;
11559 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11560 NULL, pack_fds);
11561 if (error != NULL)
11562 goto done;
11564 error = apply_unveil(got_repo_get_path(repo), 0,
11565 got_worktree_get_root_path(worktree));
11566 if (error)
11567 goto done;
11569 error = check_merge_in_progress(worktree, repo);
11570 if (error)
11571 goto done;
11573 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11574 error = got_error_from_errno("asprintf");
11575 goto done;
11578 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11579 &base_branch_ref, worktree, refname, repo);
11580 if (error)
11581 goto done;
11583 refname = strdup(got_ref_get_name(branch_ref));
11584 if (refname == NULL) {
11585 error = got_error_from_errno("strdup");
11586 got_worktree_integrate_abort(worktree, fileindex, repo,
11587 branch_ref, base_branch_ref);
11588 goto done;
11590 base_refname = strdup(got_ref_get_name(base_branch_ref));
11591 if (base_refname == NULL) {
11592 error = got_error_from_errno("strdup");
11593 got_worktree_integrate_abort(worktree, fileindex, repo,
11594 branch_ref, base_branch_ref);
11595 goto done;
11598 error = got_ref_resolve(&commit_id, repo, branch_ref);
11599 if (error)
11600 goto done;
11602 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11603 if (error)
11604 goto done;
11606 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11607 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11608 "specified branch has already been integrated");
11609 got_worktree_integrate_abort(worktree, fileindex, repo,
11610 branch_ref, base_branch_ref);
11611 goto done;
11614 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11615 if (error) {
11616 if (error->code == GOT_ERR_ANCESTRY)
11617 error = got_error(GOT_ERR_REBASE_REQUIRED);
11618 got_worktree_integrate_abort(worktree, fileindex, repo,
11619 branch_ref, base_branch_ref);
11620 goto done;
11623 memset(&upa, 0, sizeof(upa));
11624 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11625 branch_ref, base_branch_ref, update_progress, &upa,
11626 check_cancelled, NULL);
11627 if (error)
11628 goto done;
11630 printf("Integrated %s into %s\n", refname, base_refname);
11631 print_update_progress_stats(&upa);
11632 done:
11633 if (repo) {
11634 const struct got_error *close_err = got_repo_close(repo);
11635 if (error == NULL)
11636 error = close_err;
11638 if (worktree)
11639 got_worktree_close(worktree);
11640 if (pack_fds) {
11641 const struct got_error *pack_err =
11642 got_repo_pack_fds_close(pack_fds);
11643 if (error == NULL)
11644 error = pack_err;
11646 free(cwd);
11647 free(base_commit_id);
11648 free(commit_id);
11649 free(refname);
11650 free(base_refname);
11651 return error;
11654 __dead static void
11655 usage_merge(void)
11657 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11658 getprogname());
11659 exit(1);
11662 static const struct got_error *
11663 cmd_merge(int argc, char *argv[])
11665 const struct got_error *error = NULL;
11666 struct got_worktree *worktree = NULL;
11667 struct got_repository *repo = NULL;
11668 struct got_fileindex *fileindex = NULL;
11669 char *cwd = NULL, *id_str = NULL, *author = NULL;
11670 struct got_reference *branch = NULL, *wt_branch = NULL;
11671 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11672 struct got_object_id *wt_branch_tip = NULL;
11673 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11674 int interrupt_merge = 0;
11675 struct got_update_progress_arg upa;
11676 struct got_object_id *merge_commit_id = NULL;
11677 char *branch_name = NULL;
11678 int *pack_fds = NULL;
11680 memset(&upa, 0, sizeof(upa));
11682 while ((ch = getopt(argc, argv, "acn")) != -1) {
11683 switch (ch) {
11684 case 'a':
11685 abort_merge = 1;
11686 break;
11687 case 'c':
11688 continue_merge = 1;
11689 break;
11690 case 'n':
11691 interrupt_merge = 1;
11692 break;
11693 default:
11694 usage_rebase();
11695 /* NOTREACHED */
11699 argc -= optind;
11700 argv += optind;
11702 #ifndef PROFILE
11703 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11704 "unveil", NULL) == -1)
11705 err(1, "pledge");
11706 #endif
11708 if (abort_merge && continue_merge)
11709 option_conflict('a', 'c');
11710 if (abort_merge || continue_merge) {
11711 if (argc != 0)
11712 usage_merge();
11713 } else if (argc != 1)
11714 usage_merge();
11716 cwd = getcwd(NULL, 0);
11717 if (cwd == NULL) {
11718 error = got_error_from_errno("getcwd");
11719 goto done;
11722 error = got_repo_pack_fds_open(&pack_fds);
11723 if (error != NULL)
11724 goto done;
11726 error = got_worktree_open(&worktree, cwd);
11727 if (error) {
11728 if (error->code == GOT_ERR_NOT_WORKTREE)
11729 error = wrap_not_worktree_error(error,
11730 "merge", cwd);
11731 goto done;
11734 error = got_repo_open(&repo,
11735 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11736 pack_fds);
11737 if (error != NULL)
11738 goto done;
11740 error = apply_unveil(got_repo_get_path(repo), 0,
11741 worktree ? got_worktree_get_root_path(worktree) : NULL);
11742 if (error)
11743 goto done;
11745 error = check_rebase_or_histedit_in_progress(worktree);
11746 if (error)
11747 goto done;
11749 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11750 repo);
11751 if (error)
11752 goto done;
11754 if (abort_merge) {
11755 if (!merge_in_progress) {
11756 error = got_error(GOT_ERR_NOT_MERGING);
11757 goto done;
11759 error = got_worktree_merge_continue(&branch_name,
11760 &branch_tip, &fileindex, worktree, repo);
11761 if (error)
11762 goto done;
11763 error = got_worktree_merge_abort(worktree, fileindex, repo,
11764 abort_progress, &upa);
11765 if (error)
11766 goto done;
11767 printf("Merge of %s aborted\n", branch_name);
11768 goto done; /* nothing else to do */
11771 error = get_author(&author, repo, worktree);
11772 if (error)
11773 goto done;
11775 if (continue_merge) {
11776 if (!merge_in_progress) {
11777 error = got_error(GOT_ERR_NOT_MERGING);
11778 goto done;
11780 error = got_worktree_merge_continue(&branch_name,
11781 &branch_tip, &fileindex, worktree, repo);
11782 if (error)
11783 goto done;
11784 } else {
11785 error = got_ref_open(&branch, repo, argv[0], 0);
11786 if (error != NULL)
11787 goto done;
11788 branch_name = strdup(got_ref_get_name(branch));
11789 if (branch_name == NULL) {
11790 error = got_error_from_errno("strdup");
11791 goto done;
11793 error = got_ref_resolve(&branch_tip, repo, branch);
11794 if (error)
11795 goto done;
11798 error = got_ref_open(&wt_branch, repo,
11799 got_worktree_get_head_ref_name(worktree), 0);
11800 if (error)
11801 goto done;
11802 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11803 if (error)
11804 goto done;
11805 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11806 wt_branch_tip, branch_tip, 0, repo,
11807 check_cancelled, NULL);
11808 if (error && error->code != GOT_ERR_ANCESTRY)
11809 goto done;
11811 if (!continue_merge) {
11812 error = check_path_prefix(wt_branch_tip, branch_tip,
11813 got_worktree_get_path_prefix(worktree),
11814 GOT_ERR_MERGE_PATH, repo);
11815 if (error)
11816 goto done;
11817 if (yca_id) {
11818 error = check_same_branch(wt_branch_tip, branch,
11819 yca_id, repo);
11820 if (error) {
11821 if (error->code != GOT_ERR_ANCESTRY)
11822 goto done;
11823 error = NULL;
11824 } else {
11825 static char msg[512];
11826 snprintf(msg, sizeof(msg),
11827 "cannot create a merge commit because "
11828 "%s is based on %s; %s can be integrated "
11829 "with 'got integrate' instead", branch_name,
11830 got_worktree_get_head_ref_name(worktree),
11831 branch_name);
11832 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11833 goto done;
11836 error = got_worktree_merge_prepare(&fileindex, worktree,
11837 branch, repo);
11838 if (error)
11839 goto done;
11841 error = got_worktree_merge_branch(worktree, fileindex,
11842 yca_id, branch_tip, repo, update_progress, &upa,
11843 check_cancelled, NULL);
11844 if (error)
11845 goto done;
11846 print_merge_progress_stats(&upa);
11847 if (!upa.did_something) {
11848 error = got_worktree_merge_abort(worktree, fileindex,
11849 repo, abort_progress, &upa);
11850 if (error)
11851 goto done;
11852 printf("Already up-to-date\n");
11853 goto done;
11857 if (interrupt_merge) {
11858 error = got_worktree_merge_postpone(worktree, fileindex);
11859 if (error)
11860 goto done;
11861 printf("Merge of %s interrupted on request\n", branch_name);
11862 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11863 upa.not_deleted > 0 || upa.unversioned > 0) {
11864 error = got_worktree_merge_postpone(worktree, fileindex);
11865 if (error)
11866 goto done;
11867 if (upa.conflicts > 0 && upa.missing == 0 &&
11868 upa.not_deleted == 0 && upa.unversioned == 0) {
11869 error = got_error_msg(GOT_ERR_CONFLICTS,
11870 "conflicts must be resolved before merging "
11871 "can continue");
11872 } else if (upa.conflicts > 0) {
11873 error = got_error_msg(GOT_ERR_CONFLICTS,
11874 "conflicts must be resolved before merging "
11875 "can continue; changes destined for some "
11876 "files were not yet merged and "
11877 "should be merged manually if required before the "
11878 "merge operation is continued");
11879 } else {
11880 error = got_error_msg(GOT_ERR_CONFLICTS,
11881 "changes destined for some "
11882 "files were not yet merged and should be "
11883 "merged manually if required before the "
11884 "merge operation is continued");
11886 goto done;
11887 } else {
11888 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11889 fileindex, author, NULL, 1, branch_tip, branch_name,
11890 repo, continue_merge ? print_status : NULL, NULL);
11891 if (error)
11892 goto done;
11893 error = got_worktree_merge_complete(worktree, fileindex, repo);
11894 if (error)
11895 goto done;
11896 error = got_object_id_str(&id_str, merge_commit_id);
11897 if (error)
11898 goto done;
11899 printf("Merged %s into %s: %s\n", branch_name,
11900 got_worktree_get_head_ref_name(worktree),
11901 id_str);
11904 done:
11905 free(id_str);
11906 free(merge_commit_id);
11907 free(author);
11908 free(branch_tip);
11909 free(branch_name);
11910 free(yca_id);
11911 if (branch)
11912 got_ref_close(branch);
11913 if (wt_branch)
11914 got_ref_close(wt_branch);
11915 if (worktree)
11916 got_worktree_close(worktree);
11917 if (repo) {
11918 const struct got_error *close_err = got_repo_close(repo);
11919 if (error == NULL)
11920 error = close_err;
11922 if (pack_fds) {
11923 const struct got_error *pack_err =
11924 got_repo_pack_fds_close(pack_fds);
11925 if (error == NULL)
11926 error = pack_err;
11928 return error;
11931 __dead static void
11932 usage_stage(void)
11934 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11935 "[-S] [file-path ...]\n",
11936 getprogname());
11937 exit(1);
11940 static const struct got_error *
11941 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11942 const char *path, struct got_object_id *blob_id,
11943 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11944 int dirfd, const char *de_name)
11946 const struct got_error *err = NULL;
11947 char *id_str = NULL;
11949 if (staged_status != GOT_STATUS_ADD &&
11950 staged_status != GOT_STATUS_MODIFY &&
11951 staged_status != GOT_STATUS_DELETE)
11952 return NULL;
11954 if (staged_status == GOT_STATUS_ADD ||
11955 staged_status == GOT_STATUS_MODIFY)
11956 err = got_object_id_str(&id_str, staged_blob_id);
11957 else
11958 err = got_object_id_str(&id_str, blob_id);
11959 if (err)
11960 return err;
11962 printf("%s %c %s\n", id_str, staged_status, path);
11963 free(id_str);
11964 return NULL;
11967 static const struct got_error *
11968 cmd_stage(int argc, char *argv[])
11970 const struct got_error *error = NULL;
11971 struct got_repository *repo = NULL;
11972 struct got_worktree *worktree = NULL;
11973 char *cwd = NULL;
11974 struct got_pathlist_head paths;
11975 struct got_pathlist_entry *pe;
11976 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11977 FILE *patch_script_file = NULL;
11978 const char *patch_script_path = NULL;
11979 struct choose_patch_arg cpa;
11980 int *pack_fds = NULL;
11982 TAILQ_INIT(&paths);
11984 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11985 switch (ch) {
11986 case 'l':
11987 list_stage = 1;
11988 break;
11989 case 'p':
11990 pflag = 1;
11991 break;
11992 case 'F':
11993 patch_script_path = optarg;
11994 break;
11995 case 'S':
11996 allow_bad_symlinks = 1;
11997 break;
11998 default:
11999 usage_stage();
12000 /* NOTREACHED */
12004 argc -= optind;
12005 argv += optind;
12007 #ifndef PROFILE
12008 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12009 "unveil", NULL) == -1)
12010 err(1, "pledge");
12011 #endif
12012 if (list_stage && (pflag || patch_script_path))
12013 errx(1, "-l option cannot be used with other options");
12014 if (patch_script_path && !pflag)
12015 errx(1, "-F option can only be used together with -p option");
12017 cwd = getcwd(NULL, 0);
12018 if (cwd == NULL) {
12019 error = got_error_from_errno("getcwd");
12020 goto done;
12023 error = got_repo_pack_fds_open(&pack_fds);
12024 if (error != NULL)
12025 goto done;
12027 error = got_worktree_open(&worktree, cwd);
12028 if (error) {
12029 if (error->code == GOT_ERR_NOT_WORKTREE)
12030 error = wrap_not_worktree_error(error, "stage", cwd);
12031 goto done;
12034 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12035 NULL, pack_fds);
12036 if (error != NULL)
12037 goto done;
12039 if (patch_script_path) {
12040 patch_script_file = fopen(patch_script_path, "re");
12041 if (patch_script_file == NULL) {
12042 error = got_error_from_errno2("fopen",
12043 patch_script_path);
12044 goto done;
12047 error = apply_unveil(got_repo_get_path(repo), 0,
12048 got_worktree_get_root_path(worktree));
12049 if (error)
12050 goto done;
12052 error = check_merge_in_progress(worktree, repo);
12053 if (error)
12054 goto done;
12056 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12057 if (error)
12058 goto done;
12060 if (list_stage)
12061 error = got_worktree_status(worktree, &paths, repo, 0,
12062 print_stage, NULL, check_cancelled, NULL);
12063 else {
12064 cpa.patch_script_file = patch_script_file;
12065 cpa.action = "stage";
12066 error = got_worktree_stage(worktree, &paths,
12067 pflag ? NULL : print_status, NULL,
12068 pflag ? choose_patch : NULL, &cpa,
12069 allow_bad_symlinks, repo);
12071 done:
12072 if (patch_script_file && fclose(patch_script_file) == EOF &&
12073 error == NULL)
12074 error = got_error_from_errno2("fclose", patch_script_path);
12075 if (repo) {
12076 const struct got_error *close_err = got_repo_close(repo);
12077 if (error == NULL)
12078 error = close_err;
12080 if (worktree)
12081 got_worktree_close(worktree);
12082 if (pack_fds) {
12083 const struct got_error *pack_err =
12084 got_repo_pack_fds_close(pack_fds);
12085 if (error == NULL)
12086 error = pack_err;
12088 TAILQ_FOREACH(pe, &paths, entry)
12089 free((char *)pe->path);
12090 got_pathlist_free(&paths);
12091 free(cwd);
12092 return error;
12095 __dead static void
12096 usage_unstage(void)
12098 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12099 "[file-path ...]\n",
12100 getprogname());
12101 exit(1);
12105 static const struct got_error *
12106 cmd_unstage(int argc, char *argv[])
12108 const struct got_error *error = NULL;
12109 struct got_repository *repo = NULL;
12110 struct got_worktree *worktree = NULL;
12111 char *cwd = NULL;
12112 struct got_pathlist_head paths;
12113 struct got_pathlist_entry *pe;
12114 int ch, pflag = 0;
12115 struct got_update_progress_arg upa;
12116 FILE *patch_script_file = NULL;
12117 const char *patch_script_path = NULL;
12118 struct choose_patch_arg cpa;
12119 int *pack_fds = NULL;
12121 TAILQ_INIT(&paths);
12123 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12124 switch (ch) {
12125 case 'p':
12126 pflag = 1;
12127 break;
12128 case 'F':
12129 patch_script_path = optarg;
12130 break;
12131 default:
12132 usage_unstage();
12133 /* NOTREACHED */
12137 argc -= optind;
12138 argv += optind;
12140 #ifndef PROFILE
12141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12142 "unveil", NULL) == -1)
12143 err(1, "pledge");
12144 #endif
12145 if (patch_script_path && !pflag)
12146 errx(1, "-F option can only be used together with -p option");
12148 cwd = getcwd(NULL, 0);
12149 if (cwd == NULL) {
12150 error = got_error_from_errno("getcwd");
12151 goto done;
12154 error = got_repo_pack_fds_open(&pack_fds);
12155 if (error != NULL)
12156 goto done;
12158 error = got_worktree_open(&worktree, cwd);
12159 if (error) {
12160 if (error->code == GOT_ERR_NOT_WORKTREE)
12161 error = wrap_not_worktree_error(error, "unstage", cwd);
12162 goto done;
12165 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12166 NULL, pack_fds);
12167 if (error != NULL)
12168 goto done;
12170 if (patch_script_path) {
12171 patch_script_file = fopen(patch_script_path, "re");
12172 if (patch_script_file == NULL) {
12173 error = got_error_from_errno2("fopen",
12174 patch_script_path);
12175 goto done;
12179 error = apply_unveil(got_repo_get_path(repo), 0,
12180 got_worktree_get_root_path(worktree));
12181 if (error)
12182 goto done;
12184 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12185 if (error)
12186 goto done;
12188 cpa.patch_script_file = patch_script_file;
12189 cpa.action = "unstage";
12190 memset(&upa, 0, sizeof(upa));
12191 error = got_worktree_unstage(worktree, &paths, update_progress,
12192 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12193 if (!error)
12194 print_merge_progress_stats(&upa);
12195 done:
12196 if (patch_script_file && fclose(patch_script_file) == EOF &&
12197 error == NULL)
12198 error = got_error_from_errno2("fclose", patch_script_path);
12199 if (repo) {
12200 const struct got_error *close_err = got_repo_close(repo);
12201 if (error == NULL)
12202 error = close_err;
12204 if (worktree)
12205 got_worktree_close(worktree);
12206 if (pack_fds) {
12207 const struct got_error *pack_err =
12208 got_repo_pack_fds_close(pack_fds);
12209 if (error == NULL)
12210 error = pack_err;
12212 TAILQ_FOREACH(pe, &paths, entry)
12213 free((char *)pe->path);
12214 got_pathlist_free(&paths);
12215 free(cwd);
12216 return error;
12219 __dead static void
12220 usage_cat(void)
12222 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12223 "arg1 [arg2 ...]\n", getprogname());
12224 exit(1);
12227 static const struct got_error *
12228 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12230 const struct got_error *err;
12231 struct got_blob_object *blob;
12233 err = got_object_open_as_blob(&blob, repo, id, 8192);
12234 if (err)
12235 return err;
12237 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12238 got_object_blob_close(blob);
12239 return err;
12242 static const struct got_error *
12243 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12245 const struct got_error *err;
12246 struct got_tree_object *tree;
12247 int nentries, i;
12249 err = got_object_open_as_tree(&tree, repo, id);
12250 if (err)
12251 return err;
12253 nentries = got_object_tree_get_nentries(tree);
12254 for (i = 0; i < nentries; i++) {
12255 struct got_tree_entry *te;
12256 char *id_str;
12257 if (sigint_received || sigpipe_received)
12258 break;
12259 te = got_object_tree_get_entry(tree, i);
12260 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12261 if (err)
12262 break;
12263 fprintf(outfile, "%s %.7o %s\n", id_str,
12264 got_tree_entry_get_mode(te),
12265 got_tree_entry_get_name(te));
12266 free(id_str);
12269 got_object_tree_close(tree);
12270 return err;
12273 static void
12274 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12276 long long h, m;
12277 char sign = '+';
12279 if (gmtoff < 0) {
12280 sign = '-';
12281 gmtoff = -gmtoff;
12284 h = (long long)gmtoff / 3600;
12285 m = ((long long)gmtoff - h*3600) / 60;
12286 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12289 static const struct got_error *
12290 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12292 const struct got_error *err;
12293 struct got_commit_object *commit;
12294 const struct got_object_id_queue *parent_ids;
12295 struct got_object_qid *pid;
12296 char *id_str = NULL;
12297 const char *logmsg = NULL;
12298 char gmtoff[6];
12300 err = got_object_open_as_commit(&commit, repo, id);
12301 if (err)
12302 return err;
12304 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12305 if (err)
12306 goto done;
12308 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12309 parent_ids = got_object_commit_get_parent_ids(commit);
12310 fprintf(outfile, "numparents %d\n",
12311 got_object_commit_get_nparents(commit));
12312 STAILQ_FOREACH(pid, parent_ids, entry) {
12313 char *pid_str;
12314 err = got_object_id_str(&pid_str, &pid->id);
12315 if (err)
12316 goto done;
12317 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12318 free(pid_str);
12320 format_gmtoff(gmtoff, sizeof(gmtoff),
12321 got_object_commit_get_author_gmtoff(commit));
12322 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12323 got_object_commit_get_author(commit),
12324 (long long)got_object_commit_get_author_time(commit),
12325 gmtoff);
12327 format_gmtoff(gmtoff, sizeof(gmtoff),
12328 got_object_commit_get_committer_gmtoff(commit));
12329 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12330 got_object_commit_get_author(commit),
12331 (long long)got_object_commit_get_committer_time(commit),
12332 gmtoff);
12334 logmsg = got_object_commit_get_logmsg_raw(commit);
12335 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12336 fprintf(outfile, "%s", logmsg);
12337 done:
12338 free(id_str);
12339 got_object_commit_close(commit);
12340 return err;
12343 static const struct got_error *
12344 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12346 const struct got_error *err;
12347 struct got_tag_object *tag;
12348 char *id_str = NULL;
12349 const char *tagmsg = NULL;
12350 char gmtoff[6];
12352 err = got_object_open_as_tag(&tag, repo, id);
12353 if (err)
12354 return err;
12356 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12357 if (err)
12358 goto done;
12360 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12362 switch (got_object_tag_get_object_type(tag)) {
12363 case GOT_OBJ_TYPE_BLOB:
12364 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12365 GOT_OBJ_LABEL_BLOB);
12366 break;
12367 case GOT_OBJ_TYPE_TREE:
12368 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12369 GOT_OBJ_LABEL_TREE);
12370 break;
12371 case GOT_OBJ_TYPE_COMMIT:
12372 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12373 GOT_OBJ_LABEL_COMMIT);
12374 break;
12375 case GOT_OBJ_TYPE_TAG:
12376 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12377 GOT_OBJ_LABEL_TAG);
12378 break;
12379 default:
12380 break;
12383 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12384 got_object_tag_get_name(tag));
12386 format_gmtoff(gmtoff, sizeof(gmtoff),
12387 got_object_tag_get_tagger_gmtoff(tag));
12388 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12389 got_object_tag_get_tagger(tag),
12390 (long long)got_object_tag_get_tagger_time(tag),
12391 gmtoff);
12393 tagmsg = got_object_tag_get_message(tag);
12394 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12395 fprintf(outfile, "%s", tagmsg);
12396 done:
12397 free(id_str);
12398 got_object_tag_close(tag);
12399 return err;
12402 static const struct got_error *
12403 cmd_cat(int argc, char *argv[])
12405 const struct got_error *error;
12406 struct got_repository *repo = NULL;
12407 struct got_worktree *worktree = NULL;
12408 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12409 const char *commit_id_str = NULL;
12410 struct got_object_id *id = NULL, *commit_id = NULL;
12411 struct got_commit_object *commit = NULL;
12412 int ch, obj_type, i, force_path = 0;
12413 struct got_reflist_head refs;
12414 int *pack_fds = NULL;
12416 TAILQ_INIT(&refs);
12418 #ifndef PROFILE
12419 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12420 NULL) == -1)
12421 err(1, "pledge");
12422 #endif
12424 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12425 switch (ch) {
12426 case 'c':
12427 commit_id_str = optarg;
12428 break;
12429 case 'r':
12430 repo_path = realpath(optarg, NULL);
12431 if (repo_path == NULL)
12432 return got_error_from_errno2("realpath",
12433 optarg);
12434 got_path_strip_trailing_slashes(repo_path);
12435 break;
12436 case 'P':
12437 force_path = 1;
12438 break;
12439 default:
12440 usage_cat();
12441 /* NOTREACHED */
12445 argc -= optind;
12446 argv += optind;
12448 cwd = getcwd(NULL, 0);
12449 if (cwd == NULL) {
12450 error = got_error_from_errno("getcwd");
12451 goto done;
12454 error = got_repo_pack_fds_open(&pack_fds);
12455 if (error != NULL)
12456 goto done;
12458 if (repo_path == NULL) {
12459 error = got_worktree_open(&worktree, cwd);
12460 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12461 goto done;
12462 if (worktree) {
12463 repo_path = strdup(
12464 got_worktree_get_repo_path(worktree));
12465 if (repo_path == NULL) {
12466 error = got_error_from_errno("strdup");
12467 goto done;
12470 /* Release work tree lock. */
12471 got_worktree_close(worktree);
12472 worktree = NULL;
12476 if (repo_path == NULL) {
12477 repo_path = strdup(cwd);
12478 if (repo_path == NULL)
12479 return got_error_from_errno("strdup");
12482 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12483 free(repo_path);
12484 if (error != NULL)
12485 goto done;
12487 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12488 if (error)
12489 goto done;
12491 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12492 if (error)
12493 goto done;
12495 if (commit_id_str == NULL)
12496 commit_id_str = GOT_REF_HEAD;
12497 error = got_repo_match_object_id(&commit_id, NULL,
12498 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12499 if (error)
12500 goto done;
12502 error = got_object_open_as_commit(&commit, repo, commit_id);
12503 if (error)
12504 goto done;
12506 for (i = 0; i < argc; i++) {
12507 if (force_path) {
12508 error = got_object_id_by_path(&id, repo, commit,
12509 argv[i]);
12510 if (error)
12511 break;
12512 } else {
12513 error = got_repo_match_object_id(&id, &label, argv[i],
12514 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12515 repo);
12516 if (error) {
12517 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12518 error->code != GOT_ERR_NOT_REF)
12519 break;
12520 error = got_object_id_by_path(&id, repo,
12521 commit, argv[i]);
12522 if (error)
12523 break;
12527 error = got_object_get_type(&obj_type, repo, id);
12528 if (error)
12529 break;
12531 switch (obj_type) {
12532 case GOT_OBJ_TYPE_BLOB:
12533 error = cat_blob(id, repo, stdout);
12534 break;
12535 case GOT_OBJ_TYPE_TREE:
12536 error = cat_tree(id, repo, stdout);
12537 break;
12538 case GOT_OBJ_TYPE_COMMIT:
12539 error = cat_commit(id, repo, stdout);
12540 break;
12541 case GOT_OBJ_TYPE_TAG:
12542 error = cat_tag(id, repo, stdout);
12543 break;
12544 default:
12545 error = got_error(GOT_ERR_OBJ_TYPE);
12546 break;
12548 if (error)
12549 break;
12550 free(label);
12551 label = NULL;
12552 free(id);
12553 id = NULL;
12555 done:
12556 free(label);
12557 free(id);
12558 free(commit_id);
12559 if (commit)
12560 got_object_commit_close(commit);
12561 if (worktree)
12562 got_worktree_close(worktree);
12563 if (repo) {
12564 const struct got_error *close_err = got_repo_close(repo);
12565 if (error == NULL)
12566 error = close_err;
12568 if (pack_fds) {
12569 const struct got_error *pack_err =
12570 got_repo_pack_fds_close(pack_fds);
12571 if (error == NULL)
12572 error = pack_err;
12575 got_ref_list_free(&refs);
12576 return error;
12579 __dead static void
12580 usage_info(void)
12582 fprintf(stderr, "usage: %s info [path ...]\n",
12583 getprogname());
12584 exit(1);
12587 static const struct got_error *
12588 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12589 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12590 struct got_object_id *commit_id)
12592 const struct got_error *err = NULL;
12593 char *id_str = NULL;
12594 char datebuf[128];
12595 struct tm mytm, *tm;
12596 struct got_pathlist_head *paths = arg;
12597 struct got_pathlist_entry *pe;
12600 * Clear error indication from any of the path arguments which
12601 * would cause this file index entry to be displayed.
12603 TAILQ_FOREACH(pe, paths, entry) {
12604 if (got_path_cmp(path, pe->path, strlen(path),
12605 pe->path_len) == 0 ||
12606 got_path_is_child(path, pe->path, pe->path_len))
12607 pe->data = NULL; /* no error */
12610 printf(GOT_COMMIT_SEP_STR);
12611 if (S_ISLNK(mode))
12612 printf("symlink: %s\n", path);
12613 else if (S_ISREG(mode)) {
12614 printf("file: %s\n", path);
12615 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12616 } else if (S_ISDIR(mode))
12617 printf("directory: %s\n", path);
12618 else
12619 printf("something: %s\n", path);
12621 tm = localtime_r(&mtime, &mytm);
12622 if (tm == NULL)
12623 return NULL;
12624 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12625 return got_error(GOT_ERR_NO_SPACE);
12626 printf("timestamp: %s\n", datebuf);
12628 if (blob_id) {
12629 err = got_object_id_str(&id_str, blob_id);
12630 if (err)
12631 return err;
12632 printf("based on blob: %s\n", id_str);
12633 free(id_str);
12636 if (staged_blob_id) {
12637 err = got_object_id_str(&id_str, staged_blob_id);
12638 if (err)
12639 return err;
12640 printf("based on staged blob: %s\n", id_str);
12641 free(id_str);
12644 if (commit_id) {
12645 err = got_object_id_str(&id_str, commit_id);
12646 if (err)
12647 return err;
12648 printf("based on commit: %s\n", id_str);
12649 free(id_str);
12652 return NULL;
12655 static const struct got_error *
12656 cmd_info(int argc, char *argv[])
12658 const struct got_error *error = NULL;
12659 struct got_worktree *worktree = NULL;
12660 char *cwd = NULL, *id_str = NULL;
12661 struct got_pathlist_head paths;
12662 struct got_pathlist_entry *pe;
12663 char *uuidstr = NULL;
12664 int ch, show_files = 0;
12665 int *pack_fds = NULL;
12667 TAILQ_INIT(&paths);
12669 while ((ch = getopt(argc, argv, "")) != -1) {
12670 switch (ch) {
12671 default:
12672 usage_info();
12673 /* NOTREACHED */
12677 argc -= optind;
12678 argv += optind;
12680 #ifndef PROFILE
12681 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12682 NULL) == -1)
12683 err(1, "pledge");
12684 #endif
12685 cwd = getcwd(NULL, 0);
12686 if (cwd == NULL) {
12687 error = got_error_from_errno("getcwd");
12688 goto done;
12691 error = got_repo_pack_fds_open(&pack_fds);
12692 if (error != NULL)
12693 goto done;
12695 error = got_worktree_open(&worktree, cwd);
12696 if (error) {
12697 if (error->code == GOT_ERR_NOT_WORKTREE)
12698 error = wrap_not_worktree_error(error, "info", cwd);
12699 goto done;
12702 #ifndef PROFILE
12703 /* Remove "cpath" promise. */
12704 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12705 NULL) == -1)
12706 err(1, "pledge");
12707 #endif
12708 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12709 if (error)
12710 goto done;
12712 if (argc >= 1) {
12713 error = get_worktree_paths_from_argv(&paths, argc, argv,
12714 worktree);
12715 if (error)
12716 goto done;
12717 show_files = 1;
12720 error = got_object_id_str(&id_str,
12721 got_worktree_get_base_commit_id(worktree));
12722 if (error)
12723 goto done;
12725 error = got_worktree_get_uuid(&uuidstr, worktree);
12726 if (error)
12727 goto done;
12729 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12730 printf("work tree base commit: %s\n", id_str);
12731 printf("work tree path prefix: %s\n",
12732 got_worktree_get_path_prefix(worktree));
12733 printf("work tree branch reference: %s\n",
12734 got_worktree_get_head_ref_name(worktree));
12735 printf("work tree UUID: %s\n", uuidstr);
12736 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12738 if (show_files) {
12739 struct got_pathlist_entry *pe;
12740 TAILQ_FOREACH(pe, &paths, entry) {
12741 if (pe->path_len == 0)
12742 continue;
12744 * Assume this path will fail. This will be corrected
12745 * in print_path_info() in case the path does suceeed.
12747 pe->data = (void *)got_error_path(pe->path,
12748 GOT_ERR_BAD_PATH);
12750 error = got_worktree_path_info(worktree, &paths,
12751 print_path_info, &paths, check_cancelled, NULL);
12752 if (error)
12753 goto done;
12754 TAILQ_FOREACH(pe, &paths, entry) {
12755 if (pe->data != NULL) {
12756 error = pe->data; /* bad path */
12757 break;
12761 done:
12762 if (pack_fds) {
12763 const struct got_error *pack_err =
12764 got_repo_pack_fds_close(pack_fds);
12765 if (error == NULL)
12766 error = pack_err;
12768 TAILQ_FOREACH(pe, &paths, entry)
12769 free((char *)pe->path);
12770 got_pathlist_free(&paths);
12771 free(cwd);
12772 free(id_str);
12773 free(uuidstr);
12774 return error;