Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static volatile sig_atomic_t sigint_received;
67 static volatile sig_atomic_t sigpipe_received;
69 static void
70 catch_sigint(int signo)
71 {
72 sigint_received = 1;
73 }
75 static void
76 catch_sigpipe(int signo)
77 {
78 sigpipe_received = 1;
79 }
82 struct got_cmd {
83 const char *cmd_name;
84 const struct got_error *(*cmd_main)(int, char *[]);
85 void (*cmd_usage)(void);
86 const char *cmd_alias;
87 };
89 __dead static void usage(int, int);
90 __dead static void usage_init(void);
91 __dead static void usage_import(void);
92 __dead static void usage_clone(void);
93 __dead static void usage_fetch(void);
94 __dead static void usage_checkout(void);
95 __dead static void usage_update(void);
96 __dead static void usage_log(void);
97 __dead static void usage_diff(void);
98 __dead static void usage_blame(void);
99 __dead static void usage_tree(void);
100 __dead static void usage_status(void);
101 __dead static void usage_ref(void);
102 __dead static void usage_branch(void);
103 __dead static void usage_tag(void);
104 __dead static void usage_add(void);
105 __dead static void usage_remove(void);
106 __dead static void usage_patch(void);
107 __dead static void usage_revert(void);
108 __dead static void usage_commit(void);
109 __dead static void usage_send(void);
110 __dead static void usage_cherrypick(void);
111 __dead static void usage_backout(void);
112 __dead static void usage_rebase(void);
113 __dead static void usage_histedit(void);
114 __dead static void usage_integrate(void);
115 __dead static void usage_merge(void);
116 __dead static void usage_stage(void);
117 __dead static void usage_unstage(void);
118 __dead static void usage_cat(void);
119 __dead static void usage_info(void);
121 static const struct got_error* cmd_init(int, char *[]);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "init", cmd_init, usage_init, "" },
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_init(void)
350 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
351 exit(1);
354 static const struct got_error *
355 cmd_init(int argc, char *argv[])
357 const struct got_error *error = NULL;
358 char *repo_path = NULL;
359 int ch;
361 while ((ch = getopt(argc, argv, "")) != -1) {
362 switch (ch) {
363 default:
364 usage_init();
365 /* NOTREACHED */
369 argc -= optind;
370 argv += optind;
372 #ifndef PROFILE
373 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
374 err(1, "pledge");
375 #endif
376 if (argc != 1)
377 usage_init();
379 repo_path = strdup(argv[0]);
380 if (repo_path == NULL)
381 return got_error_from_errno("strdup");
383 got_path_strip_trailing_slashes(repo_path);
385 error = got_path_mkdir(repo_path);
386 if (error &&
387 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
388 goto done;
390 error = apply_unveil(repo_path, 0, NULL);
391 if (error)
392 goto done;
394 error = got_repo_init(repo_path);
395 done:
396 free(repo_path);
397 return error;
400 __dead static void
401 usage_import(void)
403 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
404 "[-r repository-path] [-I pattern] path\n", getprogname());
405 exit(1);
408 int
409 spawn_editor(const char *editor, const char *file)
411 pid_t pid;
412 sig_t sighup, sigint, sigquit;
413 int st = -1;
415 sighup = signal(SIGHUP, SIG_IGN);
416 sigint = signal(SIGINT, SIG_IGN);
417 sigquit = signal(SIGQUIT, SIG_IGN);
419 switch (pid = fork()) {
420 case -1:
421 goto doneediting;
422 case 0:
423 execl(editor, editor, file, (char *)NULL);
424 _exit(127);
427 while (waitpid(pid, &st, 0) == -1)
428 if (errno != EINTR)
429 break;
431 doneediting:
432 (void)signal(SIGHUP, sighup);
433 (void)signal(SIGINT, sigint);
434 (void)signal(SIGQUIT, sigquit);
436 if (!WIFEXITED(st)) {
437 errno = EINTR;
438 return -1;
441 return WEXITSTATUS(st);
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 char *line = NULL;
451 size_t linesize = 0;
452 ssize_t linelen;
453 struct stat st, st2;
454 FILE *fp = NULL;
455 size_t len, logmsg_len;
456 char *initial_content_stripped = NULL, *buf = NULL, *s;
458 *logmsg = NULL;
460 if (stat(logmsg_path, &st) == -1)
461 return got_error_from_errno2("stat", logmsg_path);
463 if (spawn_editor(editor, logmsg_path) == -1)
464 return got_error_from_errno("failed spawning editor");
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno("stat");
469 if (require_modification &&
470 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 /*
475 * Set up a stripped version of the initial content without comments
476 * and blank lines. We need this in order to check if the message
477 * has in fact been edited.
478 */
479 initial_content_stripped = malloc(initial_content_len + 1);
480 if (initial_content_stripped == NULL)
481 return got_error_from_errno("malloc");
482 initial_content_stripped[0] = '\0';
484 buf = strdup(initial_content);
485 if (buf == NULL) {
486 err = got_error_from_errno("strdup");
487 goto done;
489 s = buf;
490 len = 0;
491 while ((line = strsep(&s, "\n")) != NULL) {
492 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
493 continue; /* remove comments and leading empty lines */
494 len = strlcat(initial_content_stripped, line,
495 initial_content_len + 1);
496 if (len >= initial_content_len + 1) {
497 err = got_error(GOT_ERR_NO_SPACE);
498 goto done;
501 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
502 initial_content_stripped[len - 1] = '\0';
503 len--;
506 logmsg_len = st2.st_size;
507 *logmsg = malloc(logmsg_len + 1);
508 if (*logmsg == NULL)
509 return got_error_from_errno("malloc");
510 (*logmsg)[0] = '\0';
512 fp = fopen(logmsg_path, "re");
513 if (fp == NULL) {
514 err = got_error_from_errno("fopen");
515 goto done;
518 len = 0;
519 while ((linelen = getline(&line, &linesize, fp)) != -1) {
520 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
521 continue; /* remove comments and leading empty lines */
522 len = strlcat(*logmsg, line, logmsg_len + 1);
523 if (len >= logmsg_len + 1) {
524 err = got_error(GOT_ERR_NO_SPACE);
525 goto done;
528 free(line);
529 if (ferror(fp)) {
530 err = got_ferror(fp, GOT_ERR_IO);
531 goto done;
533 while (len > 0 && (*logmsg)[len - 1] == '\n') {
534 (*logmsg)[len - 1] = '\0';
535 len--;
538 if (len == 0) {
539 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
540 "commit message cannot be empty, aborting");
541 goto done;
543 if (require_modification &&
544 strcmp(*logmsg, initial_content_stripped) == 0)
545 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
546 "no changes made to commit message, aborting");
547 done:
548 free(initial_content_stripped);
549 free(buf);
550 if (fp && fclose(fp) == EOF && err == NULL)
551 err = got_error_from_errno("fclose");
552 if (err) {
553 free(*logmsg);
554 *logmsg = NULL;
556 return err;
559 static const struct got_error *
560 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
561 const char *path_dir, const char *branch_name)
563 char *initial_content = NULL;
564 const struct got_error *err = NULL;
565 int initial_content_len;
566 int fd = -1;
568 initial_content_len = asprintf(&initial_content,
569 "\n# %s to be imported to branch %s\n", path_dir,
570 branch_name);
571 if (initial_content_len == -1)
572 return got_error_from_errno("asprintf");
574 err = got_opentemp_named_fd(logmsg_path, &fd,
575 GOT_TMPDIR_STR "/got-importmsg");
576 if (err)
577 goto done;
579 if (write(fd, initial_content, initial_content_len) == -1) {
580 err = got_error_from_errno2("write", *logmsg_path);
581 goto done;
584 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
585 initial_content_len, 1);
586 done:
587 if (fd != -1 && close(fd) == -1 && err == NULL)
588 err = got_error_from_errno2("close", *logmsg_path);
589 free(initial_content);
590 if (err) {
591 free(*logmsg_path);
592 *logmsg_path = NULL;
594 return err;
597 static const struct got_error *
598 import_progress(void *arg, const char *path)
600 printf("A %s\n", path);
601 return NULL;
604 static int
605 valid_author(const char *author)
607 /*
608 * Really dumb email address check; we're only doing this to
609 * avoid git's object parser breaking on commits we create.
610 */
611 while (*author && *author != '<')
612 author++;
613 if (*author != '<')
614 return 0;
615 while (*author && *author != '@')
616 author++;
617 if (*author != '@')
618 return 0;
619 while (*author && *author != '>')
620 author++;
621 return *author == '>';
624 static const struct got_error *
625 get_author(char **author, struct got_repository *repo,
626 struct got_worktree *worktree)
628 const struct got_error *err = NULL;
629 const char *got_author = NULL, *name, *email;
630 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
632 *author = NULL;
634 if (worktree)
635 worktree_conf = got_worktree_get_gotconfig(worktree);
636 repo_conf = got_repo_get_gotconfig(repo);
638 /*
639 * Priority of potential author information sources, from most
640 * significant to least significant:
641 * 1) work tree's .got/got.conf file
642 * 2) repository's got.conf file
643 * 3) repository's git config file
644 * 4) environment variables
645 * 5) global git config files (in user's home directory or /etc)
646 */
648 if (worktree_conf)
649 got_author = got_gotconfig_get_author(worktree_conf);
650 if (got_author == NULL)
651 got_author = got_gotconfig_get_author(repo_conf);
652 if (got_author == NULL) {
653 name = got_repo_get_gitconfig_author_name(repo);
654 email = got_repo_get_gitconfig_author_email(repo);
655 if (name && email) {
656 if (asprintf(author, "%s <%s>", name, email) == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
661 got_author = getenv("GOT_AUTHOR");
662 if (got_author == NULL) {
663 name = got_repo_get_global_gitconfig_author_name(repo);
664 email = got_repo_get_global_gitconfig_author_email(
665 repo);
666 if (name && email) {
667 if (asprintf(author, "%s <%s>", name, email)
668 == -1)
669 return got_error_from_errno("asprintf");
670 return NULL;
672 /* TODO: Look up user in password database? */
673 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
677 *author = strdup(got_author);
678 if (*author == NULL)
679 return got_error_from_errno("strdup");
681 if (!valid_author(*author)) {
682 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
683 free(*author);
684 *author = NULL;
686 return err;
689 static const struct got_error *
690 get_gitconfig_path(char **gitconfig_path)
692 const char *homedir = getenv("HOME");
694 *gitconfig_path = NULL;
695 if (homedir) {
696 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
697 return got_error_from_errno("asprintf");
700 return NULL;
703 static const struct got_error *
704 cmd_import(int argc, char *argv[])
706 const struct got_error *error = NULL;
707 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
708 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
709 const char *branch_name = "main";
710 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
711 struct got_repository *repo = NULL;
712 struct got_reference *branch_ref = NULL, *head_ref = NULL;
713 struct got_object_id *new_commit_id = NULL;
714 int ch;
715 struct got_pathlist_head ignores;
716 struct got_pathlist_entry *pe;
717 int preserve_logmsg = 0;
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;
912 pack_fds = NULL;
914 if (preserve_logmsg) {
915 fprintf(stderr, "%s: log message preserved in %s\n",
916 getprogname(), logmsg_path);
917 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
918 error = got_error_from_errno2("unlink", logmsg_path);
919 free(logmsg);
920 free(logmsg_path);
921 free(repo_path);
922 free(editor);
923 free(refname);
924 free(new_commit_id);
925 free(id_str);
926 free(author);
927 free(gitconfig_path);
928 if (branch_ref)
929 got_ref_close(branch_ref);
930 if (head_ref)
931 got_ref_close(head_ref);
932 return error;
935 __dead static void
936 usage_clone(void)
938 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
939 "[-R reference] repository-url [directory]\n", getprogname());
940 exit(1);
943 struct got_fetch_progress_arg {
944 char last_scaled_size[FMT_SCALED_STRSIZE];
945 int last_p_indexed;
946 int last_p_resolved;
947 int verbosity;
949 struct got_repository *repo;
951 int create_configs;
952 int configs_created;
953 struct {
954 struct got_pathlist_head *symrefs;
955 struct got_pathlist_head *wanted_branches;
956 struct got_pathlist_head *wanted_refs;
957 const char *proto;
958 const char *host;
959 const char *port;
960 const char *remote_repo_path;
961 const char *git_url;
962 int fetch_all_branches;
963 int mirror_references;
964 } config_info;
965 };
967 /* XXX forward declaration */
968 static const struct got_error *
969 create_config_files(const char *proto, const char *host, const char *port,
970 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
971 int mirror_references, struct got_pathlist_head *symrefs,
972 struct got_pathlist_head *wanted_branches,
973 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
975 static const struct got_error *
976 fetch_progress(void *arg, const char *message, off_t packfile_size,
977 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
979 const struct got_error *err = NULL;
980 struct got_fetch_progress_arg *a = arg;
981 char scaled_size[FMT_SCALED_STRSIZE];
982 int p_indexed, p_resolved;
983 int print_size = 0, print_indexed = 0, print_resolved = 0;
985 /*
986 * In order to allow a failed clone to be resumed with 'got fetch'
987 * we try to create configuration files as soon as possible.
988 * Once the server has sent information about its default branch
989 * we have all required information.
990 */
991 if (a->create_configs && !a->configs_created &&
992 !TAILQ_EMPTY(a->config_info.symrefs)) {
993 err = create_config_files(a->config_info.proto,
994 a->config_info.host, a->config_info.port,
995 a->config_info.remote_repo_path,
996 a->config_info.git_url,
997 a->config_info.fetch_all_branches,
998 a->config_info.mirror_references,
999 a->config_info.symrefs,
1000 a->config_info.wanted_branches,
1001 a->config_info.wanted_refs, a->repo);
1002 if (err)
1003 return err;
1004 a->configs_created = 1;
1007 if (a->verbosity < 0)
1008 return NULL;
1010 if (message && message[0] != '\0') {
1011 printf("\rserver: %s", message);
1012 fflush(stdout);
1013 return NULL;
1016 if (packfile_size > 0 || nobj_indexed > 0) {
1017 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1018 (a->last_scaled_size[0] == '\0' ||
1019 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1020 print_size = 1;
1021 if (strlcpy(a->last_scaled_size, scaled_size,
1022 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1023 return got_error(GOT_ERR_NO_SPACE);
1025 if (nobj_indexed > 0) {
1026 p_indexed = (nobj_indexed * 100) / nobj_total;
1027 if (p_indexed != a->last_p_indexed) {
1028 a->last_p_indexed = p_indexed;
1029 print_indexed = 1;
1030 print_size = 1;
1033 if (nobj_resolved > 0) {
1034 p_resolved = (nobj_resolved * 100) /
1035 (nobj_total - nobj_loose);
1036 if (p_resolved != a->last_p_resolved) {
1037 a->last_p_resolved = p_resolved;
1038 print_resolved = 1;
1039 print_indexed = 1;
1040 print_size = 1;
1045 if (print_size || print_indexed || print_resolved)
1046 printf("\r");
1047 if (print_size)
1048 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1049 if (print_indexed)
1050 printf("; indexing %d%%", p_indexed);
1051 if (print_resolved)
1052 printf("; resolving deltas %d%%", p_resolved);
1053 if (print_size || print_indexed || print_resolved)
1054 fflush(stdout);
1056 return NULL;
1059 static const struct got_error *
1060 create_symref(const char *refname, struct got_reference *target_ref,
1061 int verbosity, struct got_repository *repo)
1063 const struct got_error *err;
1064 struct got_reference *head_symref;
1066 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1067 if (err)
1068 return err;
1070 err = got_ref_write(head_symref, repo);
1071 if (err == NULL && verbosity > 0) {
1072 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1073 got_ref_get_name(target_ref));
1075 got_ref_close(head_symref);
1076 return err;
1079 static const struct got_error *
1080 list_remote_refs(struct got_pathlist_head *symrefs,
1081 struct got_pathlist_head *refs)
1083 const struct got_error *err;
1084 struct got_pathlist_entry *pe;
1086 TAILQ_FOREACH(pe, symrefs, entry) {
1087 const char *refname = pe->path;
1088 const char *targetref = pe->data;
1090 printf("%s: %s\n", refname, targetref);
1093 TAILQ_FOREACH(pe, refs, entry) {
1094 const char *refname = pe->path;
1095 struct got_object_id *id = pe->data;
1096 char *id_str;
1098 err = got_object_id_str(&id_str, id);
1099 if (err)
1100 return err;
1101 printf("%s: %s\n", refname, id_str);
1102 free(id_str);
1105 return NULL;
1108 static const struct got_error *
1109 create_ref(const char *refname, struct got_object_id *id,
1110 int verbosity, struct got_repository *repo)
1112 const struct got_error *err = NULL;
1113 struct got_reference *ref;
1114 char *id_str;
1116 err = got_object_id_str(&id_str, id);
1117 if (err)
1118 return err;
1120 err = got_ref_alloc(&ref, refname, id);
1121 if (err)
1122 goto done;
1124 err = got_ref_write(ref, repo);
1125 got_ref_close(ref);
1127 if (err == NULL && verbosity >= 0)
1128 printf("Created reference %s: %s\n", refname, id_str);
1129 done:
1130 free(id_str);
1131 return err;
1134 static int
1135 match_wanted_ref(const char *refname, const char *wanted_ref)
1137 if (strncmp(refname, "refs/", 5) != 0)
1138 return 0;
1139 refname += 5;
1142 * Prevent fetching of references that won't make any
1143 * sense outside of the remote repository's context.
1145 if (strncmp(refname, "got/", 4) == 0)
1146 return 0;
1147 if (strncmp(refname, "remotes/", 8) == 0)
1148 return 0;
1150 if (strncmp(wanted_ref, "refs/", 5) == 0)
1151 wanted_ref += 5;
1153 /* Allow prefix match. */
1154 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1155 return 1;
1157 /* Allow exact match. */
1158 return (strcmp(refname, wanted_ref) == 0);
1161 static int
1162 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1164 struct got_pathlist_entry *pe;
1166 TAILQ_FOREACH(pe, wanted_refs, entry) {
1167 if (match_wanted_ref(refname, pe->path))
1168 return 1;
1171 return 0;
1174 static const struct got_error *
1175 create_wanted_ref(const char *refname, struct got_object_id *id,
1176 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1178 const struct got_error *err;
1179 char *remote_refname;
1181 if (strncmp("refs/", refname, 5) == 0)
1182 refname += 5;
1184 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1185 remote_repo_name, refname) == -1)
1186 return got_error_from_errno("asprintf");
1188 err = create_ref(remote_refname, id, verbosity, repo);
1189 free(remote_refname);
1190 return err;
1193 static const struct got_error *
1194 create_gotconfig(const char *proto, const char *host, const char *port,
1195 const char *remote_repo_path, const char *default_branch,
1196 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1197 struct got_pathlist_head *wanted_refs, int mirror_references,
1198 struct got_repository *repo)
1200 const struct got_error *err = NULL;
1201 char *gotconfig_path = NULL;
1202 char *gotconfig = NULL;
1203 FILE *gotconfig_file = NULL;
1204 const char *branchname = NULL;
1205 char *branches = NULL, *refs = NULL;
1206 ssize_t n;
1208 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1209 struct got_pathlist_entry *pe;
1210 TAILQ_FOREACH(pe, wanted_branches, entry) {
1211 char *s;
1212 branchname = pe->path;
1213 if (strncmp(branchname, "refs/heads/", 11) == 0)
1214 branchname += 11;
1215 if (asprintf(&s, "%s\"%s\" ",
1216 branches ? branches : "", branchname) == -1) {
1217 err = got_error_from_errno("asprintf");
1218 goto done;
1220 free(branches);
1221 branches = s;
1223 } else if (!fetch_all_branches && default_branch) {
1224 branchname = default_branch;
1225 if (strncmp(branchname, "refs/heads/", 11) == 0)
1226 branchname += 11;
1227 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1228 err = got_error_from_errno("asprintf");
1229 goto done;
1232 if (!TAILQ_EMPTY(wanted_refs)) {
1233 struct got_pathlist_entry *pe;
1234 TAILQ_FOREACH(pe, wanted_refs, entry) {
1235 char *s;
1236 const char *refname = pe->path;
1237 if (strncmp(refname, "refs/", 5) == 0)
1238 branchname += 5;
1239 if (asprintf(&s, "%s\"%s\" ",
1240 refs ? refs : "", refname) == -1) {
1241 err = got_error_from_errno("asprintf");
1242 goto done;
1244 free(refs);
1245 refs = s;
1249 /* Create got.conf(5). */
1250 gotconfig_path = got_repo_get_path_gotconfig(repo);
1251 if (gotconfig_path == NULL) {
1252 err = got_error_from_errno("got_repo_get_path_gotconfig");
1253 goto done;
1255 gotconfig_file = fopen(gotconfig_path, "ae");
1256 if (gotconfig_file == NULL) {
1257 err = got_error_from_errno2("fopen", gotconfig_path);
1258 goto done;
1260 if (asprintf(&gotconfig,
1261 "remote \"%s\" {\n"
1262 "\tserver %s\n"
1263 "\tprotocol %s\n"
1264 "%s%s%s"
1265 "\trepository \"%s\"\n"
1266 "%s%s%s"
1267 "%s%s%s"
1268 "%s"
1269 "%s"
1270 "}\n",
1271 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1272 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1273 remote_repo_path, branches ? "\tbranch { " : "",
1274 branches ? branches : "", branches ? "}\n" : "",
1275 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1276 mirror_references ? "\tmirror-references yes\n" : "",
1277 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1278 err = got_error_from_errno("asprintf");
1279 goto done;
1281 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1282 if (n != strlen(gotconfig)) {
1283 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1284 goto done;
1287 done:
1288 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1289 err = got_error_from_errno2("fclose", gotconfig_path);
1290 free(gotconfig_path);
1291 free(branches);
1292 return err;
1295 static const struct got_error *
1296 create_gitconfig(const char *git_url, const char *default_branch,
1297 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1298 struct got_pathlist_head *wanted_refs, int mirror_references,
1299 struct got_repository *repo)
1301 const struct got_error *err = NULL;
1302 char *gitconfig_path = NULL;
1303 char *gitconfig = NULL;
1304 FILE *gitconfig_file = NULL;
1305 char *branches = NULL, *refs = NULL;
1306 const char *branchname;
1307 ssize_t n;
1309 /* Create a config file Git can understand. */
1310 gitconfig_path = got_repo_get_path_gitconfig(repo);
1311 if (gitconfig_path == NULL) {
1312 err = got_error_from_errno("got_repo_get_path_gitconfig");
1313 goto done;
1315 gitconfig_file = fopen(gitconfig_path, "ae");
1316 if (gitconfig_file == NULL) {
1317 err = got_error_from_errno2("fopen", gitconfig_path);
1318 goto done;
1320 if (fetch_all_branches) {
1321 if (mirror_references) {
1322 if (asprintf(&branches,
1323 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1324 err = got_error_from_errno("asprintf");
1325 goto done;
1327 } else if (asprintf(&branches,
1328 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1329 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1330 err = got_error_from_errno("asprintf");
1331 goto done;
1333 } else if (!TAILQ_EMPTY(wanted_branches)) {
1334 struct got_pathlist_entry *pe;
1335 TAILQ_FOREACH(pe, wanted_branches, entry) {
1336 char *s;
1337 branchname = pe->path;
1338 if (strncmp(branchname, "refs/heads/", 11) == 0)
1339 branchname += 11;
1340 if (mirror_references) {
1341 if (asprintf(&s,
1342 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1343 branches ? branches : "",
1344 branchname, branchname) == -1) {
1345 err = got_error_from_errno("asprintf");
1346 goto done;
1348 } else if (asprintf(&s,
1349 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1350 branches ? branches : "",
1351 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1352 branchname) == -1) {
1353 err = got_error_from_errno("asprintf");
1354 goto done;
1356 free(branches);
1357 branches = s;
1359 } else {
1361 * If the server specified a default branch, use just that one.
1362 * Otherwise fall back to fetching all branches on next fetch.
1364 if (default_branch) {
1365 branchname = default_branch;
1366 if (strncmp(branchname, "refs/heads/", 11) == 0)
1367 branchname += 11;
1368 } else
1369 branchname = "*"; /* fall back to all branches */
1370 if (mirror_references) {
1371 if (asprintf(&branches,
1372 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1373 branchname, branchname) == -1) {
1374 err = got_error_from_errno("asprintf");
1375 goto done;
1377 } else if (asprintf(&branches,
1378 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1379 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1380 branchname) == -1) {
1381 err = got_error_from_errno("asprintf");
1382 goto done;
1385 if (!TAILQ_EMPTY(wanted_refs)) {
1386 struct got_pathlist_entry *pe;
1387 TAILQ_FOREACH(pe, wanted_refs, entry) {
1388 char *s;
1389 const char *refname = pe->path;
1390 if (strncmp(refname, "refs/", 5) == 0)
1391 refname += 5;
1392 if (mirror_references) {
1393 if (asprintf(&s,
1394 "%s\tfetch = refs/%s:refs/%s\n",
1395 refs ? refs : "", refname, refname) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (asprintf(&s,
1400 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1401 refs ? refs : "",
1402 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1403 refname) == -1) {
1404 err = got_error_from_errno("asprintf");
1405 goto done;
1407 free(refs);
1408 refs = s;
1412 if (asprintf(&gitconfig,
1413 "[remote \"%s\"]\n"
1414 "\turl = %s\n"
1415 "%s"
1416 "%s"
1417 "\tfetch = refs/tags/*:refs/tags/*\n",
1418 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1419 refs ? refs : "") == -1) {
1420 err = got_error_from_errno("asprintf");
1421 goto done;
1423 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1424 if (n != strlen(gitconfig)) {
1425 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1426 goto done;
1428 done:
1429 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1430 err = got_error_from_errno2("fclose", gitconfig_path);
1431 free(gitconfig_path);
1432 free(branches);
1433 return err;
1436 static const struct got_error *
1437 create_config_files(const char *proto, const char *host, const char *port,
1438 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1439 int mirror_references, struct got_pathlist_head *symrefs,
1440 struct got_pathlist_head *wanted_branches,
1441 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1443 const struct got_error *err = NULL;
1444 const char *default_branch = NULL;
1445 struct got_pathlist_entry *pe;
1448 * If we asked for a set of wanted branches then use the first
1449 * one of those.
1451 if (!TAILQ_EMPTY(wanted_branches)) {
1452 pe = TAILQ_FIRST(wanted_branches);
1453 default_branch = pe->path;
1454 } else {
1455 /* First HEAD ref listed by server is the default branch. */
1456 TAILQ_FOREACH(pe, symrefs, entry) {
1457 const char *refname = pe->path;
1458 const char *target = pe->data;
1460 if (strcmp(refname, GOT_REF_HEAD) != 0)
1461 continue;
1463 default_branch = target;
1464 break;
1468 /* Create got.conf(5). */
1469 err = create_gotconfig(proto, host, port, remote_repo_path,
1470 default_branch, fetch_all_branches, wanted_branches,
1471 wanted_refs, mirror_references, repo);
1472 if (err)
1473 return err;
1475 /* Create a config file Git can understand. */
1476 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1477 wanted_branches, wanted_refs, mirror_references, repo);
1480 static const struct got_error *
1481 cmd_clone(int argc, char *argv[])
1483 const struct got_error *error = NULL;
1484 const char *uri, *dirname;
1485 char *proto, *host, *port, *repo_name, *server_path;
1486 char *default_destdir = NULL, *id_str = NULL;
1487 const char *repo_path;
1488 struct got_repository *repo = NULL;
1489 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1490 struct got_pathlist_entry *pe;
1491 struct got_object_id *pack_hash = NULL;
1492 int ch, fetchfd = -1, fetchstatus;
1493 pid_t fetchpid = -1;
1494 struct got_fetch_progress_arg fpa;
1495 char *git_url = NULL;
1496 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1497 int list_refs_only = 0;
1498 int *pack_fds = NULL;
1500 TAILQ_INIT(&refs);
1501 TAILQ_INIT(&symrefs);
1502 TAILQ_INIT(&wanted_branches);
1503 TAILQ_INIT(&wanted_refs);
1505 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1506 switch (ch) {
1507 case 'a':
1508 fetch_all_branches = 1;
1509 break;
1510 case 'b':
1511 error = got_pathlist_append(&wanted_branches,
1512 optarg, NULL);
1513 if (error)
1514 return error;
1515 break;
1516 case 'l':
1517 list_refs_only = 1;
1518 break;
1519 case 'm':
1520 mirror_references = 1;
1521 break;
1522 case 'v':
1523 if (verbosity < 0)
1524 verbosity = 0;
1525 else if (verbosity < 3)
1526 verbosity++;
1527 break;
1528 case 'q':
1529 verbosity = -1;
1530 break;
1531 case 'R':
1532 error = got_pathlist_append(&wanted_refs,
1533 optarg, NULL);
1534 if (error)
1535 return error;
1536 break;
1537 default:
1538 usage_clone();
1539 break;
1542 argc -= optind;
1543 argv += optind;
1545 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1546 option_conflict('a', 'b');
1547 if (list_refs_only) {
1548 if (!TAILQ_EMPTY(&wanted_branches))
1549 option_conflict('l', 'b');
1550 if (fetch_all_branches)
1551 option_conflict('l', 'a');
1552 if (mirror_references)
1553 option_conflict('l', 'm');
1554 if (!TAILQ_EMPTY(&wanted_refs))
1555 option_conflict('l', 'R');
1558 uri = argv[0];
1560 if (argc == 1)
1561 dirname = NULL;
1562 else if (argc == 2)
1563 dirname = argv[1];
1564 else
1565 usage_clone();
1567 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1568 &repo_name, uri);
1569 if (error)
1570 goto done;
1572 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1573 host, port ? ":" : "", port ? port : "",
1574 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1575 error = got_error_from_errno("asprintf");
1576 goto done;
1579 if (strcmp(proto, "git") == 0) {
1580 #ifndef PROFILE
1581 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1582 "sendfd dns inet unveil", NULL) == -1)
1583 err(1, "pledge");
1584 #endif
1585 } else if (strcmp(proto, "git+ssh") == 0 ||
1586 strcmp(proto, "ssh") == 0) {
1587 #ifndef PROFILE
1588 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1589 "sendfd unveil", NULL) == -1)
1590 err(1, "pledge");
1591 #endif
1592 } else if (strcmp(proto, "http") == 0 ||
1593 strcmp(proto, "git+http") == 0) {
1594 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1595 goto done;
1596 } else {
1597 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1598 goto done;
1600 if (dirname == NULL) {
1601 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1602 error = got_error_from_errno("asprintf");
1603 goto done;
1605 repo_path = default_destdir;
1606 } else
1607 repo_path = dirname;
1609 if (!list_refs_only) {
1610 error = got_path_mkdir(repo_path);
1611 if (error &&
1612 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1613 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1614 goto done;
1615 if (!got_path_dir_is_empty(repo_path)) {
1616 error = got_error_path(repo_path,
1617 GOT_ERR_DIR_NOT_EMPTY);
1618 goto done;
1622 error = got_dial_apply_unveil(proto);
1623 if (error)
1624 goto done;
1626 error = apply_unveil(repo_path, 0, NULL);
1627 if (error)
1628 goto done;
1630 if (verbosity >= 0)
1631 printf("Connecting to %s%s%s\n", host,
1632 port ? ":" : "", port ? port : "");
1634 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1635 server_path, verbosity);
1636 if (error)
1637 goto done;
1639 if (!list_refs_only) {
1640 error = got_repo_init(repo_path);
1641 if (error)
1642 goto done;
1643 error = got_repo_pack_fds_open(&pack_fds);
1644 if (error != NULL)
1645 goto done;
1646 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1647 if (error)
1648 goto done;
1651 fpa.last_scaled_size[0] = '\0';
1652 fpa.last_p_indexed = -1;
1653 fpa.last_p_resolved = -1;
1654 fpa.verbosity = verbosity;
1655 fpa.create_configs = 1;
1656 fpa.configs_created = 0;
1657 fpa.repo = repo;
1658 fpa.config_info.symrefs = &symrefs;
1659 fpa.config_info.wanted_branches = &wanted_branches;
1660 fpa.config_info.wanted_refs = &wanted_refs;
1661 fpa.config_info.proto = proto;
1662 fpa.config_info.host = host;
1663 fpa.config_info.port = port;
1664 fpa.config_info.remote_repo_path = server_path;
1665 fpa.config_info.git_url = git_url;
1666 fpa.config_info.fetch_all_branches = fetch_all_branches;
1667 fpa.config_info.mirror_references = mirror_references;
1668 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1669 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1670 fetch_all_branches, &wanted_branches, &wanted_refs,
1671 list_refs_only, verbosity, fetchfd, repo,
1672 fetch_progress, &fpa);
1673 if (error)
1674 goto done;
1676 if (list_refs_only) {
1677 error = list_remote_refs(&symrefs, &refs);
1678 goto done;
1681 if (pack_hash == NULL) {
1682 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1683 "server sent an empty pack file");
1684 goto done;
1686 error = got_object_id_str(&id_str, pack_hash);
1687 if (error)
1688 goto done;
1689 if (verbosity >= 0)
1690 printf("\nFetched %s.pack\n", id_str);
1691 free(id_str);
1693 /* Set up references provided with the pack file. */
1694 TAILQ_FOREACH(pe, &refs, entry) {
1695 const char *refname = pe->path;
1696 struct got_object_id *id = pe->data;
1697 char *remote_refname;
1699 if (is_wanted_ref(&wanted_refs, refname) &&
1700 !mirror_references) {
1701 error = create_wanted_ref(refname, id,
1702 GOT_FETCH_DEFAULT_REMOTE_NAME,
1703 verbosity - 1, repo);
1704 if (error)
1705 goto done;
1706 continue;
1709 error = create_ref(refname, id, verbosity - 1, repo);
1710 if (error)
1711 goto done;
1713 if (mirror_references)
1714 continue;
1716 if (strncmp("refs/heads/", refname, 11) != 0)
1717 continue;
1719 if (asprintf(&remote_refname,
1720 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1721 refname + 11) == -1) {
1722 error = got_error_from_errno("asprintf");
1723 goto done;
1725 error = create_ref(remote_refname, id, verbosity - 1, repo);
1726 free(remote_refname);
1727 if (error)
1728 goto done;
1731 /* Set the HEAD reference if the server provided one. */
1732 TAILQ_FOREACH(pe, &symrefs, entry) {
1733 struct got_reference *target_ref;
1734 const char *refname = pe->path;
1735 const char *target = pe->data;
1736 char *remote_refname = NULL, *remote_target = NULL;
1738 if (strcmp(refname, GOT_REF_HEAD) != 0)
1739 continue;
1741 error = got_ref_open(&target_ref, repo, target, 0);
1742 if (error) {
1743 if (error->code == GOT_ERR_NOT_REF) {
1744 error = NULL;
1745 continue;
1747 goto done;
1750 error = create_symref(refname, target_ref, verbosity, repo);
1751 got_ref_close(target_ref);
1752 if (error)
1753 goto done;
1755 if (mirror_references)
1756 continue;
1758 if (strncmp("refs/heads/", target, 11) != 0)
1759 continue;
1761 if (asprintf(&remote_refname,
1762 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1763 refname) == -1) {
1764 error = got_error_from_errno("asprintf");
1765 goto done;
1767 if (asprintf(&remote_target,
1768 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 target + 11) == -1) {
1770 error = got_error_from_errno("asprintf");
1771 free(remote_refname);
1772 goto done;
1774 error = got_ref_open(&target_ref, repo, remote_target, 0);
1775 if (error) {
1776 free(remote_refname);
1777 free(remote_target);
1778 if (error->code == GOT_ERR_NOT_REF) {
1779 error = NULL;
1780 continue;
1782 goto done;
1784 error = create_symref(remote_refname, target_ref,
1785 verbosity - 1, repo);
1786 free(remote_refname);
1787 free(remote_target);
1788 got_ref_close(target_ref);
1789 if (error)
1790 goto done;
1792 if (pe == NULL) {
1794 * We failed to set the HEAD reference. If we asked for
1795 * a set of wanted branches use the first of one of those
1796 * which could be fetched instead.
1798 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1799 const char *target = pe->path;
1800 struct got_reference *target_ref;
1802 error = got_ref_open(&target_ref, repo, target, 0);
1803 if (error) {
1804 if (error->code == GOT_ERR_NOT_REF) {
1805 error = NULL;
1806 continue;
1808 goto done;
1811 error = create_symref(GOT_REF_HEAD, target_ref,
1812 verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1816 break;
1820 if (verbosity >= 0)
1821 printf("Created %s repository '%s'\n",
1822 mirror_references ? "mirrored" : "cloned", repo_path);
1823 done:
1824 if (pack_fds) {
1825 const struct got_error *pack_err =
1826 got_repo_pack_fds_close(pack_fds);
1827 if (error == NULL)
1828 error = pack_err;
1829 pack_fds = NULL;
1831 if (fetchpid > 0) {
1832 if (kill(fetchpid, SIGTERM) == -1)
1833 error = got_error_from_errno("kill");
1834 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1835 error = got_error_from_errno("waitpid");
1837 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1838 error = got_error_from_errno("close");
1839 if (repo) {
1840 const struct got_error *close_err = got_repo_close(repo);
1841 if (error == NULL)
1842 error = close_err;
1844 TAILQ_FOREACH(pe, &refs, entry) {
1845 free((void *)pe->path);
1846 free(pe->data);
1848 got_pathlist_free(&refs);
1849 TAILQ_FOREACH(pe, &symrefs, entry) {
1850 free((void *)pe->path);
1851 free(pe->data);
1853 got_pathlist_free(&symrefs);
1854 got_pathlist_free(&wanted_branches);
1855 got_pathlist_free(&wanted_refs);
1856 free(pack_hash);
1857 free(proto);
1858 free(host);
1859 free(port);
1860 free(server_path);
1861 free(repo_name);
1862 free(default_destdir);
1863 free(git_url);
1864 return error;
1867 static const struct got_error *
1868 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1869 int replace_tags, int verbosity, struct got_repository *repo)
1871 const struct got_error *err = NULL;
1872 char *new_id_str = NULL;
1873 struct got_object_id *old_id = NULL;
1875 err = got_object_id_str(&new_id_str, new_id);
1876 if (err)
1877 goto done;
1879 if (!replace_tags &&
1880 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1881 err = got_ref_resolve(&old_id, repo, ref);
1882 if (err)
1883 goto done;
1884 if (got_object_id_cmp(old_id, new_id) == 0)
1885 goto done;
1886 if (verbosity >= 0) {
1887 printf("Rejecting update of existing tag %s: %s\n",
1888 got_ref_get_name(ref), new_id_str);
1890 goto done;
1893 if (got_ref_is_symbolic(ref)) {
1894 if (verbosity >= 0) {
1895 printf("Replacing reference %s: %s\n",
1896 got_ref_get_name(ref),
1897 got_ref_get_symref_target(ref));
1899 err = got_ref_change_symref_to_ref(ref, new_id);
1900 if (err)
1901 goto done;
1902 err = got_ref_write(ref, repo);
1903 if (err)
1904 goto done;
1905 } else {
1906 err = got_ref_resolve(&old_id, repo, ref);
1907 if (err)
1908 goto done;
1909 if (got_object_id_cmp(old_id, new_id) == 0)
1910 goto done;
1912 err = got_ref_change_ref(ref, new_id);
1913 if (err)
1914 goto done;
1915 err = got_ref_write(ref, repo);
1916 if (err)
1917 goto done;
1920 if (verbosity >= 0)
1921 printf("Updated %s: %s\n", got_ref_get_name(ref),
1922 new_id_str);
1923 done:
1924 free(old_id);
1925 free(new_id_str);
1926 return err;
1929 static const struct got_error *
1930 update_symref(const char *refname, struct got_reference *target_ref,
1931 int verbosity, struct got_repository *repo)
1933 const struct got_error *err = NULL, *unlock_err;
1934 struct got_reference *symref;
1935 int symref_is_locked = 0;
1937 err = got_ref_open(&symref, repo, refname, 1);
1938 if (err) {
1939 if (err->code != GOT_ERR_NOT_REF)
1940 return err;
1941 err = got_ref_alloc_symref(&symref, refname, target_ref);
1942 if (err)
1943 goto done;
1945 err = got_ref_write(symref, repo);
1946 if (err)
1947 goto done;
1949 if (verbosity >= 0)
1950 printf("Created reference %s: %s\n",
1951 got_ref_get_name(symref),
1952 got_ref_get_symref_target(symref));
1953 } else {
1954 symref_is_locked = 1;
1956 if (strcmp(got_ref_get_symref_target(symref),
1957 got_ref_get_name(target_ref)) == 0)
1958 goto done;
1960 err = got_ref_change_symref(symref,
1961 got_ref_get_name(target_ref));
1962 if (err)
1963 goto done;
1965 err = got_ref_write(symref, repo);
1966 if (err)
1967 goto done;
1969 if (verbosity >= 0)
1970 printf("Updated %s: %s\n", got_ref_get_name(symref),
1971 got_ref_get_symref_target(symref));
1974 done:
1975 if (symref_is_locked) {
1976 unlock_err = got_ref_unlock(symref);
1977 if (unlock_err && err == NULL)
1978 err = unlock_err;
1980 got_ref_close(symref);
1981 return err;
1984 __dead static void
1985 usage_fetch(void)
1987 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1988 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1989 "[remote-repository-name]\n",
1990 getprogname());
1991 exit(1);
1994 static const struct got_error *
1995 delete_missing_ref(struct got_reference *ref,
1996 int verbosity, struct got_repository *repo)
1998 const struct got_error *err = NULL;
1999 struct got_object_id *id = NULL;
2000 char *id_str = NULL;
2002 if (got_ref_is_symbolic(ref)) {
2003 err = got_ref_delete(ref, repo);
2004 if (err)
2005 return err;
2006 if (verbosity >= 0) {
2007 printf("Deleted %s: %s\n",
2008 got_ref_get_name(ref),
2009 got_ref_get_symref_target(ref));
2011 } else {
2012 err = got_ref_resolve(&id, repo, ref);
2013 if (err)
2014 return err;
2015 err = got_object_id_str(&id_str, id);
2016 if (err)
2017 goto done;
2019 err = got_ref_delete(ref, repo);
2020 if (err)
2021 goto done;
2022 if (verbosity >= 0) {
2023 printf("Deleted %s: %s\n",
2024 got_ref_get_name(ref), id_str);
2027 done:
2028 free(id);
2029 free(id_str);
2030 return NULL;
2033 static const struct got_error *
2034 delete_missing_refs(struct got_pathlist_head *their_refs,
2035 struct got_pathlist_head *their_symrefs,
2036 const struct got_remote_repo *remote,
2037 int verbosity, struct got_repository *repo)
2039 const struct got_error *err = NULL, *unlock_err;
2040 struct got_reflist_head my_refs;
2041 struct got_reflist_entry *re;
2042 struct got_pathlist_entry *pe;
2043 char *remote_namespace = NULL;
2044 char *local_refname = NULL;
2046 TAILQ_INIT(&my_refs);
2048 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2049 == -1)
2050 return got_error_from_errno("asprintf");
2052 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2053 if (err)
2054 goto done;
2056 TAILQ_FOREACH(re, &my_refs, entry) {
2057 const char *refname = got_ref_get_name(re->ref);
2058 const char *their_refname;
2060 if (remote->mirror_references) {
2061 their_refname = refname;
2062 } else {
2063 if (strncmp(refname, remote_namespace,
2064 strlen(remote_namespace)) == 0) {
2065 if (strcmp(refname + strlen(remote_namespace),
2066 GOT_REF_HEAD) == 0)
2067 continue;
2068 if (asprintf(&local_refname, "refs/heads/%s",
2069 refname + strlen(remote_namespace)) == -1) {
2070 err = got_error_from_errno("asprintf");
2071 goto done;
2073 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2074 continue;
2076 their_refname = local_refname;
2079 TAILQ_FOREACH(pe, their_refs, entry) {
2080 if (strcmp(their_refname, pe->path) == 0)
2081 break;
2083 if (pe != NULL)
2084 continue;
2086 TAILQ_FOREACH(pe, their_symrefs, entry) {
2087 if (strcmp(their_refname, pe->path) == 0)
2088 break;
2090 if (pe != NULL)
2091 continue;
2093 err = delete_missing_ref(re->ref, verbosity, repo);
2094 if (err)
2095 break;
2097 if (local_refname) {
2098 struct got_reference *ref;
2099 err = got_ref_open(&ref, repo, local_refname, 1);
2100 if (err) {
2101 if (err->code != GOT_ERR_NOT_REF)
2102 break;
2103 free(local_refname);
2104 local_refname = NULL;
2105 continue;
2107 err = delete_missing_ref(ref, verbosity, repo);
2108 if (err)
2109 break;
2110 unlock_err = got_ref_unlock(ref);
2111 got_ref_close(ref);
2112 if (unlock_err && err == NULL) {
2113 err = unlock_err;
2114 break;
2117 free(local_refname);
2118 local_refname = NULL;
2121 done:
2122 free(remote_namespace);
2123 free(local_refname);
2124 return err;
2127 static const struct got_error *
2128 update_wanted_ref(const char *refname, struct got_object_id *id,
2129 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2131 const struct got_error *err, *unlock_err;
2132 char *remote_refname;
2133 struct got_reference *ref;
2135 if (strncmp("refs/", refname, 5) == 0)
2136 refname += 5;
2138 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2139 remote_repo_name, refname) == -1)
2140 return got_error_from_errno("asprintf");
2142 err = got_ref_open(&ref, repo, remote_refname, 1);
2143 if (err) {
2144 if (err->code != GOT_ERR_NOT_REF)
2145 goto done;
2146 err = create_ref(remote_refname, id, verbosity, repo);
2147 } else {
2148 err = update_ref(ref, id, 0, verbosity, repo);
2149 unlock_err = got_ref_unlock(ref);
2150 if (unlock_err && err == NULL)
2151 err = unlock_err;
2152 got_ref_close(ref);
2154 done:
2155 free(remote_refname);
2156 return err;
2159 static const struct got_error *
2160 delete_ref(struct got_repository *repo, struct got_reference *ref)
2162 const struct got_error *err = NULL;
2163 struct got_object_id *id = NULL;
2164 char *id_str = NULL;
2165 const char *target;
2167 if (got_ref_is_symbolic(ref)) {
2168 target = got_ref_get_symref_target(ref);
2169 } else {
2170 err = got_ref_resolve(&id, repo, ref);
2171 if (err)
2172 goto done;
2173 err = got_object_id_str(&id_str, id);
2174 if (err)
2175 goto done;
2176 target = id_str;
2179 err = got_ref_delete(ref, repo);
2180 if (err)
2181 goto done;
2183 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2184 done:
2185 free(id);
2186 free(id_str);
2187 return err;
2190 static const struct got_error *
2191 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2193 const struct got_error *err = NULL;
2194 struct got_reflist_head refs;
2195 struct got_reflist_entry *re;
2196 char *prefix;
2198 TAILQ_INIT(&refs);
2200 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2201 err = got_error_from_errno("asprintf");
2202 goto done;
2204 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2205 if (err)
2206 goto done;
2208 TAILQ_FOREACH(re, &refs, entry)
2209 delete_ref(repo, re->ref);
2210 done:
2211 got_ref_list_free(&refs);
2212 return err;
2215 static const struct got_error *
2216 cmd_fetch(int argc, char *argv[])
2218 const struct got_error *error = NULL, *unlock_err;
2219 char *cwd = NULL, *repo_path = NULL;
2220 const char *remote_name;
2221 char *proto = NULL, *host = NULL, *port = NULL;
2222 char *repo_name = NULL, *server_path = NULL;
2223 const struct got_remote_repo *remotes, *remote = NULL;
2224 int nremotes;
2225 char *id_str = NULL;
2226 struct got_repository *repo = NULL;
2227 struct got_worktree *worktree = NULL;
2228 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2229 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2230 struct got_pathlist_entry *pe;
2231 struct got_object_id *pack_hash = NULL;
2232 int i, ch, fetchfd = -1, fetchstatus;
2233 pid_t fetchpid = -1;
2234 struct got_fetch_progress_arg fpa;
2235 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2236 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2237 int *pack_fds = NULL;
2239 TAILQ_INIT(&refs);
2240 TAILQ_INIT(&symrefs);
2241 TAILQ_INIT(&wanted_branches);
2242 TAILQ_INIT(&wanted_refs);
2244 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2245 switch (ch) {
2246 case 'a':
2247 fetch_all_branches = 1;
2248 break;
2249 case 'b':
2250 error = got_pathlist_append(&wanted_branches,
2251 optarg, NULL);
2252 if (error)
2253 return error;
2254 break;
2255 case 'd':
2256 delete_refs = 1;
2257 break;
2258 case 'l':
2259 list_refs_only = 1;
2260 break;
2261 case 'r':
2262 repo_path = realpath(optarg, NULL);
2263 if (repo_path == NULL)
2264 return got_error_from_errno2("realpath",
2265 optarg);
2266 got_path_strip_trailing_slashes(repo_path);
2267 break;
2268 case 't':
2269 replace_tags = 1;
2270 break;
2271 case 'v':
2272 if (verbosity < 0)
2273 verbosity = 0;
2274 else if (verbosity < 3)
2275 verbosity++;
2276 break;
2277 case 'q':
2278 verbosity = -1;
2279 break;
2280 case 'R':
2281 error = got_pathlist_append(&wanted_refs,
2282 optarg, NULL);
2283 if (error)
2284 return error;
2285 break;
2286 case 'X':
2287 delete_remote = 1;
2288 break;
2289 default:
2290 usage_fetch();
2291 break;
2294 argc -= optind;
2295 argv += optind;
2297 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2298 option_conflict('a', 'b');
2299 if (list_refs_only) {
2300 if (!TAILQ_EMPTY(&wanted_branches))
2301 option_conflict('l', 'b');
2302 if (fetch_all_branches)
2303 option_conflict('l', 'a');
2304 if (delete_refs)
2305 option_conflict('l', 'd');
2306 if (delete_remote)
2307 option_conflict('l', 'X');
2309 if (delete_remote) {
2310 if (fetch_all_branches)
2311 option_conflict('X', 'a');
2312 if (!TAILQ_EMPTY(&wanted_branches))
2313 option_conflict('X', 'b');
2314 if (delete_refs)
2315 option_conflict('X', 'd');
2316 if (replace_tags)
2317 option_conflict('X', 't');
2318 if (!TAILQ_EMPTY(&wanted_refs))
2319 option_conflict('X', 'R');
2322 if (argc == 0) {
2323 if (delete_remote)
2324 errx(1, "-X option requires a remote name");
2325 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2326 } else if (argc == 1)
2327 remote_name = argv[0];
2328 else
2329 usage_fetch();
2331 cwd = getcwd(NULL, 0);
2332 if (cwd == NULL) {
2333 error = got_error_from_errno("getcwd");
2334 goto done;
2337 error = got_repo_pack_fds_open(&pack_fds);
2338 if (error != NULL)
2339 goto done;
2341 if (repo_path == NULL) {
2342 error = got_worktree_open(&worktree, cwd);
2343 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2344 goto done;
2345 else
2346 error = NULL;
2347 if (worktree) {
2348 repo_path =
2349 strdup(got_worktree_get_repo_path(worktree));
2350 if (repo_path == NULL)
2351 error = got_error_from_errno("strdup");
2352 if (error)
2353 goto done;
2354 } else {
2355 repo_path = strdup(cwd);
2356 if (repo_path == NULL) {
2357 error = got_error_from_errno("strdup");
2358 goto done;
2363 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2364 if (error)
2365 goto done;
2367 if (delete_remote) {
2368 error = delete_refs_for_remote(repo, remote_name);
2369 goto done; /* nothing else to do */
2372 if (worktree) {
2373 worktree_conf = got_worktree_get_gotconfig(worktree);
2374 if (worktree_conf) {
2375 got_gotconfig_get_remotes(&nremotes, &remotes,
2376 worktree_conf);
2377 for (i = 0; i < nremotes; i++) {
2378 if (strcmp(remotes[i].name, remote_name) == 0) {
2379 remote = &remotes[i];
2380 break;
2385 if (remote == NULL) {
2386 repo_conf = got_repo_get_gotconfig(repo);
2387 if (repo_conf) {
2388 got_gotconfig_get_remotes(&nremotes, &remotes,
2389 repo_conf);
2390 for (i = 0; i < nremotes; i++) {
2391 if (strcmp(remotes[i].name, remote_name) == 0) {
2392 remote = &remotes[i];
2393 break;
2398 if (remote == NULL) {
2399 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2400 for (i = 0; i < nremotes; i++) {
2401 if (strcmp(remotes[i].name, remote_name) == 0) {
2402 remote = &remotes[i];
2403 break;
2407 if (remote == NULL) {
2408 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2409 goto done;
2412 if (TAILQ_EMPTY(&wanted_branches)) {
2413 if (!fetch_all_branches)
2414 fetch_all_branches = remote->fetch_all_branches;
2415 for (i = 0; i < remote->nfetch_branches; i++) {
2416 got_pathlist_append(&wanted_branches,
2417 remote->fetch_branches[i], NULL);
2420 if (TAILQ_EMPTY(&wanted_refs)) {
2421 for (i = 0; i < remote->nfetch_refs; i++) {
2422 got_pathlist_append(&wanted_refs,
2423 remote->fetch_refs[i], NULL);
2427 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2428 &repo_name, remote->fetch_url);
2429 if (error)
2430 goto done;
2432 if (strcmp(proto, "git") == 0) {
2433 #ifndef PROFILE
2434 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2435 "sendfd dns inet unveil", NULL) == -1)
2436 err(1, "pledge");
2437 #endif
2438 } else if (strcmp(proto, "git+ssh") == 0 ||
2439 strcmp(proto, "ssh") == 0) {
2440 #ifndef PROFILE
2441 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2442 "sendfd unveil", NULL) == -1)
2443 err(1, "pledge");
2444 #endif
2445 } else if (strcmp(proto, "http") == 0 ||
2446 strcmp(proto, "git+http") == 0) {
2447 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2448 goto done;
2449 } else {
2450 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2451 goto done;
2454 error = got_dial_apply_unveil(proto);
2455 if (error)
2456 goto done;
2458 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2459 if (error)
2460 goto done;
2462 if (verbosity >= 0)
2463 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2464 port ? ":" : "", port ? port : "");
2466 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2467 server_path, verbosity);
2468 if (error)
2469 goto done;
2471 fpa.last_scaled_size[0] = '\0';
2472 fpa.last_p_indexed = -1;
2473 fpa.last_p_resolved = -1;
2474 fpa.verbosity = verbosity;
2475 fpa.repo = repo;
2476 fpa.create_configs = 0;
2477 fpa.configs_created = 0;
2478 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2479 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2480 remote->mirror_references, fetch_all_branches, &wanted_branches,
2481 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2482 fetch_progress, &fpa);
2483 if (error)
2484 goto done;
2486 if (list_refs_only) {
2487 error = list_remote_refs(&symrefs, &refs);
2488 goto done;
2491 if (pack_hash == NULL) {
2492 if (verbosity >= 0)
2493 printf("Already up-to-date\n");
2494 } else if (verbosity >= 0) {
2495 error = got_object_id_str(&id_str, pack_hash);
2496 if (error)
2497 goto done;
2498 printf("\nFetched %s.pack\n", id_str);
2499 free(id_str);
2500 id_str = NULL;
2503 /* Update references provided with the pack file. */
2504 TAILQ_FOREACH(pe, &refs, entry) {
2505 const char *refname = pe->path;
2506 struct got_object_id *id = pe->data;
2507 struct got_reference *ref;
2508 char *remote_refname;
2510 if (is_wanted_ref(&wanted_refs, refname) &&
2511 !remote->mirror_references) {
2512 error = update_wanted_ref(refname, id,
2513 remote->name, verbosity, repo);
2514 if (error)
2515 goto done;
2516 continue;
2519 if (remote->mirror_references ||
2520 strncmp("refs/tags/", refname, 10) == 0) {
2521 error = got_ref_open(&ref, repo, refname, 1);
2522 if (error) {
2523 if (error->code != GOT_ERR_NOT_REF)
2524 goto done;
2525 error = create_ref(refname, id, verbosity,
2526 repo);
2527 if (error)
2528 goto done;
2529 } else {
2530 error = update_ref(ref, id, replace_tags,
2531 verbosity, repo);
2532 unlock_err = got_ref_unlock(ref);
2533 if (unlock_err && error == NULL)
2534 error = unlock_err;
2535 got_ref_close(ref);
2536 if (error)
2537 goto done;
2539 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2540 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2541 remote_name, refname + 11) == -1) {
2542 error = got_error_from_errno("asprintf");
2543 goto done;
2546 error = got_ref_open(&ref, repo, remote_refname, 1);
2547 if (error) {
2548 if (error->code != GOT_ERR_NOT_REF)
2549 goto done;
2550 error = create_ref(remote_refname, id,
2551 verbosity, repo);
2552 if (error)
2553 goto done;
2554 } else {
2555 error = update_ref(ref, id, replace_tags,
2556 verbosity, repo);
2557 unlock_err = got_ref_unlock(ref);
2558 if (unlock_err && error == NULL)
2559 error = unlock_err;
2560 got_ref_close(ref);
2561 if (error)
2562 goto done;
2565 /* Also create a local branch if none exists yet. */
2566 error = got_ref_open(&ref, repo, refname, 1);
2567 if (error) {
2568 if (error->code != GOT_ERR_NOT_REF)
2569 goto done;
2570 error = create_ref(refname, id, verbosity,
2571 repo);
2572 if (error)
2573 goto done;
2574 } else {
2575 unlock_err = got_ref_unlock(ref);
2576 if (unlock_err && error == NULL)
2577 error = unlock_err;
2578 got_ref_close(ref);
2582 if (delete_refs) {
2583 error = delete_missing_refs(&refs, &symrefs, remote,
2584 verbosity, repo);
2585 if (error)
2586 goto done;
2589 if (!remote->mirror_references) {
2590 /* Update remote HEAD reference if the server provided one. */
2591 TAILQ_FOREACH(pe, &symrefs, entry) {
2592 struct got_reference *target_ref;
2593 const char *refname = pe->path;
2594 const char *target = pe->data;
2595 char *remote_refname = NULL, *remote_target = NULL;
2597 if (strcmp(refname, GOT_REF_HEAD) != 0)
2598 continue;
2600 if (strncmp("refs/heads/", target, 11) != 0)
2601 continue;
2603 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2604 remote->name, refname) == -1) {
2605 error = got_error_from_errno("asprintf");
2606 goto done;
2608 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2609 remote->name, target + 11) == -1) {
2610 error = got_error_from_errno("asprintf");
2611 free(remote_refname);
2612 goto done;
2615 error = got_ref_open(&target_ref, repo, remote_target,
2616 0);
2617 if (error) {
2618 free(remote_refname);
2619 free(remote_target);
2620 if (error->code == GOT_ERR_NOT_REF) {
2621 error = NULL;
2622 continue;
2624 goto done;
2626 error = update_symref(remote_refname, target_ref,
2627 verbosity, repo);
2628 free(remote_refname);
2629 free(remote_target);
2630 got_ref_close(target_ref);
2631 if (error)
2632 goto done;
2635 done:
2636 if (fetchpid > 0) {
2637 if (kill(fetchpid, SIGTERM) == -1)
2638 error = got_error_from_errno("kill");
2639 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2640 error = got_error_from_errno("waitpid");
2642 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2643 error = got_error_from_errno("close");
2644 if (repo) {
2645 const struct got_error *close_err = got_repo_close(repo);
2646 if (error == NULL)
2647 error = close_err;
2649 if (worktree)
2650 got_worktree_close(worktree);
2651 if (pack_fds) {
2652 const struct got_error *pack_err =
2653 got_repo_pack_fds_close(pack_fds);
2654 if (error == NULL)
2655 error = pack_err;
2656 pack_fds = NULL;
2658 TAILQ_FOREACH(pe, &refs, entry) {
2659 free((void *)pe->path);
2660 free(pe->data);
2662 got_pathlist_free(&refs);
2663 TAILQ_FOREACH(pe, &symrefs, entry) {
2664 free((void *)pe->path);
2665 free(pe->data);
2667 got_pathlist_free(&symrefs);
2668 got_pathlist_free(&wanted_branches);
2669 got_pathlist_free(&wanted_refs);
2670 free(id_str);
2671 free(cwd);
2672 free(repo_path);
2673 free(pack_hash);
2674 free(proto);
2675 free(host);
2676 free(port);
2677 free(server_path);
2678 free(repo_name);
2679 return error;
2683 __dead static void
2684 usage_checkout(void)
2686 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2687 "[-p prefix] [-q] repository-path [worktree-path]\n",
2688 getprogname());
2689 exit(1);
2692 static void
2693 show_worktree_base_ref_warning(void)
2695 fprintf(stderr, "%s: warning: could not create a reference "
2696 "to the work tree's base commit; the commit could be "
2697 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2698 "repository writable and running 'got update' will prevent this\n",
2699 getprogname());
2702 struct got_checkout_progress_arg {
2703 const char *worktree_path;
2704 int had_base_commit_ref_error;
2705 int verbosity;
2708 static const struct got_error *
2709 checkout_progress(void *arg, unsigned char status, const char *path)
2711 struct got_checkout_progress_arg *a = arg;
2713 /* Base commit bump happens silently. */
2714 if (status == GOT_STATUS_BUMP_BASE)
2715 return NULL;
2717 if (status == GOT_STATUS_BASE_REF_ERR) {
2718 a->had_base_commit_ref_error = 1;
2719 return NULL;
2722 while (path[0] == '/')
2723 path++;
2725 if (a->verbosity >= 0)
2726 printf("%c %s/%s\n", status, a->worktree_path, path);
2728 return NULL;
2731 static const struct got_error *
2732 check_cancelled(void *arg)
2734 if (sigint_received || sigpipe_received)
2735 return got_error(GOT_ERR_CANCELLED);
2736 return NULL;
2739 static const struct got_error *
2740 check_linear_ancestry(struct got_object_id *commit_id,
2741 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2742 struct got_repository *repo)
2744 const struct got_error *err = NULL;
2745 struct got_object_id *yca_id;
2747 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2748 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2749 if (err)
2750 return err;
2752 if (yca_id == NULL)
2753 return got_error(GOT_ERR_ANCESTRY);
2756 * Require a straight line of history between the target commit
2757 * and the work tree's base commit.
2759 * Non-linear situations such as this require a rebase:
2761 * (commit) D F (base_commit)
2762 * \ /
2763 * C E
2764 * \ /
2765 * B (yca)
2766 * |
2767 * A
2769 * 'got update' only handles linear cases:
2770 * Update forwards in time: A (base/yca) - B - C - D (commit)
2771 * Update backwards in time: D (base) - C - B - A (commit/yca)
2773 if (allow_forwards_in_time_only) {
2774 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2775 return got_error(GOT_ERR_ANCESTRY);
2776 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2777 got_object_id_cmp(base_commit_id, yca_id) != 0)
2778 return got_error(GOT_ERR_ANCESTRY);
2780 free(yca_id);
2781 return NULL;
2784 static const struct got_error *
2785 check_same_branch(struct got_object_id *commit_id,
2786 struct got_reference *head_ref, struct got_object_id *yca_id,
2787 struct got_repository *repo)
2789 const struct got_error *err = NULL;
2790 struct got_commit_graph *graph = NULL;
2791 struct got_object_id *head_commit_id = NULL;
2792 int is_same_branch = 0;
2794 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2795 if (err)
2796 goto done;
2798 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2799 is_same_branch = 1;
2800 goto done;
2802 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2803 is_same_branch = 1;
2804 goto done;
2807 err = got_commit_graph_open(&graph, "/", 1);
2808 if (err)
2809 goto done;
2811 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2812 check_cancelled, NULL);
2813 if (err)
2814 goto done;
2816 for (;;) {
2817 struct got_object_id *id;
2818 err = got_commit_graph_iter_next(&id, graph, repo,
2819 check_cancelled, NULL);
2820 if (err) {
2821 if (err->code == GOT_ERR_ITER_COMPLETED)
2822 err = NULL;
2823 break;
2826 if (id) {
2827 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2828 break;
2829 if (got_object_id_cmp(id, commit_id) == 0) {
2830 is_same_branch = 1;
2831 break;
2835 done:
2836 if (graph)
2837 got_commit_graph_close(graph);
2838 free(head_commit_id);
2839 if (!err && !is_same_branch)
2840 err = got_error(GOT_ERR_ANCESTRY);
2841 return err;
2844 static const struct got_error *
2845 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2847 static char msg[512];
2848 const char *branch_name;
2850 if (got_ref_is_symbolic(ref))
2851 branch_name = got_ref_get_symref_target(ref);
2852 else
2853 branch_name = got_ref_get_name(ref);
2855 if (strncmp("refs/heads/", branch_name, 11) == 0)
2856 branch_name += 11;
2858 snprintf(msg, sizeof(msg),
2859 "target commit is not contained in branch '%s'; "
2860 "the branch to use must be specified with -b; "
2861 "if necessary a new branch can be created for "
2862 "this commit with 'got branch -c %s BRANCH_NAME'",
2863 branch_name, commit_id_str);
2865 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2868 static const struct got_error *
2869 cmd_checkout(int argc, char *argv[])
2871 const struct got_error *error = NULL;
2872 struct got_repository *repo = NULL;
2873 struct got_reference *head_ref = NULL, *ref = NULL;
2874 struct got_worktree *worktree = NULL;
2875 char *repo_path = NULL;
2876 char *worktree_path = NULL;
2877 const char *path_prefix = "";
2878 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2879 char *commit_id_str = NULL;
2880 struct got_object_id *commit_id = NULL;
2881 char *cwd = NULL;
2882 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2883 struct got_pathlist_head paths;
2884 struct got_checkout_progress_arg cpa;
2885 int *pack_fds = NULL;
2887 TAILQ_INIT(&paths);
2889 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2890 switch (ch) {
2891 case 'b':
2892 branch_name = optarg;
2893 break;
2894 case 'c':
2895 commit_id_str = strdup(optarg);
2896 if (commit_id_str == NULL)
2897 return got_error_from_errno("strdup");
2898 break;
2899 case 'E':
2900 allow_nonempty = 1;
2901 break;
2902 case 'p':
2903 path_prefix = optarg;
2904 break;
2905 case 'q':
2906 verbosity = -1;
2907 break;
2908 default:
2909 usage_checkout();
2910 /* NOTREACHED */
2914 argc -= optind;
2915 argv += optind;
2917 #ifndef PROFILE
2918 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2919 "unveil", NULL) == -1)
2920 err(1, "pledge");
2921 #endif
2922 if (argc == 1) {
2923 char *base, *dotgit;
2924 const char *path;
2925 repo_path = realpath(argv[0], NULL);
2926 if (repo_path == NULL)
2927 return got_error_from_errno2("realpath", argv[0]);
2928 cwd = getcwd(NULL, 0);
2929 if (cwd == NULL) {
2930 error = got_error_from_errno("getcwd");
2931 goto done;
2933 if (path_prefix[0])
2934 path = path_prefix;
2935 else
2936 path = repo_path;
2937 error = got_path_basename(&base, path);
2938 if (error)
2939 goto done;
2940 dotgit = strstr(base, ".git");
2941 if (dotgit)
2942 *dotgit = '\0';
2943 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2944 error = got_error_from_errno("asprintf");
2945 free(base);
2946 goto done;
2948 free(base);
2949 } else if (argc == 2) {
2950 repo_path = realpath(argv[0], NULL);
2951 if (repo_path == NULL) {
2952 error = got_error_from_errno2("realpath", argv[0]);
2953 goto done;
2955 worktree_path = realpath(argv[1], NULL);
2956 if (worktree_path == NULL) {
2957 if (errno != ENOENT) {
2958 error = got_error_from_errno2("realpath",
2959 argv[1]);
2960 goto done;
2962 worktree_path = strdup(argv[1]);
2963 if (worktree_path == NULL) {
2964 error = got_error_from_errno("strdup");
2965 goto done;
2968 } else
2969 usage_checkout();
2971 got_path_strip_trailing_slashes(repo_path);
2972 got_path_strip_trailing_slashes(worktree_path);
2974 error = got_repo_pack_fds_open(&pack_fds);
2975 if (error != NULL)
2976 goto done;
2978 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2979 if (error != NULL)
2980 goto done;
2982 /* Pre-create work tree path for unveil(2) */
2983 error = got_path_mkdir(worktree_path);
2984 if (error) {
2985 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2986 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2987 goto done;
2988 if (!allow_nonempty &&
2989 !got_path_dir_is_empty(worktree_path)) {
2990 error = got_error_path(worktree_path,
2991 GOT_ERR_DIR_NOT_EMPTY);
2992 goto done;
2996 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2997 if (error)
2998 goto done;
3000 error = got_ref_open(&head_ref, repo, branch_name, 0);
3001 if (error != NULL)
3002 goto done;
3004 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3005 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3006 goto done;
3008 error = got_worktree_open(&worktree, worktree_path);
3009 if (error != NULL)
3010 goto done;
3012 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3013 path_prefix);
3014 if (error != NULL)
3015 goto done;
3016 if (!same_path_prefix) {
3017 error = got_error(GOT_ERR_PATH_PREFIX);
3018 goto done;
3021 if (commit_id_str) {
3022 struct got_reflist_head refs;
3023 TAILQ_INIT(&refs);
3024 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3025 NULL);
3026 if (error)
3027 goto done;
3028 error = got_repo_match_object_id(&commit_id, NULL,
3029 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3030 got_ref_list_free(&refs);
3031 if (error)
3032 goto done;
3033 error = check_linear_ancestry(commit_id,
3034 got_worktree_get_base_commit_id(worktree), 0, repo);
3035 if (error != NULL) {
3036 if (error->code == GOT_ERR_ANCESTRY) {
3037 error = checkout_ancestry_error(
3038 head_ref, commit_id_str);
3040 goto done;
3042 error = check_same_branch(commit_id, head_ref, NULL, repo);
3043 if (error) {
3044 if (error->code == GOT_ERR_ANCESTRY) {
3045 error = checkout_ancestry_error(
3046 head_ref, commit_id_str);
3048 goto done;
3050 error = got_worktree_set_base_commit_id(worktree, repo,
3051 commit_id);
3052 if (error)
3053 goto done;
3054 /* Expand potentially abbreviated commit ID string. */
3055 free(commit_id_str);
3056 error = got_object_id_str(&commit_id_str, commit_id);
3057 if (error)
3058 goto done;
3059 } else {
3060 commit_id = got_object_id_dup(
3061 got_worktree_get_base_commit_id(worktree));
3062 if (commit_id == NULL) {
3063 error = got_error_from_errno("got_object_id_dup");
3064 goto done;
3066 error = got_object_id_str(&commit_id_str, commit_id);
3067 if (error)
3068 goto done;
3071 error = got_pathlist_append(&paths, "", NULL);
3072 if (error)
3073 goto done;
3074 cpa.worktree_path = worktree_path;
3075 cpa.had_base_commit_ref_error = 0;
3076 cpa.verbosity = verbosity;
3077 error = got_worktree_checkout_files(worktree, &paths, repo,
3078 checkout_progress, &cpa, check_cancelled, NULL);
3079 if (error != NULL)
3080 goto done;
3082 if (got_ref_is_symbolic(head_ref)) {
3083 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3084 if (error)
3085 goto done;
3086 refname = got_ref_get_name(ref);
3087 } else
3088 refname = got_ref_get_name(head_ref);
3089 printf("Checked out %s: %s\n", refname, commit_id_str);
3090 printf("Now shut up and hack\n");
3091 if (cpa.had_base_commit_ref_error)
3092 show_worktree_base_ref_warning();
3093 done:
3094 if (pack_fds) {
3095 const struct got_error *pack_err =
3096 got_repo_pack_fds_close(pack_fds);
3097 if (error == NULL)
3098 error = pack_err;
3099 pack_fds = NULL;
3101 if (head_ref)
3102 got_ref_close(head_ref);
3103 if (ref)
3104 got_ref_close(ref);
3105 got_pathlist_free(&paths);
3106 free(commit_id_str);
3107 free(commit_id);
3108 free(repo_path);
3109 free(worktree_path);
3110 free(cwd);
3111 return error;
3114 struct got_update_progress_arg {
3115 int did_something;
3116 int conflicts;
3117 int obstructed;
3118 int not_updated;
3119 int missing;
3120 int not_deleted;
3121 int unversioned;
3122 int verbosity;
3125 void
3126 print_update_progress_stats(struct got_update_progress_arg *upa)
3128 if (!upa->did_something)
3129 return;
3131 if (upa->conflicts > 0)
3132 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3133 if (upa->obstructed > 0)
3134 printf("File paths obstructed by a non-regular file: %d\n",
3135 upa->obstructed);
3136 if (upa->not_updated > 0)
3137 printf("Files not updated because of existing merge "
3138 "conflicts: %d\n", upa->not_updated);
3142 * The meaning of some status codes differs between merge-style operations and
3143 * update operations. For example, the ! status code means "file was missing"
3144 * if changes were merged into the work tree, and "missing file was restored"
3145 * if the work tree was updated. This function should be used by any operation
3146 * which merges changes into the work tree without updating the work tree.
3148 void
3149 print_merge_progress_stats(struct got_update_progress_arg *upa)
3151 if (!upa->did_something)
3152 return;
3154 if (upa->conflicts > 0)
3155 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3156 if (upa->obstructed > 0)
3157 printf("File paths obstructed by a non-regular file: %d\n",
3158 upa->obstructed);
3159 if (upa->missing > 0)
3160 printf("Files which had incoming changes but could not be "
3161 "found in the work tree: %d\n", upa->missing);
3162 if (upa->not_deleted > 0)
3163 printf("Files not deleted due to differences in deleted "
3164 "content: %d\n", upa->not_deleted);
3165 if (upa->unversioned > 0)
3166 printf("Files not merged because an unversioned file was "
3167 "found in the work tree: %d\n", upa->unversioned);
3170 __dead static void
3171 usage_update(void)
3173 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3174 "[path ...]\n",
3175 getprogname());
3176 exit(1);
3179 static const struct got_error *
3180 update_progress(void *arg, unsigned char status, const char *path)
3182 struct got_update_progress_arg *upa = arg;
3184 if (status == GOT_STATUS_EXISTS ||
3185 status == GOT_STATUS_BASE_REF_ERR)
3186 return NULL;
3188 upa->did_something = 1;
3190 /* Base commit bump happens silently. */
3191 if (status == GOT_STATUS_BUMP_BASE)
3192 return NULL;
3194 if (status == GOT_STATUS_CONFLICT)
3195 upa->conflicts++;
3196 if (status == GOT_STATUS_OBSTRUCTED)
3197 upa->obstructed++;
3198 if (status == GOT_STATUS_CANNOT_UPDATE)
3199 upa->not_updated++;
3200 if (status == GOT_STATUS_MISSING)
3201 upa->missing++;
3202 if (status == GOT_STATUS_CANNOT_DELETE)
3203 upa->not_deleted++;
3204 if (status == GOT_STATUS_UNVERSIONED)
3205 upa->unversioned++;
3207 while (path[0] == '/')
3208 path++;
3209 if (upa->verbosity >= 0)
3210 printf("%c %s\n", status, path);
3212 return NULL;
3215 static const struct got_error *
3216 switch_head_ref(struct got_reference *head_ref,
3217 struct got_object_id *commit_id, struct got_worktree *worktree,
3218 struct got_repository *repo)
3220 const struct got_error *err = NULL;
3221 char *base_id_str;
3222 int ref_has_moved = 0;
3224 /* Trivial case: switching between two different references. */
3225 if (strcmp(got_ref_get_name(head_ref),
3226 got_worktree_get_head_ref_name(worktree)) != 0) {
3227 printf("Switching work tree from %s to %s\n",
3228 got_worktree_get_head_ref_name(worktree),
3229 got_ref_get_name(head_ref));
3230 return got_worktree_set_head_ref(worktree, head_ref);
3233 err = check_linear_ancestry(commit_id,
3234 got_worktree_get_base_commit_id(worktree), 0, repo);
3235 if (err) {
3236 if (err->code != GOT_ERR_ANCESTRY)
3237 return err;
3238 ref_has_moved = 1;
3240 if (!ref_has_moved)
3241 return NULL;
3243 /* Switching to a rebased branch with the same reference name. */
3244 err = got_object_id_str(&base_id_str,
3245 got_worktree_get_base_commit_id(worktree));
3246 if (err)
3247 return err;
3248 printf("Reference %s now points at a different branch\n",
3249 got_worktree_get_head_ref_name(worktree));
3250 printf("Switching work tree from %s to %s\n", base_id_str,
3251 got_worktree_get_head_ref_name(worktree));
3252 return NULL;
3255 static const struct got_error *
3256 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3258 const struct got_error *err;
3259 int in_progress;
3261 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3262 if (err)
3263 return err;
3264 if (in_progress)
3265 return got_error(GOT_ERR_REBASING);
3267 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3268 if (err)
3269 return err;
3270 if (in_progress)
3271 return got_error(GOT_ERR_HISTEDIT_BUSY);
3273 return NULL;
3276 static const struct got_error *
3277 check_merge_in_progress(struct got_worktree *worktree,
3278 struct got_repository *repo)
3280 const struct got_error *err;
3281 int in_progress;
3283 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3284 if (err)
3285 return err;
3286 if (in_progress)
3287 return got_error(GOT_ERR_MERGE_BUSY);
3289 return NULL;
3292 static const struct got_error *
3293 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3294 char *argv[], struct got_worktree *worktree)
3296 const struct got_error *err = NULL;
3297 char *path;
3298 struct got_pathlist_entry *new;
3299 int i;
3301 if (argc == 0) {
3302 path = strdup("");
3303 if (path == NULL)
3304 return got_error_from_errno("strdup");
3305 return got_pathlist_append(paths, path, NULL);
3308 for (i = 0; i < argc; i++) {
3309 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3310 if (err)
3311 break;
3312 err = got_pathlist_insert(&new, paths, path, NULL);
3313 if (err || new == NULL /* duplicate */) {
3314 free(path);
3315 if (err)
3316 break;
3320 return err;
3323 static const struct got_error *
3324 wrap_not_worktree_error(const struct got_error *orig_err,
3325 const char *cmdname, const char *path)
3327 const struct got_error *err;
3328 struct got_repository *repo;
3329 static char msg[512];
3330 int *pack_fds = NULL;
3332 err = got_repo_pack_fds_open(&pack_fds);
3333 if (err)
3334 return err;
3336 err = got_repo_open(&repo, path, NULL, pack_fds);
3337 if (err)
3338 return orig_err;
3340 snprintf(msg, sizeof(msg),
3341 "'got %s' needs a work tree in addition to a git repository\n"
3342 "Work trees can be checked out from this Git repository with "
3343 "'got checkout'.\n"
3344 "The got(1) manual page contains more information.", cmdname);
3345 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3346 got_repo_close(repo);
3347 if (pack_fds) {
3348 const struct got_error *pack_err =
3349 got_repo_pack_fds_close(pack_fds);
3350 if (err == NULL)
3351 err = pack_err;
3352 pack_fds = NULL;
3354 return err;
3357 static const struct got_error *
3358 cmd_update(int argc, char *argv[])
3360 const struct got_error *error = NULL;
3361 struct got_repository *repo = NULL;
3362 struct got_worktree *worktree = NULL;
3363 char *worktree_path = NULL;
3364 struct got_object_id *commit_id = NULL;
3365 char *commit_id_str = NULL;
3366 const char *branch_name = NULL;
3367 struct got_reference *head_ref = NULL;
3368 struct got_pathlist_head paths;
3369 struct got_pathlist_entry *pe;
3370 int ch, verbosity = 0;
3371 struct got_update_progress_arg upa;
3372 int *pack_fds = NULL;
3374 TAILQ_INIT(&paths);
3376 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3377 switch (ch) {
3378 case 'b':
3379 branch_name = optarg;
3380 break;
3381 case 'c':
3382 commit_id_str = strdup(optarg);
3383 if (commit_id_str == NULL)
3384 return got_error_from_errno("strdup");
3385 break;
3386 case 'q':
3387 verbosity = -1;
3388 break;
3389 default:
3390 usage_update();
3391 /* NOTREACHED */
3395 argc -= optind;
3396 argv += optind;
3398 #ifndef PROFILE
3399 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3400 "unveil", NULL) == -1)
3401 err(1, "pledge");
3402 #endif
3403 worktree_path = getcwd(NULL, 0);
3404 if (worktree_path == NULL) {
3405 error = got_error_from_errno("getcwd");
3406 goto done;
3409 error = got_repo_pack_fds_open(&pack_fds);
3410 if (error != NULL)
3411 goto done;
3413 error = got_worktree_open(&worktree, worktree_path);
3414 if (error) {
3415 if (error->code == GOT_ERR_NOT_WORKTREE)
3416 error = wrap_not_worktree_error(error, "update",
3417 worktree_path);
3418 goto done;
3421 error = check_rebase_or_histedit_in_progress(worktree);
3422 if (error)
3423 goto done;
3425 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3426 NULL, pack_fds);
3427 if (error != NULL)
3428 goto done;
3430 error = apply_unveil(got_repo_get_path(repo), 0,
3431 got_worktree_get_root_path(worktree));
3432 if (error)
3433 goto done;
3435 error = check_merge_in_progress(worktree, repo);
3436 if (error)
3437 goto done;
3439 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3440 if (error)
3441 goto done;
3443 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3444 got_worktree_get_head_ref_name(worktree), 0);
3445 if (error != NULL)
3446 goto done;
3447 if (commit_id_str == NULL) {
3448 error = got_ref_resolve(&commit_id, repo, head_ref);
3449 if (error != NULL)
3450 goto done;
3451 error = got_object_id_str(&commit_id_str, commit_id);
3452 if (error != NULL)
3453 goto done;
3454 } else {
3455 struct got_reflist_head refs;
3456 TAILQ_INIT(&refs);
3457 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3458 NULL);
3459 if (error)
3460 goto done;
3461 error = got_repo_match_object_id(&commit_id, NULL,
3462 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3463 got_ref_list_free(&refs);
3464 free(commit_id_str);
3465 commit_id_str = NULL;
3466 if (error)
3467 goto done;
3468 error = got_object_id_str(&commit_id_str, commit_id);
3469 if (error)
3470 goto done;
3473 if (branch_name) {
3474 struct got_object_id *head_commit_id;
3475 TAILQ_FOREACH(pe, &paths, entry) {
3476 if (pe->path_len == 0)
3477 continue;
3478 error = got_error_msg(GOT_ERR_BAD_PATH,
3479 "switching between branches requires that "
3480 "the entire work tree gets updated");
3481 goto done;
3483 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3484 if (error)
3485 goto done;
3486 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3487 repo);
3488 free(head_commit_id);
3489 if (error != NULL)
3490 goto done;
3491 error = check_same_branch(commit_id, head_ref, NULL, repo);
3492 if (error)
3493 goto done;
3494 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3495 if (error)
3496 goto done;
3497 } else {
3498 error = check_linear_ancestry(commit_id,
3499 got_worktree_get_base_commit_id(worktree), 0, repo);
3500 if (error != NULL) {
3501 if (error->code == GOT_ERR_ANCESTRY)
3502 error = got_error(GOT_ERR_BRANCH_MOVED);
3503 goto done;
3505 error = check_same_branch(commit_id, head_ref, NULL, repo);
3506 if (error)
3507 goto done;
3510 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3511 commit_id) != 0) {
3512 error = got_worktree_set_base_commit_id(worktree, repo,
3513 commit_id);
3514 if (error)
3515 goto done;
3518 memset(&upa, 0, sizeof(upa));
3519 upa.verbosity = verbosity;
3520 error = got_worktree_checkout_files(worktree, &paths, repo,
3521 update_progress, &upa, check_cancelled, NULL);
3522 if (error != NULL)
3523 goto done;
3525 if (upa.did_something) {
3526 printf("Updated to %s: %s\n",
3527 got_worktree_get_head_ref_name(worktree), commit_id_str);
3528 } else
3529 printf("Already up-to-date\n");
3531 print_update_progress_stats(&upa);
3532 done:
3533 if (pack_fds) {
3534 const struct got_error *pack_err =
3535 got_repo_pack_fds_close(pack_fds);
3536 if (error == NULL)
3537 error = pack_err;
3538 pack_fds = NULL;
3540 free(worktree_path);
3541 TAILQ_FOREACH(pe, &paths, entry)
3542 free((char *)pe->path);
3543 got_pathlist_free(&paths);
3544 free(commit_id);
3545 free(commit_id_str);
3546 return error;
3549 static const struct got_error *
3550 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3551 const char *path, int diff_context, int ignore_whitespace,
3552 int force_text_diff, struct got_repository *repo, FILE *outfile)
3554 const struct got_error *err = NULL;
3555 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3556 FILE *f1 = NULL, *f2 = NULL;
3558 if (blob_id1) {
3559 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3560 if (err)
3561 goto done;
3562 f1 = got_opentemp();
3563 if (f1 == NULL) {
3564 err = got_error_from_errno("got_opentemp");
3565 goto done;
3569 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3570 if (err)
3571 goto done;
3573 f2 = got_opentemp();
3574 if (f2 == NULL) {
3575 err = got_error_from_errno("got_opentemp");
3576 goto done;
3579 while (path[0] == '/')
3580 path++;
3581 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3582 diff_context, ignore_whitespace, force_text_diff, outfile);
3583 done:
3584 if (blob1)
3585 got_object_blob_close(blob1);
3586 got_object_blob_close(blob2);
3587 if (f1 && fclose(f1) == EOF && err == NULL)
3588 err = got_error_from_errno("fclose");
3589 if (f2 && fclose(f2) == EOF && err == NULL)
3590 err = got_error_from_errno("fclose");
3591 return err;
3594 static const struct got_error *
3595 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3596 const char *path, int diff_context, int ignore_whitespace,
3597 int force_text_diff, struct got_repository *repo, FILE *outfile)
3599 const struct got_error *err = NULL;
3600 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3601 struct got_diff_blob_output_unidiff_arg arg;
3602 FILE *f1 = NULL, *f2 = NULL;
3604 if (tree_id1) {
3605 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3606 if (err)
3607 goto done;
3608 f1 = got_opentemp();
3609 if (f1 == NULL) {
3610 err = got_error_from_errno("got_opentemp");
3611 goto done;
3615 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3616 if (err)
3617 goto done;
3619 f2 = got_opentemp();
3620 if (f2 == NULL) {
3621 err = got_error_from_errno("got_opentemp");
3622 goto done;
3625 arg.diff_context = diff_context;
3626 arg.ignore_whitespace = ignore_whitespace;
3627 arg.force_text_diff = force_text_diff;
3628 arg.outfile = outfile;
3629 arg.line_offsets = NULL;
3630 arg.nlines = 0;
3631 while (path[0] == '/')
3632 path++;
3633 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3634 got_diff_blob_output_unidiff, &arg, 1);
3635 done:
3636 if (tree1)
3637 got_object_tree_close(tree1);
3638 if (tree2)
3639 got_object_tree_close(tree2);
3640 if (f1 && fclose(f1) == EOF && err == NULL)
3641 err = got_error_from_errno("fclose");
3642 if (f2 && fclose(f2) == EOF && err == NULL)
3643 err = got_error_from_errno("fclose");
3644 return err;
3647 static const struct got_error *
3648 get_changed_paths(struct got_pathlist_head *paths,
3649 struct got_commit_object *commit, struct got_repository *repo)
3651 const struct got_error *err = NULL;
3652 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3653 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3654 struct got_object_qid *qid;
3656 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3657 if (qid != NULL) {
3658 struct got_commit_object *pcommit;
3659 err = got_object_open_as_commit(&pcommit, repo,
3660 &qid->id);
3661 if (err)
3662 return err;
3664 tree_id1 = got_object_id_dup(
3665 got_object_commit_get_tree_id(pcommit));
3666 if (tree_id1 == NULL) {
3667 got_object_commit_close(pcommit);
3668 return got_error_from_errno("got_object_id_dup");
3670 got_object_commit_close(pcommit);
3674 if (tree_id1) {
3675 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3676 if (err)
3677 goto done;
3680 tree_id2 = got_object_commit_get_tree_id(commit);
3681 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3682 if (err)
3683 goto done;
3685 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3686 got_diff_tree_collect_changed_paths, paths, 0);
3687 done:
3688 if (tree1)
3689 got_object_tree_close(tree1);
3690 if (tree2)
3691 got_object_tree_close(tree2);
3692 free(tree_id1);
3693 return err;
3696 static const struct got_error *
3697 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3698 const char *path, int diff_context, struct got_repository *repo,
3699 FILE *outfile)
3701 const struct got_error *err = NULL;
3702 struct got_commit_object *pcommit = NULL;
3703 char *id_str1 = NULL, *id_str2 = NULL;
3704 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3705 struct got_object_qid *qid;
3707 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3708 if (qid != NULL) {
3709 err = got_object_open_as_commit(&pcommit, repo,
3710 &qid->id);
3711 if (err)
3712 return err;
3715 if (path && path[0] != '\0') {
3716 int obj_type;
3717 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3718 if (err)
3719 goto done;
3720 err = got_object_id_str(&id_str2, obj_id2);
3721 if (err) {
3722 free(obj_id2);
3723 goto done;
3725 if (pcommit) {
3726 err = got_object_id_by_path(&obj_id1, repo,
3727 pcommit, path);
3728 if (err) {
3729 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3730 free(obj_id2);
3731 goto done;
3733 } else {
3734 err = got_object_id_str(&id_str1, obj_id1);
3735 if (err) {
3736 free(obj_id2);
3737 goto done;
3741 err = got_object_get_type(&obj_type, repo, obj_id2);
3742 if (err) {
3743 free(obj_id2);
3744 goto done;
3746 fprintf(outfile,
3747 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3748 switch (obj_type) {
3749 case GOT_OBJ_TYPE_BLOB:
3750 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3751 0, 0, repo, outfile);
3752 break;
3753 case GOT_OBJ_TYPE_TREE:
3754 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3755 0, 0, repo, outfile);
3756 break;
3757 default:
3758 err = got_error(GOT_ERR_OBJ_TYPE);
3759 break;
3761 free(obj_id1);
3762 free(obj_id2);
3763 } else {
3764 obj_id2 = got_object_commit_get_tree_id(commit);
3765 err = got_object_id_str(&id_str2, obj_id2);
3766 if (err)
3767 goto done;
3768 if (pcommit) {
3769 obj_id1 = got_object_commit_get_tree_id(pcommit);
3770 err = got_object_id_str(&id_str1, obj_id1);
3771 if (err)
3772 goto done;
3774 fprintf(outfile,
3775 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3776 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3777 repo, outfile);
3779 done:
3780 free(id_str1);
3781 free(id_str2);
3782 if (pcommit)
3783 got_object_commit_close(pcommit);
3784 return err;
3787 static char *
3788 get_datestr(time_t *time, char *datebuf)
3790 struct tm mytm, *tm;
3791 char *p, *s;
3793 tm = gmtime_r(time, &mytm);
3794 if (tm == NULL)
3795 return NULL;
3796 s = asctime_r(tm, datebuf);
3797 if (s == NULL)
3798 return NULL;
3799 p = strchr(s, '\n');
3800 if (p)
3801 *p = '\0';
3802 return s;
3805 static const struct got_error *
3806 match_commit(int *have_match, struct got_object_id *id,
3807 struct got_commit_object *commit, regex_t *regex)
3809 const struct got_error *err = NULL;
3810 regmatch_t regmatch;
3811 char *id_str = NULL, *logmsg = NULL;
3813 *have_match = 0;
3815 err = got_object_id_str(&id_str, id);
3816 if (err)
3817 return err;
3819 err = got_object_commit_get_logmsg(&logmsg, commit);
3820 if (err)
3821 goto done;
3823 if (regexec(regex, got_object_commit_get_author(commit), 1,
3824 &regmatch, 0) == 0 ||
3825 regexec(regex, got_object_commit_get_committer(commit), 1,
3826 &regmatch, 0) == 0 ||
3827 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3828 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3829 *have_match = 1;
3830 done:
3831 free(id_str);
3832 free(logmsg);
3833 return err;
3836 static void
3837 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3838 regex_t *regex)
3840 regmatch_t regmatch;
3841 struct got_pathlist_entry *pe;
3843 *have_match = 0;
3845 TAILQ_FOREACH(pe, changed_paths, entry) {
3846 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3847 *have_match = 1;
3848 break;
3853 static const struct got_error *
3854 match_patch(int *have_match, struct got_commit_object *commit,
3855 struct got_object_id *id, const char *path, int diff_context,
3856 struct got_repository *repo, regex_t *regex, FILE *f)
3858 const struct got_error *err = NULL;
3859 char *line = NULL;
3860 size_t linesize = 0;
3861 ssize_t linelen;
3862 regmatch_t regmatch;
3864 *have_match = 0;
3866 err = got_opentemp_truncate(f);
3867 if (err)
3868 return err;
3870 err = print_patch(commit, id, path, diff_context, repo, f);
3871 if (err)
3872 goto done;
3874 if (fseeko(f, 0L, SEEK_SET) == -1) {
3875 err = got_error_from_errno("fseeko");
3876 goto done;
3879 while ((linelen = getline(&line, &linesize, f)) != -1) {
3880 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3881 *have_match = 1;
3882 break;
3885 done:
3886 free(line);
3887 return err;
3890 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3892 static const struct got_error*
3893 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3894 struct got_object_id *id, struct got_repository *repo,
3895 int local_only)
3897 static const struct got_error *err = NULL;
3898 struct got_reflist_entry *re;
3899 char *s;
3900 const char *name;
3902 *refs_str = NULL;
3904 TAILQ_FOREACH(re, refs, entry) {
3905 struct got_tag_object *tag = NULL;
3906 struct got_object_id *ref_id;
3907 int cmp;
3909 name = got_ref_get_name(re->ref);
3910 if (strcmp(name, GOT_REF_HEAD) == 0)
3911 continue;
3912 if (strncmp(name, "refs/", 5) == 0)
3913 name += 5;
3914 if (strncmp(name, "got/", 4) == 0)
3915 continue;
3916 if (strncmp(name, "heads/", 6) == 0)
3917 name += 6;
3918 if (strncmp(name, "remotes/", 8) == 0) {
3919 if (local_only)
3920 continue;
3921 name += 8;
3922 s = strstr(name, "/" GOT_REF_HEAD);
3923 if (s != NULL && s[strlen(s)] == '\0')
3924 continue;
3926 err = got_ref_resolve(&ref_id, repo, re->ref);
3927 if (err)
3928 break;
3929 if (strncmp(name, "tags/", 5) == 0) {
3930 err = got_object_open_as_tag(&tag, repo, ref_id);
3931 if (err) {
3932 if (err->code != GOT_ERR_OBJ_TYPE) {
3933 free(ref_id);
3934 break;
3936 /* Ref points at something other than a tag. */
3937 err = NULL;
3938 tag = NULL;
3941 cmp = got_object_id_cmp(tag ?
3942 got_object_tag_get_object_id(tag) : ref_id, id);
3943 free(ref_id);
3944 if (tag)
3945 got_object_tag_close(tag);
3946 if (cmp != 0)
3947 continue;
3948 s = *refs_str;
3949 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3950 s ? ", " : "", name) == -1) {
3951 err = got_error_from_errno("asprintf");
3952 free(s);
3953 *refs_str = NULL;
3954 break;
3956 free(s);
3959 return err;
3962 static const struct got_error *
3963 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3964 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3966 const struct got_error *err = NULL;
3967 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3968 char *comma, *s, *nl;
3969 struct got_reflist_head *refs;
3970 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3971 struct tm tm;
3972 time_t committer_time;
3974 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3975 if (refs) {
3976 err = build_refs_str(&ref_str, refs, id, repo, 1);
3977 if (err)
3978 return err;
3980 /* Display the first matching ref only. */
3981 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3982 *comma = '\0';
3985 if (ref_str == NULL) {
3986 err = got_object_id_str(&id_str, id);
3987 if (err)
3988 return err;
3991 committer_time = got_object_commit_get_committer_time(commit);
3992 if (gmtime_r(&committer_time, &tm) == NULL) {
3993 err = got_error_from_errno("gmtime_r");
3994 goto done;
3996 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3997 err = got_error(GOT_ERR_NO_SPACE);
3998 goto done;
4001 err = got_object_commit_get_logmsg(&logmsg0, commit);
4002 if (err)
4003 goto done;
4005 s = logmsg0;
4006 while (isspace((unsigned char)s[0]))
4007 s++;
4009 nl = strchr(s, '\n');
4010 if (nl) {
4011 *nl = '\0';
4014 if (ref_str)
4015 printf("%s%-7s %s\n", datebuf, ref_str, s);
4016 else
4017 printf("%s%.7s %s\n", datebuf, id_str, s);
4019 if (fflush(stdout) != 0 && err == NULL)
4020 err = got_error_from_errno("fflush");
4021 done:
4022 free(id_str);
4023 free(ref_str);
4024 free(logmsg0);
4025 return err;
4028 static const struct got_error *
4029 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4030 struct got_repository *repo, const char *path,
4031 struct got_pathlist_head *changed_paths, int show_patch,
4032 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4033 const char *custom_refs_str)
4035 const struct got_error *err = NULL;
4036 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4037 char datebuf[26];
4038 time_t committer_time;
4039 const char *author, *committer;
4040 char *refs_str = NULL;
4042 err = got_object_id_str(&id_str, id);
4043 if (err)
4044 return err;
4046 if (custom_refs_str == NULL) {
4047 struct got_reflist_head *refs;
4048 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4049 if (refs) {
4050 err = build_refs_str(&refs_str, refs, id, repo, 0);
4051 if (err)
4052 goto done;
4056 printf(GOT_COMMIT_SEP_STR);
4057 if (custom_refs_str)
4058 printf("commit %s (%s)\n", id_str, custom_refs_str);
4059 else
4060 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4061 refs_str ? refs_str : "", refs_str ? ")" : "");
4062 free(id_str);
4063 id_str = NULL;
4064 free(refs_str);
4065 refs_str = NULL;
4066 printf("from: %s\n", got_object_commit_get_author(commit));
4067 committer_time = got_object_commit_get_committer_time(commit);
4068 datestr = get_datestr(&committer_time, datebuf);
4069 if (datestr)
4070 printf("date: %s UTC\n", datestr);
4071 author = got_object_commit_get_author(commit);
4072 committer = got_object_commit_get_committer(commit);
4073 if (strcmp(author, committer) != 0)
4074 printf("via: %s\n", committer);
4075 if (got_object_commit_get_nparents(commit) > 1) {
4076 const struct got_object_id_queue *parent_ids;
4077 struct got_object_qid *qid;
4078 int n = 1;
4079 parent_ids = got_object_commit_get_parent_ids(commit);
4080 STAILQ_FOREACH(qid, parent_ids, entry) {
4081 err = got_object_id_str(&id_str, &qid->id);
4082 if (err)
4083 goto done;
4084 printf("parent %d: %s\n", n++, id_str);
4085 free(id_str);
4086 id_str = NULL;
4090 err = got_object_commit_get_logmsg(&logmsg0, commit);
4091 if (err)
4092 goto done;
4094 logmsg = logmsg0;
4095 do {
4096 line = strsep(&logmsg, "\n");
4097 if (line)
4098 printf(" %s\n", line);
4099 } while (line);
4100 free(logmsg0);
4102 if (changed_paths) {
4103 struct got_pathlist_entry *pe;
4104 TAILQ_FOREACH(pe, changed_paths, entry) {
4105 struct got_diff_changed_path *cp = pe->data;
4106 printf(" %c %s\n", cp->status, pe->path);
4108 printf("\n");
4110 if (show_patch) {
4111 err = print_patch(commit, id, path, diff_context, repo, stdout);
4112 if (err == 0)
4113 printf("\n");
4116 if (fflush(stdout) != 0 && err == NULL)
4117 err = got_error_from_errno("fflush");
4118 done:
4119 free(id_str);
4120 free(refs_str);
4121 return err;
4124 static const struct got_error *
4125 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4126 struct got_repository *repo, const char *path, int show_changed_paths,
4127 int show_patch, const char *search_pattern, int diff_context, int limit,
4128 int log_branches, int reverse_display_order,
4129 struct got_reflist_object_id_map *refs_idmap, int one_line,
4130 FILE *tmpfile)
4132 const struct got_error *err;
4133 struct got_commit_graph *graph;
4134 regex_t regex;
4135 int have_match;
4136 struct got_object_id_queue reversed_commits;
4137 struct got_object_qid *qid;
4138 struct got_commit_object *commit;
4139 struct got_pathlist_head changed_paths;
4140 struct got_pathlist_entry *pe;
4142 STAILQ_INIT(&reversed_commits);
4143 TAILQ_INIT(&changed_paths);
4145 if (search_pattern && regcomp(&regex, search_pattern,
4146 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4147 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4149 err = got_commit_graph_open(&graph, path, !log_branches);
4150 if (err)
4151 return err;
4152 err = got_commit_graph_iter_start(graph, root_id, repo,
4153 check_cancelled, NULL);
4154 if (err)
4155 goto done;
4156 for (;;) {
4157 struct got_object_id *id;
4159 if (sigint_received || sigpipe_received)
4160 break;
4162 err = got_commit_graph_iter_next(&id, graph, repo,
4163 check_cancelled, NULL);
4164 if (err) {
4165 if (err->code == GOT_ERR_ITER_COMPLETED)
4166 err = NULL;
4167 break;
4169 if (id == NULL)
4170 break;
4172 err = got_object_open_as_commit(&commit, repo, id);
4173 if (err)
4174 break;
4176 if (show_changed_paths && !reverse_display_order) {
4177 err = get_changed_paths(&changed_paths, commit, repo);
4178 if (err)
4179 break;
4182 if (search_pattern) {
4183 err = match_commit(&have_match, id, commit, &regex);
4184 if (err) {
4185 got_object_commit_close(commit);
4186 break;
4188 if (have_match == 0 && show_changed_paths)
4189 match_changed_paths(&have_match,
4190 &changed_paths, &regex);
4191 if (have_match == 0 && show_patch) {
4192 err = match_patch(&have_match, commit, id,
4193 path, diff_context, repo, &regex,
4194 tmpfile);
4195 if (err)
4196 break;
4198 if (have_match == 0) {
4199 got_object_commit_close(commit);
4200 TAILQ_FOREACH(pe, &changed_paths, entry) {
4201 free((char *)pe->path);
4202 free(pe->data);
4204 got_pathlist_free(&changed_paths);
4205 continue;
4209 if (reverse_display_order) {
4210 err = got_object_qid_alloc(&qid, id);
4211 if (err)
4212 break;
4213 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4214 got_object_commit_close(commit);
4215 } else {
4216 if (one_line)
4217 err = print_commit_oneline(commit, id,
4218 repo, refs_idmap);
4219 else
4220 err = print_commit(commit, id, repo, path,
4221 show_changed_paths ? &changed_paths : NULL,
4222 show_patch, diff_context, refs_idmap, NULL);
4223 got_object_commit_close(commit);
4224 if (err)
4225 break;
4227 if ((limit && --limit == 0) ||
4228 (end_id && got_object_id_cmp(id, end_id) == 0))
4229 break;
4231 TAILQ_FOREACH(pe, &changed_paths, entry) {
4232 free((char *)pe->path);
4233 free(pe->data);
4235 got_pathlist_free(&changed_paths);
4237 if (reverse_display_order) {
4238 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4239 err = got_object_open_as_commit(&commit, repo,
4240 &qid->id);
4241 if (err)
4242 break;
4243 if (show_changed_paths) {
4244 err = get_changed_paths(&changed_paths,
4245 commit, repo);
4246 if (err)
4247 break;
4249 if (one_line)
4250 err = print_commit_oneline(commit, &qid->id,
4251 repo, refs_idmap);
4252 else
4253 err = print_commit(commit, &qid->id, repo, path,
4254 show_changed_paths ? &changed_paths : NULL,
4255 show_patch, diff_context, refs_idmap, NULL);
4256 got_object_commit_close(commit);
4257 if (err)
4258 break;
4259 TAILQ_FOREACH(pe, &changed_paths, entry) {
4260 free((char *)pe->path);
4261 free(pe->data);
4263 got_pathlist_free(&changed_paths);
4266 done:
4267 while (!STAILQ_EMPTY(&reversed_commits)) {
4268 qid = STAILQ_FIRST(&reversed_commits);
4269 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4270 got_object_qid_free(qid);
4272 TAILQ_FOREACH(pe, &changed_paths, entry) {
4273 free((char *)pe->path);
4274 free(pe->data);
4276 got_pathlist_free(&changed_paths);
4277 if (search_pattern)
4278 regfree(&regex);
4279 got_commit_graph_close(graph);
4280 return err;
4283 __dead static void
4284 usage_log(void)
4286 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4287 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4288 "[-r repository-path] [-R] [path]\n", getprogname());
4289 exit(1);
4292 static int
4293 get_default_log_limit(void)
4295 const char *got_default_log_limit;
4296 long long n;
4297 const char *errstr;
4299 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4300 if (got_default_log_limit == NULL)
4301 return 0;
4302 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4303 if (errstr != NULL)
4304 return 0;
4305 return n;
4308 static const struct got_error *
4309 cmd_log(int argc, char *argv[])
4311 const struct got_error *error;
4312 struct got_repository *repo = NULL;
4313 struct got_worktree *worktree = NULL;
4314 struct got_object_id *start_id = NULL, *end_id = NULL;
4315 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4316 const char *start_commit = NULL, *end_commit = NULL;
4317 const char *search_pattern = NULL;
4318 int diff_context = -1, ch;
4319 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4320 int reverse_display_order = 0, one_line = 0;
4321 const char *errstr;
4322 struct got_reflist_head refs;
4323 struct got_reflist_object_id_map *refs_idmap = NULL;
4324 FILE *tmpfile = NULL;
4325 int *pack_fds = NULL;
4327 TAILQ_INIT(&refs);
4329 #ifndef PROFILE
4330 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4331 NULL)
4332 == -1)
4333 err(1, "pledge");
4334 #endif
4336 limit = get_default_log_limit();
4338 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4339 switch (ch) {
4340 case 'p':
4341 show_patch = 1;
4342 break;
4343 case 'P':
4344 show_changed_paths = 1;
4345 break;
4346 case 'c':
4347 start_commit = optarg;
4348 break;
4349 case 'C':
4350 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4351 &errstr);
4352 if (errstr != NULL)
4353 errx(1, "number of context lines is %s: %s",
4354 errstr, optarg);
4355 break;
4356 case 'l':
4357 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4358 if (errstr != NULL)
4359 errx(1, "number of commits is %s: %s",
4360 errstr, optarg);
4361 break;
4362 case 'b':
4363 log_branches = 1;
4364 break;
4365 case 'r':
4366 repo_path = realpath(optarg, NULL);
4367 if (repo_path == NULL)
4368 return got_error_from_errno2("realpath",
4369 optarg);
4370 got_path_strip_trailing_slashes(repo_path);
4371 break;
4372 case 'R':
4373 reverse_display_order = 1;
4374 break;
4375 case 's':
4376 one_line = 1;
4377 break;
4378 case 'S':
4379 search_pattern = optarg;
4380 break;
4381 case 'x':
4382 end_commit = optarg;
4383 break;
4384 default:
4385 usage_log();
4386 /* NOTREACHED */
4390 argc -= optind;
4391 argv += optind;
4393 if (diff_context == -1)
4394 diff_context = 3;
4395 else if (!show_patch)
4396 errx(1, "-C requires -p");
4398 if (one_line && (show_patch || show_changed_paths))
4399 errx(1, "cannot use -s with -p or -P");
4401 cwd = getcwd(NULL, 0);
4402 if (cwd == NULL) {
4403 error = got_error_from_errno("getcwd");
4404 goto done;
4407 error = got_repo_pack_fds_open(&pack_fds);
4408 if (error != NULL)
4409 goto done;
4411 if (repo_path == NULL) {
4412 error = got_worktree_open(&worktree, cwd);
4413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4414 goto done;
4415 error = NULL;
4418 if (argc == 1) {
4419 if (worktree) {
4420 error = got_worktree_resolve_path(&path, worktree,
4421 argv[0]);
4422 if (error)
4423 goto done;
4424 } else {
4425 path = strdup(argv[0]);
4426 if (path == NULL) {
4427 error = got_error_from_errno("strdup");
4428 goto done;
4431 } else if (argc != 0)
4432 usage_log();
4434 if (repo_path == NULL) {
4435 repo_path = worktree ?
4436 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4438 if (repo_path == NULL) {
4439 error = got_error_from_errno("strdup");
4440 goto done;
4443 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4444 if (error != NULL)
4445 goto done;
4447 error = apply_unveil(got_repo_get_path(repo), 1,
4448 worktree ? got_worktree_get_root_path(worktree) : NULL);
4449 if (error)
4450 goto done;
4452 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4453 if (error)
4454 goto done;
4456 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4457 if (error)
4458 goto done;
4460 if (start_commit == NULL) {
4461 struct got_reference *head_ref;
4462 struct got_commit_object *commit = NULL;
4463 error = got_ref_open(&head_ref, repo,
4464 worktree ? got_worktree_get_head_ref_name(worktree)
4465 : GOT_REF_HEAD, 0);
4466 if (error != NULL)
4467 goto done;
4468 error = got_ref_resolve(&start_id, repo, head_ref);
4469 got_ref_close(head_ref);
4470 if (error != NULL)
4471 goto done;
4472 error = got_object_open_as_commit(&commit, repo,
4473 start_id);
4474 if (error != NULL)
4475 goto done;
4476 got_object_commit_close(commit);
4477 } else {
4478 error = got_repo_match_object_id(&start_id, NULL,
4479 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4480 if (error != NULL)
4481 goto done;
4483 if (end_commit != NULL) {
4484 error = got_repo_match_object_id(&end_id, NULL,
4485 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4486 if (error != NULL)
4487 goto done;
4490 if (worktree) {
4492 * If a path was specified on the command line it was resolved
4493 * to a path in the work tree above. Prepend the work tree's
4494 * path prefix to obtain the corresponding in-repository path.
4496 if (path) {
4497 const char *prefix;
4498 prefix = got_worktree_get_path_prefix(worktree);
4499 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4500 (path[0] != '\0') ? "/" : "", path) == -1) {
4501 error = got_error_from_errno("asprintf");
4502 goto done;
4505 } else
4506 error = got_repo_map_path(&in_repo_path, repo,
4507 path ? path : "");
4508 if (error != NULL)
4509 goto done;
4510 if (in_repo_path) {
4511 free(path);
4512 path = in_repo_path;
4515 if (worktree) {
4516 /* Release work tree lock. */
4517 got_worktree_close(worktree);
4518 worktree = NULL;
4521 if (search_pattern && show_patch) {
4522 tmpfile = got_opentemp();
4523 if (tmpfile == NULL) {
4524 error = got_error_from_errno("got_opentemp");
4525 goto done;
4529 error = print_commits(start_id, end_id, repo, path ? path : "",
4530 show_changed_paths, show_patch, search_pattern, diff_context,
4531 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4532 tmpfile);
4533 done:
4534 free(path);
4535 free(repo_path);
4536 free(cwd);
4537 if (worktree)
4538 got_worktree_close(worktree);
4539 if (repo) {
4540 const struct got_error *close_err = got_repo_close(repo);
4541 if (error == NULL)
4542 error = close_err;
4544 if (pack_fds) {
4545 const struct got_error *pack_err =
4546 got_repo_pack_fds_close(pack_fds);
4547 if (error == NULL)
4548 error = pack_err;
4549 pack_fds = NULL;
4551 if (refs_idmap)
4552 got_reflist_object_id_map_free(refs_idmap);
4553 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4554 error = got_error_from_errno("fclose");
4555 got_ref_list_free(&refs);
4556 return error;
4559 __dead static void
4560 usage_diff(void)
4562 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4563 "[-r repository-path] [-s] [-w] [-P] "
4564 "[object1 object2 | path ...]\n", getprogname());
4565 exit(1);
4568 struct print_diff_arg {
4569 struct got_repository *repo;
4570 struct got_worktree *worktree;
4571 int diff_context;
4572 const char *id_str;
4573 int header_shown;
4574 int diff_staged;
4575 int ignore_whitespace;
4576 int force_text_diff;
4580 * Create a file which contains the target path of a symlink so we can feed
4581 * it as content to the diff engine.
4583 static const struct got_error *
4584 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4585 const char *abspath)
4587 const struct got_error *err = NULL;
4588 char target_path[PATH_MAX];
4589 ssize_t target_len, outlen;
4591 *fd = -1;
4593 if (dirfd != -1) {
4594 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4595 if (target_len == -1)
4596 return got_error_from_errno2("readlinkat", abspath);
4597 } else {
4598 target_len = readlink(abspath, target_path, PATH_MAX);
4599 if (target_len == -1)
4600 return got_error_from_errno2("readlink", abspath);
4603 *fd = got_opentempfd();
4604 if (*fd == -1)
4605 return got_error_from_errno("got_opentempfd");
4607 outlen = write(*fd, target_path, target_len);
4608 if (outlen == -1) {
4609 err = got_error_from_errno("got_opentempfd");
4610 goto done;
4613 if (lseek(*fd, 0, SEEK_SET) == -1) {
4614 err = got_error_from_errno2("lseek", abspath);
4615 goto done;
4617 done:
4618 if (err) {
4619 close(*fd);
4620 *fd = -1;
4622 return err;
4625 static const struct got_error *
4626 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4627 const char *path, struct got_object_id *blob_id,
4628 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4629 int dirfd, const char *de_name)
4631 struct print_diff_arg *a = arg;
4632 const struct got_error *err = NULL;
4633 struct got_blob_object *blob1 = NULL;
4634 int fd = -1;
4635 FILE *f1 = NULL, *f2 = NULL;
4636 char *abspath = NULL, *label1 = NULL;
4637 struct stat sb;
4638 off_t size1 = 0;
4640 if (a->diff_staged) {
4641 if (staged_status != GOT_STATUS_MODIFY &&
4642 staged_status != GOT_STATUS_ADD &&
4643 staged_status != GOT_STATUS_DELETE)
4644 return NULL;
4645 } else {
4646 if (staged_status == GOT_STATUS_DELETE)
4647 return NULL;
4648 if (status == GOT_STATUS_NONEXISTENT)
4649 return got_error_set_errno(ENOENT, path);
4650 if (status != GOT_STATUS_MODIFY &&
4651 status != GOT_STATUS_ADD &&
4652 status != GOT_STATUS_DELETE &&
4653 status != GOT_STATUS_CONFLICT)
4654 return NULL;
4657 if (!a->header_shown) {
4658 printf("diff %s %s%s\n", a->id_str,
4659 got_worktree_get_root_path(a->worktree),
4660 a->diff_staged ? " (staged changes)" : "");
4661 a->header_shown = 1;
4664 if (a->diff_staged) {
4665 const char *label1 = NULL, *label2 = NULL;
4666 switch (staged_status) {
4667 case GOT_STATUS_MODIFY:
4668 label1 = path;
4669 label2 = path;
4670 break;
4671 case GOT_STATUS_ADD:
4672 label2 = path;
4673 break;
4674 case GOT_STATUS_DELETE:
4675 label1 = path;
4676 break;
4677 default:
4678 return got_error(GOT_ERR_FILE_STATUS);
4680 f1 = got_opentemp();
4681 if (f1 == NULL) {
4682 err = got_error_from_errno("got_opentemp");
4683 goto done;
4685 f2 = got_opentemp();
4686 if (f2 == NULL) {
4687 err = got_error_from_errno("got_opentemp");
4688 goto done;
4690 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4691 blob_id, staged_blob_id, label1, label2, a->diff_context,
4692 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4693 goto done;
4696 if (staged_status == GOT_STATUS_ADD ||
4697 staged_status == GOT_STATUS_MODIFY) {
4698 char *id_str;
4699 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4700 8192);
4701 if (err)
4702 goto done;
4703 err = got_object_id_str(&id_str, staged_blob_id);
4704 if (err)
4705 goto done;
4706 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4707 err = got_error_from_errno("asprintf");
4708 free(id_str);
4709 goto done;
4711 free(id_str);
4712 } else if (status != GOT_STATUS_ADD) {
4713 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4714 if (err)
4715 goto done;
4718 if (status != GOT_STATUS_DELETE) {
4719 if (asprintf(&abspath, "%s/%s",
4720 got_worktree_get_root_path(a->worktree), path) == -1) {
4721 err = got_error_from_errno("asprintf");
4722 goto done;
4725 if (dirfd != -1) {
4726 fd = openat(dirfd, de_name,
4727 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4728 if (fd == -1) {
4729 if (!got_err_open_nofollow_on_symlink()) {
4730 err = got_error_from_errno2("openat",
4731 abspath);
4732 goto done;
4734 err = get_symlink_target_file(&fd, dirfd,
4735 de_name, abspath);
4736 if (err)
4737 goto done;
4739 } else {
4740 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4741 if (fd == -1) {
4742 if (!got_err_open_nofollow_on_symlink()) {
4743 err = got_error_from_errno2("open",
4744 abspath);
4745 goto done;
4747 err = get_symlink_target_file(&fd, dirfd,
4748 de_name, abspath);
4749 if (err)
4750 goto done;
4753 if (fstat(fd, &sb) == -1) {
4754 err = got_error_from_errno2("fstat", abspath);
4755 goto done;
4757 f2 = fdopen(fd, "r");
4758 if (f2 == NULL) {
4759 err = got_error_from_errno2("fdopen", abspath);
4760 goto done;
4762 fd = -1;
4763 } else
4764 sb.st_size = 0;
4766 if (blob1) {
4767 f1 = got_opentemp();
4768 if (f1 == NULL) {
4769 err = got_error_from_errno("got_opentemp");
4770 goto done;
4772 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4773 blob1);
4774 if (err)
4775 goto done;
4778 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4779 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4780 stdout);
4781 done:
4782 if (blob1)
4783 got_object_blob_close(blob1);
4784 if (f1 && fclose(f1) == EOF && err == NULL)
4785 err = got_error_from_errno("fclose");
4786 if (f2 && fclose(f2) == EOF && err == NULL)
4787 err = got_error_from_errno("fclose");
4788 if (fd != -1 && close(fd) == -1 && err == NULL)
4789 err = got_error_from_errno("close");
4790 free(abspath);
4791 return err;
4794 static const struct got_error *
4795 cmd_diff(int argc, char *argv[])
4797 const struct got_error *error;
4798 struct got_repository *repo = NULL;
4799 struct got_worktree *worktree = NULL;
4800 char *cwd = NULL, *repo_path = NULL;
4801 const char *commit_args[2] = { NULL, NULL };
4802 int ncommit_args = 0;
4803 struct got_object_id *ids[2] = { NULL, NULL };
4804 char *labels[2] = { NULL, NULL };
4805 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4806 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4807 int force_text_diff = 0, force_path = 0, rflag = 0;
4808 const char *errstr;
4809 struct got_reflist_head refs;
4810 struct got_pathlist_head paths;
4811 struct got_pathlist_entry *pe;
4812 FILE *f1 = NULL, *f2 = NULL;
4813 int *pack_fds = NULL;
4815 TAILQ_INIT(&refs);
4816 TAILQ_INIT(&paths);
4818 #ifndef PROFILE
4819 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4820 NULL) == -1)
4821 err(1, "pledge");
4822 #endif
4824 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4825 switch (ch) {
4826 case 'a':
4827 force_text_diff = 1;
4828 break;
4829 case 'c':
4830 if (ncommit_args >= 2)
4831 errx(1, "too many -c options used");
4832 commit_args[ncommit_args++] = optarg;
4833 break;
4834 case 'C':
4835 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4836 &errstr);
4837 if (errstr != NULL)
4838 errx(1, "number of context lines is %s: %s",
4839 errstr, optarg);
4840 break;
4841 case 'r':
4842 repo_path = realpath(optarg, NULL);
4843 if (repo_path == NULL)
4844 return got_error_from_errno2("realpath",
4845 optarg);
4846 got_path_strip_trailing_slashes(repo_path);
4847 rflag = 1;
4848 break;
4849 case 's':
4850 diff_staged = 1;
4851 break;
4852 case 'w':
4853 ignore_whitespace = 1;
4854 break;
4855 case 'P':
4856 force_path = 1;
4857 break;
4858 default:
4859 usage_diff();
4860 /* NOTREACHED */
4864 argc -= optind;
4865 argv += optind;
4867 cwd = getcwd(NULL, 0);
4868 if (cwd == NULL) {
4869 error = got_error_from_errno("getcwd");
4870 goto done;
4873 error = got_repo_pack_fds_open(&pack_fds);
4874 if (error != NULL)
4875 goto done;
4877 if (repo_path == NULL) {
4878 error = got_worktree_open(&worktree, cwd);
4879 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4880 goto done;
4881 else
4882 error = NULL;
4883 if (worktree) {
4884 repo_path =
4885 strdup(got_worktree_get_repo_path(worktree));
4886 if (repo_path == NULL) {
4887 error = got_error_from_errno("strdup");
4888 goto done;
4890 } else {
4891 repo_path = strdup(cwd);
4892 if (repo_path == NULL) {
4893 error = got_error_from_errno("strdup");
4894 goto done;
4899 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4900 free(repo_path);
4901 if (error != NULL)
4902 goto done;
4904 if (rflag || worktree == NULL || ncommit_args > 0) {
4905 if (force_path) {
4906 error = got_error_msg(GOT_ERR_NOT_IMPL,
4907 "-P option can only be used when diffing "
4908 "a work tree");
4909 goto done;
4911 if (diff_staged) {
4912 error = got_error_msg(GOT_ERR_NOT_IMPL,
4913 "-s option can only be used when diffing "
4914 "a work tree");
4915 goto done;
4919 error = apply_unveil(got_repo_get_path(repo), 1,
4920 worktree ? got_worktree_get_root_path(worktree) : NULL);
4921 if (error)
4922 goto done;
4924 if ((!force_path && argc == 2) || ncommit_args > 0) {
4925 int obj_type = (ncommit_args > 0 ?
4926 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4927 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4928 NULL);
4929 if (error)
4930 goto done;
4931 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4932 const char *arg;
4933 if (ncommit_args > 0)
4934 arg = commit_args[i];
4935 else
4936 arg = argv[i];
4937 error = got_repo_match_object_id(&ids[i], &labels[i],
4938 arg, obj_type, &refs, repo);
4939 if (error) {
4940 if (error->code != GOT_ERR_NOT_REF &&
4941 error->code != GOT_ERR_NO_OBJ)
4942 goto done;
4943 if (ncommit_args > 0)
4944 goto done;
4945 error = NULL;
4946 break;
4951 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4952 struct print_diff_arg arg;
4953 char *id_str;
4955 if (worktree == NULL) {
4956 if (argc == 2 && ids[0] == NULL) {
4957 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4958 goto done;
4959 } else if (argc == 2 && ids[1] == NULL) {
4960 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4961 goto done;
4962 } else if (argc > 0) {
4963 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4964 "%s", "specified paths cannot be resolved");
4965 goto done;
4966 } else {
4967 error = got_error(GOT_ERR_NOT_WORKTREE);
4968 goto done;
4972 error = get_worktree_paths_from_argv(&paths, argc, argv,
4973 worktree);
4974 if (error)
4975 goto done;
4977 error = got_object_id_str(&id_str,
4978 got_worktree_get_base_commit_id(worktree));
4979 if (error)
4980 goto done;
4981 arg.repo = repo;
4982 arg.worktree = worktree;
4983 arg.diff_context = diff_context;
4984 arg.id_str = id_str;
4985 arg.header_shown = 0;
4986 arg.diff_staged = diff_staged;
4987 arg.ignore_whitespace = ignore_whitespace;
4988 arg.force_text_diff = force_text_diff;
4990 error = got_worktree_status(worktree, &paths, repo, 0,
4991 print_diff, &arg, check_cancelled, NULL);
4992 free(id_str);
4993 goto done;
4996 if (ncommit_args == 1) {
4997 struct got_commit_object *commit;
4998 error = got_object_open_as_commit(&commit, repo, ids[0]);
4999 if (error)
5000 goto done;
5002 labels[1] = labels[0];
5003 ids[1] = ids[0];
5004 if (got_object_commit_get_nparents(commit) > 0) {
5005 const struct got_object_id_queue *pids;
5006 struct got_object_qid *pid;
5007 pids = got_object_commit_get_parent_ids(commit);
5008 pid = STAILQ_FIRST(pids);
5009 ids[0] = got_object_id_dup(&pid->id);
5010 if (ids[0] == NULL) {
5011 error = got_error_from_errno(
5012 "got_object_id_dup");
5013 got_object_commit_close(commit);
5014 goto done;
5016 error = got_object_id_str(&labels[0], ids[0]);
5017 if (error) {
5018 got_object_commit_close(commit);
5019 goto done;
5021 } else {
5022 ids[0] = NULL;
5023 labels[0] = strdup("/dev/null");
5024 if (labels[0] == NULL) {
5025 error = got_error_from_errno("strdup");
5026 got_object_commit_close(commit);
5027 goto done;
5031 got_object_commit_close(commit);
5034 if (ncommit_args == 0 && argc > 2) {
5035 error = got_error_msg(GOT_ERR_BAD_PATH,
5036 "path arguments cannot be used when diffing two objects");
5037 goto done;
5040 if (ids[0]) {
5041 error = got_object_get_type(&type1, repo, ids[0]);
5042 if (error)
5043 goto done;
5046 error = got_object_get_type(&type2, repo, ids[1]);
5047 if (error)
5048 goto done;
5049 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5050 error = got_error(GOT_ERR_OBJ_TYPE);
5051 goto done;
5053 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5054 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5055 "path arguments cannot be used when diffing blobs");
5056 goto done;
5059 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5060 char *in_repo_path;
5061 struct got_pathlist_entry *new;
5062 if (worktree) {
5063 const char *prefix;
5064 char *p;
5065 error = got_worktree_resolve_path(&p, worktree,
5066 argv[i]);
5067 if (error)
5068 goto done;
5069 prefix = got_worktree_get_path_prefix(worktree);
5070 while (prefix[0] == '/')
5071 prefix++;
5072 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5073 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5074 p) == -1) {
5075 error = got_error_from_errno("asprintf");
5076 free(p);
5077 goto done;
5079 free(p);
5080 } else {
5081 char *mapped_path, *s;
5082 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5083 if (error)
5084 goto done;
5085 s = mapped_path;
5086 while (s[0] == '/')
5087 s++;
5088 in_repo_path = strdup(s);
5089 if (in_repo_path == NULL) {
5090 error = got_error_from_errno("asprintf");
5091 free(mapped_path);
5092 goto done;
5094 free(mapped_path);
5097 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5098 if (error || new == NULL /* duplicate */)
5099 free(in_repo_path);
5100 if (error)
5101 goto done;
5104 if (worktree) {
5105 /* Release work tree lock. */
5106 got_worktree_close(worktree);
5107 worktree = NULL;
5110 f1 = got_opentemp();
5111 if (f1 == NULL) {
5112 error = got_error_from_errno("got_opentemp");
5113 goto done;
5116 f2 = got_opentemp();
5117 if (f2 == NULL) {
5118 error = got_error_from_errno("got_opentemp");
5119 goto done;
5122 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5123 case GOT_OBJ_TYPE_BLOB:
5124 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5125 ids[0], ids[1], NULL, NULL, diff_context,
5126 ignore_whitespace, force_text_diff, repo, stdout);
5127 break;
5128 case GOT_OBJ_TYPE_TREE:
5129 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5130 ids[0], ids[1], &paths, "", "", diff_context,
5131 ignore_whitespace, force_text_diff, repo, stdout);
5132 break;
5133 case GOT_OBJ_TYPE_COMMIT:
5134 printf("diff %s %s\n", labels[0], labels[1]);
5135 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5136 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5137 force_text_diff, repo, stdout);
5138 break;
5139 default:
5140 error = got_error(GOT_ERR_OBJ_TYPE);
5142 done:
5143 free(labels[0]);
5144 free(labels[1]);
5145 free(ids[0]);
5146 free(ids[1]);
5147 if (worktree)
5148 got_worktree_close(worktree);
5149 if (repo) {
5150 const struct got_error *close_err = got_repo_close(repo);
5151 if (error == NULL)
5152 error = close_err;
5154 if (pack_fds) {
5155 const struct got_error *pack_err =
5156 got_repo_pack_fds_close(pack_fds);
5157 if (error == NULL)
5158 error = pack_err;
5159 pack_fds = NULL;
5161 TAILQ_FOREACH(pe, &paths, entry)
5162 free((char *)pe->path);
5163 got_pathlist_free(&paths);
5164 got_ref_list_free(&refs);
5165 if (f1 && fclose(f1) == EOF && error == NULL)
5166 error = got_error_from_errno("fclose");
5167 if (f2 && fclose(f2) == EOF && error == NULL)
5168 error = got_error_from_errno("fclose");
5169 return error;
5172 __dead static void
5173 usage_blame(void)
5175 fprintf(stderr,
5176 "usage: %s blame [-c commit] [-r repository-path] path\n",
5177 getprogname());
5178 exit(1);
5181 struct blame_line {
5182 int annotated;
5183 char *id_str;
5184 char *committer;
5185 char datebuf[11]; /* YYYY-MM-DD + NUL */
5188 struct blame_cb_args {
5189 struct blame_line *lines;
5190 int nlines;
5191 int nlines_prec;
5192 int lineno_cur;
5193 off_t *line_offsets;
5194 FILE *f;
5195 struct got_repository *repo;
5198 static const struct got_error *
5199 blame_cb(void *arg, int nlines, int lineno,
5200 struct got_commit_object *commit, struct got_object_id *id)
5202 const struct got_error *err = NULL;
5203 struct blame_cb_args *a = arg;
5204 struct blame_line *bline;
5205 char *line = NULL;
5206 size_t linesize = 0;
5207 off_t offset;
5208 struct tm tm;
5209 time_t committer_time;
5211 if (nlines != a->nlines ||
5212 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5213 return got_error(GOT_ERR_RANGE);
5215 if (sigint_received)
5216 return got_error(GOT_ERR_ITER_COMPLETED);
5218 if (lineno == -1)
5219 return NULL; /* no change in this commit */
5221 /* Annotate this line. */
5222 bline = &a->lines[lineno - 1];
5223 if (bline->annotated)
5224 return NULL;
5225 err = got_object_id_str(&bline->id_str, id);
5226 if (err)
5227 return err;
5229 bline->committer = strdup(got_object_commit_get_committer(commit));
5230 if (bline->committer == NULL) {
5231 err = got_error_from_errno("strdup");
5232 goto done;
5235 committer_time = got_object_commit_get_committer_time(commit);
5236 if (gmtime_r(&committer_time, &tm) == NULL)
5237 return got_error_from_errno("gmtime_r");
5238 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5239 &tm) == 0) {
5240 err = got_error(GOT_ERR_NO_SPACE);
5241 goto done;
5243 bline->annotated = 1;
5245 /* Print lines annotated so far. */
5246 bline = &a->lines[a->lineno_cur - 1];
5247 if (!bline->annotated)
5248 goto done;
5250 offset = a->line_offsets[a->lineno_cur - 1];
5251 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5252 err = got_error_from_errno("fseeko");
5253 goto done;
5256 while (bline->annotated) {
5257 char *smallerthan, *at, *nl, *committer;
5258 size_t len;
5260 if (getline(&line, &linesize, a->f) == -1) {
5261 if (ferror(a->f))
5262 err = got_error_from_errno("getline");
5263 break;
5266 committer = bline->committer;
5267 smallerthan = strchr(committer, '<');
5268 if (smallerthan && smallerthan[1] != '\0')
5269 committer = smallerthan + 1;
5270 at = strchr(committer, '@');
5271 if (at)
5272 *at = '\0';
5273 len = strlen(committer);
5274 if (len >= 9)
5275 committer[8] = '\0';
5277 nl = strchr(line, '\n');
5278 if (nl)
5279 *nl = '\0';
5280 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5281 bline->id_str, bline->datebuf, committer, line);
5283 a->lineno_cur++;
5284 bline = &a->lines[a->lineno_cur - 1];
5286 done:
5287 free(line);
5288 return err;
5291 static const struct got_error *
5292 cmd_blame(int argc, char *argv[])
5294 const struct got_error *error;
5295 struct got_repository *repo = NULL;
5296 struct got_worktree *worktree = NULL;
5297 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5298 char *link_target = NULL;
5299 struct got_object_id *obj_id = NULL;
5300 struct got_object_id *commit_id = NULL;
5301 struct got_commit_object *commit = NULL;
5302 struct got_blob_object *blob = NULL;
5303 char *commit_id_str = NULL;
5304 struct blame_cb_args bca;
5305 int ch, obj_type, i;
5306 off_t filesize;
5307 int *pack_fds = NULL;
5309 memset(&bca, 0, sizeof(bca));
5311 #ifndef PROFILE
5312 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5313 NULL) == -1)
5314 err(1, "pledge");
5315 #endif
5317 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5318 switch (ch) {
5319 case 'c':
5320 commit_id_str = optarg;
5321 break;
5322 case 'r':
5323 repo_path = realpath(optarg, NULL);
5324 if (repo_path == NULL)
5325 return got_error_from_errno2("realpath",
5326 optarg);
5327 got_path_strip_trailing_slashes(repo_path);
5328 break;
5329 default:
5330 usage_blame();
5331 /* NOTREACHED */
5335 argc -= optind;
5336 argv += optind;
5338 if (argc == 1)
5339 path = argv[0];
5340 else
5341 usage_blame();
5343 cwd = getcwd(NULL, 0);
5344 if (cwd == NULL) {
5345 error = got_error_from_errno("getcwd");
5346 goto done;
5349 error = got_repo_pack_fds_open(&pack_fds);
5350 if (error != NULL)
5351 goto done;
5353 if (repo_path == NULL) {
5354 error = got_worktree_open(&worktree, cwd);
5355 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5356 goto done;
5357 else
5358 error = NULL;
5359 if (worktree) {
5360 repo_path =
5361 strdup(got_worktree_get_repo_path(worktree));
5362 if (repo_path == NULL) {
5363 error = got_error_from_errno("strdup");
5364 if (error)
5365 goto done;
5367 } else {
5368 repo_path = strdup(cwd);
5369 if (repo_path == NULL) {
5370 error = got_error_from_errno("strdup");
5371 goto done;
5376 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5377 if (error != NULL)
5378 goto done;
5380 if (worktree) {
5381 const char *prefix = got_worktree_get_path_prefix(worktree);
5382 char *p;
5384 error = got_worktree_resolve_path(&p, worktree, path);
5385 if (error)
5386 goto done;
5387 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5388 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5389 p) == -1) {
5390 error = got_error_from_errno("asprintf");
5391 free(p);
5392 goto done;
5394 free(p);
5395 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5396 } else {
5397 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5398 if (error)
5399 goto done;
5400 error = got_repo_map_path(&in_repo_path, repo, path);
5402 if (error)
5403 goto done;
5405 if (commit_id_str == NULL) {
5406 struct got_reference *head_ref;
5407 error = got_ref_open(&head_ref, repo, worktree ?
5408 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5409 if (error != NULL)
5410 goto done;
5411 error = got_ref_resolve(&commit_id, repo, head_ref);
5412 got_ref_close(head_ref);
5413 if (error != NULL)
5414 goto done;
5415 } else {
5416 struct got_reflist_head refs;
5417 TAILQ_INIT(&refs);
5418 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5419 NULL);
5420 if (error)
5421 goto done;
5422 error = got_repo_match_object_id(&commit_id, NULL,
5423 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5424 got_ref_list_free(&refs);
5425 if (error)
5426 goto done;
5429 if (worktree) {
5430 /* Release work tree lock. */
5431 got_worktree_close(worktree);
5432 worktree = NULL;
5435 error = got_object_open_as_commit(&commit, repo, commit_id);
5436 if (error)
5437 goto done;
5439 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5440 commit, repo);
5441 if (error)
5442 goto done;
5444 error = got_object_id_by_path(&obj_id, repo, commit,
5445 link_target ? link_target : in_repo_path);
5446 if (error)
5447 goto done;
5449 error = got_object_get_type(&obj_type, repo, obj_id);
5450 if (error)
5451 goto done;
5453 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5454 error = got_error_path(link_target ? link_target : in_repo_path,
5455 GOT_ERR_OBJ_TYPE);
5456 goto done;
5459 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5460 if (error)
5461 goto done;
5462 bca.f = got_opentemp();
5463 if (bca.f == NULL) {
5464 error = got_error_from_errno("got_opentemp");
5465 goto done;
5467 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5468 &bca.line_offsets, bca.f, blob);
5469 if (error || bca.nlines == 0)
5470 goto done;
5472 /* Don't include \n at EOF in the blame line count. */
5473 if (bca.line_offsets[bca.nlines - 1] == filesize)
5474 bca.nlines--;
5476 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5477 if (bca.lines == NULL) {
5478 error = got_error_from_errno("calloc");
5479 goto done;
5481 bca.lineno_cur = 1;
5482 bca.nlines_prec = 0;
5483 i = bca.nlines;
5484 while (i > 0) {
5485 i /= 10;
5486 bca.nlines_prec++;
5488 bca.repo = repo;
5490 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5491 repo, blame_cb, &bca, check_cancelled, NULL);
5492 done:
5493 free(in_repo_path);
5494 free(link_target);
5495 free(repo_path);
5496 free(cwd);
5497 free(commit_id);
5498 free(obj_id);
5499 if (commit)
5500 got_object_commit_close(commit);
5501 if (blob)
5502 got_object_blob_close(blob);
5503 if (worktree)
5504 got_worktree_close(worktree);
5505 if (repo) {
5506 const struct got_error *close_err = got_repo_close(repo);
5507 if (error == NULL)
5508 error = close_err;
5510 if (pack_fds) {
5511 const struct got_error *pack_err =
5512 got_repo_pack_fds_close(pack_fds);
5513 if (error == NULL)
5514 error = pack_err;
5515 pack_fds = NULL;
5517 if (bca.lines) {
5518 for (i = 0; i < bca.nlines; i++) {
5519 struct blame_line *bline = &bca.lines[i];
5520 free(bline->id_str);
5521 free(bline->committer);
5523 free(bca.lines);
5525 free(bca.line_offsets);
5526 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5527 error = got_error_from_errno("fclose");
5528 return error;
5531 __dead static void
5532 usage_tree(void)
5534 fprintf(stderr,
5535 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5536 getprogname());
5537 exit(1);
5540 static const struct got_error *
5541 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5542 const char *root_path, struct got_repository *repo)
5544 const struct got_error *err = NULL;
5545 int is_root_path = (strcmp(path, root_path) == 0);
5546 const char *modestr = "";
5547 mode_t mode = got_tree_entry_get_mode(te);
5548 char *link_target = NULL;
5550 path += strlen(root_path);
5551 while (path[0] == '/')
5552 path++;
5554 if (got_object_tree_entry_is_submodule(te))
5555 modestr = "$";
5556 else if (S_ISLNK(mode)) {
5557 int i;
5559 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5560 if (err)
5561 return err;
5562 for (i = 0; i < strlen(link_target); i++) {
5563 if (!isprint((unsigned char)link_target[i]))
5564 link_target[i] = '?';
5567 modestr = "@";
5569 else if (S_ISDIR(mode))
5570 modestr = "/";
5571 else if (mode & S_IXUSR)
5572 modestr = "*";
5574 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5575 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5576 link_target ? " -> ": "", link_target ? link_target : "");
5578 free(link_target);
5579 return NULL;
5582 static const struct got_error *
5583 print_tree(const char *path, struct got_commit_object *commit,
5584 int show_ids, int recurse, const char *root_path,
5585 struct got_repository *repo)
5587 const struct got_error *err = NULL;
5588 struct got_object_id *tree_id = NULL;
5589 struct got_tree_object *tree = NULL;
5590 int nentries, i;
5592 err = got_object_id_by_path(&tree_id, repo, commit, path);
5593 if (err)
5594 goto done;
5596 err = got_object_open_as_tree(&tree, repo, tree_id);
5597 if (err)
5598 goto done;
5599 nentries = got_object_tree_get_nentries(tree);
5600 for (i = 0; i < nentries; i++) {
5601 struct got_tree_entry *te;
5602 char *id = NULL;
5604 if (sigint_received || sigpipe_received)
5605 break;
5607 te = got_object_tree_get_entry(tree, i);
5608 if (show_ids) {
5609 char *id_str;
5610 err = got_object_id_str(&id_str,
5611 got_tree_entry_get_id(te));
5612 if (err)
5613 goto done;
5614 if (asprintf(&id, "%s ", id_str) == -1) {
5615 err = got_error_from_errno("asprintf");
5616 free(id_str);
5617 goto done;
5619 free(id_str);
5621 err = print_entry(te, id, path, root_path, repo);
5622 free(id);
5623 if (err)
5624 goto done;
5626 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5627 char *child_path;
5628 if (asprintf(&child_path, "%s%s%s", path,
5629 path[0] == '/' && path[1] == '\0' ? "" : "/",
5630 got_tree_entry_get_name(te)) == -1) {
5631 err = got_error_from_errno("asprintf");
5632 goto done;
5634 err = print_tree(child_path, commit, show_ids, 1,
5635 root_path, repo);
5636 free(child_path);
5637 if (err)
5638 goto done;
5641 done:
5642 if (tree)
5643 got_object_tree_close(tree);
5644 free(tree_id);
5645 return err;
5648 static const struct got_error *
5649 cmd_tree(int argc, char *argv[])
5651 const struct got_error *error;
5652 struct got_repository *repo = NULL;
5653 struct got_worktree *worktree = NULL;
5654 const char *path, *refname = NULL;
5655 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5656 struct got_object_id *commit_id = NULL;
5657 struct got_commit_object *commit = NULL;
5658 char *commit_id_str = NULL;
5659 int show_ids = 0, recurse = 0;
5660 int ch;
5661 int *pack_fds = NULL;
5663 #ifndef PROFILE
5664 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5665 NULL) == -1)
5666 err(1, "pledge");
5667 #endif
5669 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5670 switch (ch) {
5671 case 'c':
5672 commit_id_str = optarg;
5673 break;
5674 case 'r':
5675 repo_path = realpath(optarg, NULL);
5676 if (repo_path == NULL)
5677 return got_error_from_errno2("realpath",
5678 optarg);
5679 got_path_strip_trailing_slashes(repo_path);
5680 break;
5681 case 'i':
5682 show_ids = 1;
5683 break;
5684 case 'R':
5685 recurse = 1;
5686 break;
5687 default:
5688 usage_tree();
5689 /* NOTREACHED */
5693 argc -= optind;
5694 argv += optind;
5696 if (argc == 1)
5697 path = argv[0];
5698 else if (argc > 1)
5699 usage_tree();
5700 else
5701 path = NULL;
5703 cwd = getcwd(NULL, 0);
5704 if (cwd == NULL) {
5705 error = got_error_from_errno("getcwd");
5706 goto done;
5709 error = got_repo_pack_fds_open(&pack_fds);
5710 if (error != NULL)
5711 goto done;
5713 if (repo_path == NULL) {
5714 error = got_worktree_open(&worktree, cwd);
5715 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5716 goto done;
5717 else
5718 error = NULL;
5719 if (worktree) {
5720 repo_path =
5721 strdup(got_worktree_get_repo_path(worktree));
5722 if (repo_path == NULL)
5723 error = got_error_from_errno("strdup");
5724 if (error)
5725 goto done;
5726 } else {
5727 repo_path = strdup(cwd);
5728 if (repo_path == NULL) {
5729 error = got_error_from_errno("strdup");
5730 goto done;
5735 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5736 if (error != NULL)
5737 goto done;
5739 if (worktree) {
5740 const char *prefix = got_worktree_get_path_prefix(worktree);
5741 char *p;
5743 if (path == NULL)
5744 path = "";
5745 error = got_worktree_resolve_path(&p, worktree, path);
5746 if (error)
5747 goto done;
5748 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5749 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5750 p) == -1) {
5751 error = got_error_from_errno("asprintf");
5752 free(p);
5753 goto done;
5755 free(p);
5756 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5757 if (error)
5758 goto done;
5759 } else {
5760 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5761 if (error)
5762 goto done;
5763 if (path == NULL)
5764 path = "/";
5765 error = got_repo_map_path(&in_repo_path, repo, path);
5766 if (error != NULL)
5767 goto done;
5770 if (commit_id_str == NULL) {
5771 struct got_reference *head_ref;
5772 if (worktree)
5773 refname = got_worktree_get_head_ref_name(worktree);
5774 else
5775 refname = GOT_REF_HEAD;
5776 error = got_ref_open(&head_ref, repo, refname, 0);
5777 if (error != NULL)
5778 goto done;
5779 error = got_ref_resolve(&commit_id, repo, head_ref);
5780 got_ref_close(head_ref);
5781 if (error != NULL)
5782 goto done;
5783 } else {
5784 struct got_reflist_head refs;
5785 TAILQ_INIT(&refs);
5786 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5787 NULL);
5788 if (error)
5789 goto done;
5790 error = got_repo_match_object_id(&commit_id, NULL,
5791 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5792 got_ref_list_free(&refs);
5793 if (error)
5794 goto done;
5797 if (worktree) {
5798 /* Release work tree lock. */
5799 got_worktree_close(worktree);
5800 worktree = NULL;
5803 error = got_object_open_as_commit(&commit, repo, commit_id);
5804 if (error)
5805 goto done;
5807 error = print_tree(in_repo_path, commit, show_ids, recurse,
5808 in_repo_path, repo);
5809 done:
5810 free(in_repo_path);
5811 free(repo_path);
5812 free(cwd);
5813 free(commit_id);
5814 if (commit)
5815 got_object_commit_close(commit);
5816 if (worktree)
5817 got_worktree_close(worktree);
5818 if (repo) {
5819 const struct got_error *close_err = got_repo_close(repo);
5820 if (error == NULL)
5821 error = close_err;
5823 if (pack_fds) {
5824 const struct got_error *pack_err =
5825 got_repo_pack_fds_close(pack_fds);
5826 if (error == NULL)
5827 error = pack_err;
5828 pack_fds = NULL;
5830 return error;
5833 __dead static void
5834 usage_status(void)
5836 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5837 "[-S status-codes] [path ...]\n", getprogname());
5838 exit(1);
5841 struct got_status_arg {
5842 char *status_codes;
5843 int suppress;
5846 static const struct got_error *
5847 print_status(void *arg, unsigned char status, unsigned char staged_status,
5848 const char *path, struct got_object_id *blob_id,
5849 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5850 int dirfd, const char *de_name)
5852 struct got_status_arg *st = arg;
5854 if (status == staged_status && (status == GOT_STATUS_DELETE))
5855 status = GOT_STATUS_NO_CHANGE;
5856 if (st != NULL && st->status_codes) {
5857 size_t ncodes = strlen(st->status_codes);
5858 int i, j = 0;
5860 for (i = 0; i < ncodes ; i++) {
5861 if (st->suppress) {
5862 if (status == st->status_codes[i] ||
5863 staged_status == st->status_codes[i]) {
5864 j++;
5865 continue;
5867 } else {
5868 if (status == st->status_codes[i] ||
5869 staged_status == st->status_codes[i])
5870 break;
5874 if (st->suppress && j == 0)
5875 goto print;
5877 if (i == ncodes)
5878 return NULL;
5880 print:
5881 printf("%c%c %s\n", status, staged_status, path);
5882 return NULL;
5885 static const struct got_error *
5886 cmd_status(int argc, char *argv[])
5888 const struct got_error *error = NULL;
5889 struct got_repository *repo = NULL;
5890 struct got_worktree *worktree = NULL;
5891 struct got_status_arg st;
5892 char *cwd = NULL;
5893 struct got_pathlist_head paths;
5894 struct got_pathlist_entry *pe;
5895 int ch, i, no_ignores = 0;
5896 int *pack_fds = NULL;
5898 TAILQ_INIT(&paths);
5900 memset(&st, 0, sizeof(st));
5901 st.status_codes = NULL;
5902 st.suppress = 0;
5904 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5905 switch (ch) {
5906 case 'I':
5907 no_ignores = 1;
5908 break;
5909 case 'S':
5910 if (st.status_codes != NULL && st.suppress == 0)
5911 option_conflict('S', 's');
5912 st.suppress = 1;
5913 /* fallthrough */
5914 case 's':
5915 for (i = 0; i < strlen(optarg); i++) {
5916 switch (optarg[i]) {
5917 case GOT_STATUS_MODIFY:
5918 case GOT_STATUS_ADD:
5919 case GOT_STATUS_DELETE:
5920 case GOT_STATUS_CONFLICT:
5921 case GOT_STATUS_MISSING:
5922 case GOT_STATUS_OBSTRUCTED:
5923 case GOT_STATUS_UNVERSIONED:
5924 case GOT_STATUS_MODE_CHANGE:
5925 case GOT_STATUS_NONEXISTENT:
5926 break;
5927 default:
5928 errx(1, "invalid status code '%c'",
5929 optarg[i]);
5932 if (ch == 's' && st.suppress)
5933 option_conflict('s', 'S');
5934 st.status_codes = optarg;
5935 break;
5936 default:
5937 usage_status();
5938 /* NOTREACHED */
5942 argc -= optind;
5943 argv += optind;
5945 #ifndef PROFILE
5946 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5947 NULL) == -1)
5948 err(1, "pledge");
5949 #endif
5950 cwd = getcwd(NULL, 0);
5951 if (cwd == NULL) {
5952 error = got_error_from_errno("getcwd");
5953 goto done;
5956 error = got_repo_pack_fds_open(&pack_fds);
5957 if (error != NULL)
5958 goto done;
5960 error = got_worktree_open(&worktree, cwd);
5961 if (error) {
5962 if (error->code == GOT_ERR_NOT_WORKTREE)
5963 error = wrap_not_worktree_error(error, "status", cwd);
5964 goto done;
5967 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5968 NULL, pack_fds);
5969 if (error != NULL)
5970 goto done;
5972 error = apply_unveil(got_repo_get_path(repo), 1,
5973 got_worktree_get_root_path(worktree));
5974 if (error)
5975 goto done;
5977 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5978 if (error)
5979 goto done;
5981 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5982 print_status, &st, check_cancelled, NULL);
5983 done:
5984 if (pack_fds) {
5985 const struct got_error *pack_err =
5986 got_repo_pack_fds_close(pack_fds);
5987 if (error == NULL)
5988 error = pack_err;
5989 pack_fds = NULL;
5992 TAILQ_FOREACH(pe, &paths, entry)
5993 free((char *)pe->path);
5994 got_pathlist_free(&paths);
5995 free(cwd);
5996 return error;
5999 __dead static void
6000 usage_ref(void)
6002 fprintf(stderr,
6003 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6004 "[-s reference] [-d] [name]\n",
6005 getprogname());
6006 exit(1);
6009 static const struct got_error *
6010 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6012 static const struct got_error *err = NULL;
6013 struct got_reflist_head refs;
6014 struct got_reflist_entry *re;
6016 TAILQ_INIT(&refs);
6017 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6018 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6019 repo);
6020 if (err)
6021 return err;
6023 TAILQ_FOREACH(re, &refs, entry) {
6024 char *refstr;
6025 refstr = got_ref_to_str(re->ref);
6026 if (refstr == NULL) {
6027 err = got_error_from_errno("got_ref_to_str");
6028 break;
6030 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6031 free(refstr);
6034 got_ref_list_free(&refs);
6035 return err;
6038 static const struct got_error *
6039 delete_ref_by_name(struct got_repository *repo, const char *refname)
6041 const struct got_error *err;
6042 struct got_reference *ref;
6044 err = got_ref_open(&ref, repo, refname, 0);
6045 if (err)
6046 return err;
6048 err = delete_ref(repo, ref);
6049 got_ref_close(ref);
6050 return err;
6053 static const struct got_error *
6054 add_ref(struct got_repository *repo, const char *refname, const char *target)
6056 const struct got_error *err = NULL;
6057 struct got_object_id *id = NULL;
6058 struct got_reference *ref = NULL;
6059 struct got_reflist_head refs;
6062 * Don't let the user create a reference name with a leading '-'.
6063 * While technically a valid reference name, this case is usually
6064 * an unintended typo.
6066 if (refname[0] == '-')
6067 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6069 TAILQ_INIT(&refs);
6070 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6071 if (err)
6072 goto done;
6073 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6074 &refs, repo);
6075 got_ref_list_free(&refs);
6076 if (err)
6077 goto done;
6079 err = got_ref_alloc(&ref, refname, id);
6080 if (err)
6081 goto done;
6083 err = got_ref_write(ref, repo);
6084 done:
6085 if (ref)
6086 got_ref_close(ref);
6087 free(id);
6088 return err;
6091 static const struct got_error *
6092 add_symref(struct got_repository *repo, const char *refname, const char *target)
6094 const struct got_error *err = NULL;
6095 struct got_reference *ref = NULL;
6096 struct got_reference *target_ref = NULL;
6099 * Don't let the user create a reference name with a leading '-'.
6100 * While technically a valid reference name, this case is usually
6101 * an unintended typo.
6103 if (refname[0] == '-')
6104 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6106 err = got_ref_open(&target_ref, repo, target, 0);
6107 if (err)
6108 return err;
6110 err = got_ref_alloc_symref(&ref, refname, target_ref);
6111 if (err)
6112 goto done;
6114 err = got_ref_write(ref, repo);
6115 done:
6116 if (target_ref)
6117 got_ref_close(target_ref);
6118 if (ref)
6119 got_ref_close(ref);
6120 return err;
6123 static const struct got_error *
6124 cmd_ref(int argc, char *argv[])
6126 const struct got_error *error = NULL;
6127 struct got_repository *repo = NULL;
6128 struct got_worktree *worktree = NULL;
6129 char *cwd = NULL, *repo_path = NULL;
6130 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6131 const char *obj_arg = NULL, *symref_target= NULL;
6132 char *refname = NULL;
6133 int *pack_fds = NULL;
6135 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6136 switch (ch) {
6137 case 'c':
6138 obj_arg = optarg;
6139 break;
6140 case 'd':
6141 do_delete = 1;
6142 break;
6143 case 'r':
6144 repo_path = realpath(optarg, NULL);
6145 if (repo_path == NULL)
6146 return got_error_from_errno2("realpath",
6147 optarg);
6148 got_path_strip_trailing_slashes(repo_path);
6149 break;
6150 case 'l':
6151 do_list = 1;
6152 break;
6153 case 's':
6154 symref_target = optarg;
6155 break;
6156 case 't':
6157 sort_by_time = 1;
6158 break;
6159 default:
6160 usage_ref();
6161 /* NOTREACHED */
6165 if (obj_arg && do_list)
6166 option_conflict('c', 'l');
6167 if (obj_arg && do_delete)
6168 option_conflict('c', 'd');
6169 if (obj_arg && symref_target)
6170 option_conflict('c', 's');
6171 if (symref_target && do_delete)
6172 option_conflict('s', 'd');
6173 if (symref_target && do_list)
6174 option_conflict('s', 'l');
6175 if (do_delete && do_list)
6176 option_conflict('d', 'l');
6177 if (sort_by_time && !do_list)
6178 errx(1, "-t option requires -l option");
6180 argc -= optind;
6181 argv += optind;
6183 if (do_list) {
6184 if (argc != 0 && argc != 1)
6185 usage_ref();
6186 if (argc == 1) {
6187 refname = strdup(argv[0]);
6188 if (refname == NULL) {
6189 error = got_error_from_errno("strdup");
6190 goto done;
6193 } else {
6194 if (argc != 1)
6195 usage_ref();
6196 refname = strdup(argv[0]);
6197 if (refname == NULL) {
6198 error = got_error_from_errno("strdup");
6199 goto done;
6203 if (refname)
6204 got_path_strip_trailing_slashes(refname);
6206 #ifndef PROFILE
6207 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6208 "sendfd unveil", NULL) == -1)
6209 err(1, "pledge");
6210 #endif
6211 cwd = getcwd(NULL, 0);
6212 if (cwd == NULL) {
6213 error = got_error_from_errno("getcwd");
6214 goto done;
6217 error = got_repo_pack_fds_open(&pack_fds);
6218 if (error != NULL)
6219 goto done;
6221 if (repo_path == NULL) {
6222 error = got_worktree_open(&worktree, cwd);
6223 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6224 goto done;
6225 else
6226 error = NULL;
6227 if (worktree) {
6228 repo_path =
6229 strdup(got_worktree_get_repo_path(worktree));
6230 if (repo_path == NULL)
6231 error = got_error_from_errno("strdup");
6232 if (error)
6233 goto done;
6234 } else {
6235 repo_path = strdup(cwd);
6236 if (repo_path == NULL) {
6237 error = got_error_from_errno("strdup");
6238 goto done;
6243 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6244 if (error != NULL)
6245 goto done;
6247 #ifndef PROFILE
6248 if (do_list) {
6249 /* Remove "cpath" promise. */
6250 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6251 NULL) == -1)
6252 err(1, "pledge");
6254 #endif
6256 error = apply_unveil(got_repo_get_path(repo), do_list,
6257 worktree ? got_worktree_get_root_path(worktree) : NULL);
6258 if (error)
6259 goto done;
6261 if (do_list)
6262 error = list_refs(repo, refname, sort_by_time);
6263 else if (do_delete)
6264 error = delete_ref_by_name(repo, refname);
6265 else if (symref_target)
6266 error = add_symref(repo, refname, symref_target);
6267 else {
6268 if (obj_arg == NULL)
6269 usage_ref();
6270 error = add_ref(repo, refname, obj_arg);
6272 done:
6273 free(refname);
6274 if (repo) {
6275 const struct got_error *close_err = got_repo_close(repo);
6276 if (error == NULL)
6277 error = close_err;
6279 if (worktree)
6280 got_worktree_close(worktree);
6281 if (pack_fds) {
6282 const struct got_error *pack_err =
6283 got_repo_pack_fds_close(pack_fds);
6284 if (error == NULL)
6285 error = pack_err;
6286 pack_fds = NULL;
6288 free(cwd);
6289 free(repo_path);
6290 return error;
6293 __dead static void
6294 usage_branch(void)
6296 fprintf(stderr,
6297 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6298 "[-n] [name]\n", getprogname());
6299 exit(1);
6302 static const struct got_error *
6303 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6304 struct got_reference *ref)
6306 const struct got_error *err = NULL;
6307 const char *refname, *marker = " ";
6308 char *refstr;
6310 refname = got_ref_get_name(ref);
6311 if (worktree && strcmp(refname,
6312 got_worktree_get_head_ref_name(worktree)) == 0) {
6313 struct got_object_id *id = NULL;
6315 err = got_ref_resolve(&id, repo, ref);
6316 if (err)
6317 return err;
6318 if (got_object_id_cmp(id,
6319 got_worktree_get_base_commit_id(worktree)) == 0)
6320 marker = "* ";
6321 else
6322 marker = "~ ";
6323 free(id);
6326 if (strncmp(refname, "refs/heads/", 11) == 0)
6327 refname += 11;
6328 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6329 refname += 18;
6330 if (strncmp(refname, "refs/remotes/", 13) == 0)
6331 refname += 13;
6333 refstr = got_ref_to_str(ref);
6334 if (refstr == NULL)
6335 return got_error_from_errno("got_ref_to_str");
6337 printf("%s%s: %s\n", marker, refname, refstr);
6338 free(refstr);
6339 return NULL;
6342 static const struct got_error *
6343 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6345 const char *refname;
6347 if (worktree == NULL)
6348 return got_error(GOT_ERR_NOT_WORKTREE);
6350 refname = got_worktree_get_head_ref_name(worktree);
6352 if (strncmp(refname, "refs/heads/", 11) == 0)
6353 refname += 11;
6354 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6355 refname += 18;
6357 printf("%s\n", refname);
6359 return NULL;
6362 static const struct got_error *
6363 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6364 int sort_by_time)
6366 static const struct got_error *err = NULL;
6367 struct got_reflist_head refs;
6368 struct got_reflist_entry *re;
6369 struct got_reference *temp_ref = NULL;
6370 int rebase_in_progress, histedit_in_progress;
6372 TAILQ_INIT(&refs);
6374 if (worktree) {
6375 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6376 worktree);
6377 if (err)
6378 return err;
6380 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6381 worktree);
6382 if (err)
6383 return err;
6385 if (rebase_in_progress || histedit_in_progress) {
6386 err = got_ref_open(&temp_ref, repo,
6387 got_worktree_get_head_ref_name(worktree), 0);
6388 if (err)
6389 return err;
6390 list_branch(repo, worktree, temp_ref);
6391 got_ref_close(temp_ref);
6395 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6396 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6397 repo);
6398 if (err)
6399 return err;
6401 TAILQ_FOREACH(re, &refs, entry)
6402 list_branch(repo, worktree, re->ref);
6404 got_ref_list_free(&refs);
6406 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6407 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6408 repo);
6409 if (err)
6410 return err;
6412 TAILQ_FOREACH(re, &refs, entry)
6413 list_branch(repo, worktree, re->ref);
6415 got_ref_list_free(&refs);
6417 return NULL;
6420 static const struct got_error *
6421 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6422 const char *branch_name)
6424 const struct got_error *err = NULL;
6425 struct got_reference *ref = NULL;
6426 char *refname, *remote_refname = NULL;
6428 if (strncmp(branch_name, "refs/", 5) == 0)
6429 branch_name += 5;
6430 if (strncmp(branch_name, "heads/", 6) == 0)
6431 branch_name += 6;
6432 else if (strncmp(branch_name, "remotes/", 8) == 0)
6433 branch_name += 8;
6435 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6436 return got_error_from_errno("asprintf");
6438 if (asprintf(&remote_refname, "refs/remotes/%s",
6439 branch_name) == -1) {
6440 err = got_error_from_errno("asprintf");
6441 goto done;
6444 err = got_ref_open(&ref, repo, refname, 0);
6445 if (err) {
6446 const struct got_error *err2;
6447 if (err->code != GOT_ERR_NOT_REF)
6448 goto done;
6450 * Keep 'err' intact such that if neither branch exists
6451 * we report "refs/heads" rather than "refs/remotes" in
6452 * our error message.
6454 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6455 if (err2)
6456 goto done;
6457 err = NULL;
6460 if (worktree &&
6461 strcmp(got_worktree_get_head_ref_name(worktree),
6462 got_ref_get_name(ref)) == 0) {
6463 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6464 "will not delete this work tree's current branch");
6465 goto done;
6468 err = delete_ref(repo, ref);
6469 done:
6470 if (ref)
6471 got_ref_close(ref);
6472 free(refname);
6473 free(remote_refname);
6474 return err;
6477 static const struct got_error *
6478 add_branch(struct got_repository *repo, const char *branch_name,
6479 struct got_object_id *base_commit_id)
6481 const struct got_error *err = NULL;
6482 struct got_reference *ref = NULL;
6483 char *base_refname = NULL, *refname = NULL;
6486 * Don't let the user create a branch name with a leading '-'.
6487 * While technically a valid reference name, this case is usually
6488 * an unintended typo.
6490 if (branch_name[0] == '-')
6491 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6493 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6494 branch_name += 11;
6496 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6497 err = got_error_from_errno("asprintf");
6498 goto done;
6501 err = got_ref_open(&ref, repo, refname, 0);
6502 if (err == NULL) {
6503 err = got_error(GOT_ERR_BRANCH_EXISTS);
6504 goto done;
6505 } else if (err->code != GOT_ERR_NOT_REF)
6506 goto done;
6508 err = got_ref_alloc(&ref, refname, base_commit_id);
6509 if (err)
6510 goto done;
6512 err = got_ref_write(ref, repo);
6513 done:
6514 if (ref)
6515 got_ref_close(ref);
6516 free(base_refname);
6517 free(refname);
6518 return err;
6521 static const struct got_error *
6522 cmd_branch(int argc, char *argv[])
6524 const struct got_error *error = NULL;
6525 struct got_repository *repo = NULL;
6526 struct got_worktree *worktree = NULL;
6527 char *cwd = NULL, *repo_path = NULL;
6528 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6529 const char *delref = NULL, *commit_id_arg = NULL;
6530 struct got_reference *ref = NULL;
6531 struct got_pathlist_head paths;
6532 struct got_pathlist_entry *pe;
6533 struct got_object_id *commit_id = NULL;
6534 char *commit_id_str = NULL;
6535 int *pack_fds = NULL;
6537 TAILQ_INIT(&paths);
6539 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6540 switch (ch) {
6541 case 'c':
6542 commit_id_arg = optarg;
6543 break;
6544 case 'd':
6545 delref = optarg;
6546 break;
6547 case 'r':
6548 repo_path = realpath(optarg, NULL);
6549 if (repo_path == NULL)
6550 return got_error_from_errno2("realpath",
6551 optarg);
6552 got_path_strip_trailing_slashes(repo_path);
6553 break;
6554 case 'l':
6555 do_list = 1;
6556 break;
6557 case 'n':
6558 do_update = 0;
6559 break;
6560 case 't':
6561 sort_by_time = 1;
6562 break;
6563 default:
6564 usage_branch();
6565 /* NOTREACHED */
6569 if (do_list && delref)
6570 option_conflict('l', 'd');
6571 if (sort_by_time && !do_list)
6572 errx(1, "-t option requires -l option");
6574 argc -= optind;
6575 argv += optind;
6577 if (!do_list && !delref && argc == 0)
6578 do_show = 1;
6580 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6581 errx(1, "-c option can only be used when creating a branch");
6583 if (do_list || delref) {
6584 if (argc > 0)
6585 usage_branch();
6586 } else if (!do_show && argc != 1)
6587 usage_branch();
6589 #ifndef PROFILE
6590 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6591 "sendfd unveil", NULL) == -1)
6592 err(1, "pledge");
6593 #endif
6594 cwd = getcwd(NULL, 0);
6595 if (cwd == NULL) {
6596 error = got_error_from_errno("getcwd");
6597 goto done;
6600 error = got_repo_pack_fds_open(&pack_fds);
6601 if (error != NULL)
6602 goto done;
6604 if (repo_path == NULL) {
6605 error = got_worktree_open(&worktree, cwd);
6606 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6607 goto done;
6608 else
6609 error = NULL;
6610 if (worktree) {
6611 repo_path =
6612 strdup(got_worktree_get_repo_path(worktree));
6613 if (repo_path == NULL)
6614 error = got_error_from_errno("strdup");
6615 if (error)
6616 goto done;
6617 } else {
6618 repo_path = strdup(cwd);
6619 if (repo_path == NULL) {
6620 error = got_error_from_errno("strdup");
6621 goto done;
6626 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6627 if (error != NULL)
6628 goto done;
6630 #ifndef PROFILE
6631 if (do_list || do_show) {
6632 /* Remove "cpath" promise. */
6633 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6634 NULL) == -1)
6635 err(1, "pledge");
6637 #endif
6639 error = apply_unveil(got_repo_get_path(repo), do_list,
6640 worktree ? got_worktree_get_root_path(worktree) : NULL);
6641 if (error)
6642 goto done;
6644 if (do_show)
6645 error = show_current_branch(repo, worktree);
6646 else if (do_list)
6647 error = list_branches(repo, worktree, sort_by_time);
6648 else if (delref)
6649 error = delete_branch(repo, worktree, delref);
6650 else {
6651 struct got_reflist_head refs;
6652 TAILQ_INIT(&refs);
6653 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6654 NULL);
6655 if (error)
6656 goto done;
6657 if (commit_id_arg == NULL)
6658 commit_id_arg = worktree ?
6659 got_worktree_get_head_ref_name(worktree) :
6660 GOT_REF_HEAD;
6661 error = got_repo_match_object_id(&commit_id, NULL,
6662 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6663 got_ref_list_free(&refs);
6664 if (error)
6665 goto done;
6666 error = add_branch(repo, argv[0], commit_id);
6667 if (error)
6668 goto done;
6669 if (worktree && do_update) {
6670 struct got_update_progress_arg upa;
6671 char *branch_refname = NULL;
6673 error = got_object_id_str(&commit_id_str, commit_id);
6674 if (error)
6675 goto done;
6676 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6677 worktree);
6678 if (error)
6679 goto done;
6680 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6681 == -1) {
6682 error = got_error_from_errno("asprintf");
6683 goto done;
6685 error = got_ref_open(&ref, repo, branch_refname, 0);
6686 free(branch_refname);
6687 if (error)
6688 goto done;
6689 error = switch_head_ref(ref, commit_id, worktree,
6690 repo);
6691 if (error)
6692 goto done;
6693 error = got_worktree_set_base_commit_id(worktree, repo,
6694 commit_id);
6695 if (error)
6696 goto done;
6697 memset(&upa, 0, sizeof(upa));
6698 error = got_worktree_checkout_files(worktree, &paths,
6699 repo, update_progress, &upa, check_cancelled,
6700 NULL);
6701 if (error)
6702 goto done;
6703 if (upa.did_something) {
6704 printf("Updated to %s: %s\n",
6705 got_worktree_get_head_ref_name(worktree),
6706 commit_id_str);
6708 print_update_progress_stats(&upa);
6711 done:
6712 if (ref)
6713 got_ref_close(ref);
6714 if (repo) {
6715 const struct got_error *close_err = got_repo_close(repo);
6716 if (error == NULL)
6717 error = close_err;
6719 if (worktree)
6720 got_worktree_close(worktree);
6721 if (pack_fds) {
6722 const struct got_error *pack_err =
6723 got_repo_pack_fds_close(pack_fds);
6724 if (error == NULL)
6725 error = pack_err;
6726 pack_fds = NULL;
6728 free(cwd);
6729 free(repo_path);
6730 free(commit_id);
6731 free(commit_id_str);
6732 TAILQ_FOREACH(pe, &paths, entry)
6733 free((char *)pe->path);
6734 got_pathlist_free(&paths);
6735 return error;
6739 __dead static void
6740 usage_tag(void)
6742 fprintf(stderr,
6743 "usage: %s tag [-c commit] [-r repository] [-l] "
6744 "[-m message] name\n", getprogname());
6745 exit(1);
6748 #if 0
6749 static const struct got_error *
6750 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6752 const struct got_error *err = NULL;
6753 struct got_reflist_entry *re, *se, *new;
6754 struct got_object_id *re_id, *se_id;
6755 struct got_tag_object *re_tag, *se_tag;
6756 time_t re_time, se_time;
6758 STAILQ_FOREACH(re, tags, entry) {
6759 se = STAILQ_FIRST(sorted);
6760 if (se == NULL) {
6761 err = got_reflist_entry_dup(&new, re);
6762 if (err)
6763 return err;
6764 STAILQ_INSERT_HEAD(sorted, new, entry);
6765 continue;
6766 } else {
6767 err = got_ref_resolve(&re_id, repo, re->ref);
6768 if (err)
6769 break;
6770 err = got_object_open_as_tag(&re_tag, repo, re_id);
6771 free(re_id);
6772 if (err)
6773 break;
6774 re_time = got_object_tag_get_tagger_time(re_tag);
6775 got_object_tag_close(re_tag);
6778 while (se) {
6779 err = got_ref_resolve(&se_id, repo, re->ref);
6780 if (err)
6781 break;
6782 err = got_object_open_as_tag(&se_tag, repo, se_id);
6783 free(se_id);
6784 if (err)
6785 break;
6786 se_time = got_object_tag_get_tagger_time(se_tag);
6787 got_object_tag_close(se_tag);
6789 if (se_time > re_time) {
6790 err = got_reflist_entry_dup(&new, re);
6791 if (err)
6792 return err;
6793 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6794 break;
6796 se = STAILQ_NEXT(se, entry);
6797 continue;
6800 done:
6801 return err;
6803 #endif
6805 static const struct got_error *
6806 list_tags(struct got_repository *repo)
6808 static const struct got_error *err = NULL;
6809 struct got_reflist_head refs;
6810 struct got_reflist_entry *re;
6812 TAILQ_INIT(&refs);
6814 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6815 if (err)
6816 return err;
6818 TAILQ_FOREACH(re, &refs, entry) {
6819 const char *refname;
6820 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6821 char datebuf[26];
6822 const char *tagger;
6823 time_t tagger_time;
6824 struct got_object_id *id;
6825 struct got_tag_object *tag;
6826 struct got_commit_object *commit = NULL;
6828 refname = got_ref_get_name(re->ref);
6829 if (strncmp(refname, "refs/tags/", 10) != 0)
6830 continue;
6831 refname += 10;
6832 refstr = got_ref_to_str(re->ref);
6833 if (refstr == NULL) {
6834 err = got_error_from_errno("got_ref_to_str");
6835 break;
6837 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6838 free(refstr);
6840 err = got_ref_resolve(&id, repo, re->ref);
6841 if (err)
6842 break;
6843 err = got_object_open_as_tag(&tag, repo, id);
6844 if (err) {
6845 if (err->code != GOT_ERR_OBJ_TYPE) {
6846 free(id);
6847 break;
6849 /* "lightweight" tag */
6850 err = got_object_open_as_commit(&commit, repo, id);
6851 if (err) {
6852 free(id);
6853 break;
6855 tagger = got_object_commit_get_committer(commit);
6856 tagger_time =
6857 got_object_commit_get_committer_time(commit);
6858 err = got_object_id_str(&id_str, id);
6859 free(id);
6860 if (err)
6861 break;
6862 } else {
6863 free(id);
6864 tagger = got_object_tag_get_tagger(tag);
6865 tagger_time = got_object_tag_get_tagger_time(tag);
6866 err = got_object_id_str(&id_str,
6867 got_object_tag_get_object_id(tag));
6868 if (err)
6869 break;
6871 printf("from: %s\n", tagger);
6872 datestr = get_datestr(&tagger_time, datebuf);
6873 if (datestr)
6874 printf("date: %s UTC\n", datestr);
6875 if (commit)
6876 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6877 else {
6878 switch (got_object_tag_get_object_type(tag)) {
6879 case GOT_OBJ_TYPE_BLOB:
6880 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6881 id_str);
6882 break;
6883 case GOT_OBJ_TYPE_TREE:
6884 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6885 id_str);
6886 break;
6887 case GOT_OBJ_TYPE_COMMIT:
6888 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6889 id_str);
6890 break;
6891 case GOT_OBJ_TYPE_TAG:
6892 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6893 id_str);
6894 break;
6895 default:
6896 break;
6899 free(id_str);
6900 if (commit) {
6901 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6902 if (err)
6903 break;
6904 got_object_commit_close(commit);
6905 } else {
6906 tagmsg0 = strdup(got_object_tag_get_message(tag));
6907 got_object_tag_close(tag);
6908 if (tagmsg0 == NULL) {
6909 err = got_error_from_errno("strdup");
6910 break;
6914 tagmsg = tagmsg0;
6915 do {
6916 line = strsep(&tagmsg, "\n");
6917 if (line)
6918 printf(" %s\n", line);
6919 } while (line);
6920 free(tagmsg0);
6923 got_ref_list_free(&refs);
6924 return NULL;
6927 static const struct got_error *
6928 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6929 const char *tag_name, const char *repo_path)
6931 const struct got_error *err = NULL;
6932 char *template = NULL, *initial_content = NULL;
6933 char *editor = NULL;
6934 int initial_content_len;
6935 int fd = -1;
6937 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6938 err = got_error_from_errno("asprintf");
6939 goto done;
6942 initial_content_len = asprintf(&initial_content,
6943 "\n# tagging commit %s as %s\n",
6944 commit_id_str, tag_name);
6945 if (initial_content_len == -1) {
6946 err = got_error_from_errno("asprintf");
6947 goto done;
6950 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6951 if (err)
6952 goto done;
6954 if (write(fd, initial_content, initial_content_len) == -1) {
6955 err = got_error_from_errno2("write", *tagmsg_path);
6956 goto done;
6959 err = get_editor(&editor);
6960 if (err)
6961 goto done;
6962 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6963 initial_content_len, 1);
6964 done:
6965 free(initial_content);
6966 free(template);
6967 free(editor);
6969 if (fd != -1 && close(fd) == -1 && err == NULL)
6970 err = got_error_from_errno2("close", *tagmsg_path);
6972 /* Editor is done; we can now apply unveil(2) */
6973 if (err == NULL)
6974 err = apply_unveil(repo_path, 0, NULL);
6975 if (err) {
6976 free(*tagmsg);
6977 *tagmsg = NULL;
6979 return err;
6982 static const struct got_error *
6983 add_tag(struct got_repository *repo, const char *tagger,
6984 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6986 const struct got_error *err = NULL;
6987 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6988 char *label = NULL, *commit_id_str = NULL;
6989 struct got_reference *ref = NULL;
6990 char *refname = NULL, *tagmsg = NULL;
6991 char *tagmsg_path = NULL, *tag_id_str = NULL;
6992 int preserve_tagmsg = 0;
6993 struct got_reflist_head refs;
6995 TAILQ_INIT(&refs);
6998 * Don't let the user create a tag name with a leading '-'.
6999 * While technically a valid reference name, this case is usually
7000 * an unintended typo.
7002 if (tag_name[0] == '-')
7003 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7005 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7006 if (err)
7007 goto done;
7009 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7010 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7011 if (err)
7012 goto done;
7014 err = got_object_id_str(&commit_id_str, commit_id);
7015 if (err)
7016 goto done;
7018 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7019 refname = strdup(tag_name);
7020 if (refname == NULL) {
7021 err = got_error_from_errno("strdup");
7022 goto done;
7024 tag_name += 10;
7025 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
7026 err = got_error_from_errno("asprintf");
7027 goto done;
7030 err = got_ref_open(&ref, repo, refname, 0);
7031 if (err == NULL) {
7032 err = got_error(GOT_ERR_TAG_EXISTS);
7033 goto done;
7034 } else if (err->code != GOT_ERR_NOT_REF)
7035 goto done;
7037 if (tagmsg_arg == NULL) {
7038 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7039 tag_name, got_repo_get_path(repo));
7040 if (err) {
7041 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7042 tagmsg_path != NULL)
7043 preserve_tagmsg = 1;
7044 goto done;
7048 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7049 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7050 if (err) {
7051 if (tagmsg_path)
7052 preserve_tagmsg = 1;
7053 goto done;
7056 err = got_ref_alloc(&ref, refname, tag_id);
7057 if (err) {
7058 if (tagmsg_path)
7059 preserve_tagmsg = 1;
7060 goto done;
7063 err = got_ref_write(ref, repo);
7064 if (err) {
7065 if (tagmsg_path)
7066 preserve_tagmsg = 1;
7067 goto done;
7070 err = got_object_id_str(&tag_id_str, tag_id);
7071 if (err) {
7072 if (tagmsg_path)
7073 preserve_tagmsg = 1;
7074 goto done;
7076 printf("Created tag %s\n", tag_id_str);
7077 done:
7078 if (preserve_tagmsg) {
7079 fprintf(stderr, "%s: tag message preserved in %s\n",
7080 getprogname(), tagmsg_path);
7081 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7082 err = got_error_from_errno2("unlink", tagmsg_path);
7083 free(tag_id_str);
7084 if (ref)
7085 got_ref_close(ref);
7086 free(commit_id);
7087 free(commit_id_str);
7088 free(refname);
7089 free(tagmsg);
7090 free(tagmsg_path);
7091 got_ref_list_free(&refs);
7092 return err;
7095 static const struct got_error *
7096 cmd_tag(int argc, char *argv[])
7098 const struct got_error *error = NULL;
7099 struct got_repository *repo = NULL;
7100 struct got_worktree *worktree = NULL;
7101 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7102 char *gitconfig_path = NULL, *tagger = NULL;
7103 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
7104 int ch, do_list = 0;
7105 int *pack_fds = NULL;
7107 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7108 switch (ch) {
7109 case 'c':
7110 commit_id_arg = optarg;
7111 break;
7112 case 'm':
7113 tagmsg = optarg;
7114 break;
7115 case 'r':
7116 repo_path = realpath(optarg, NULL);
7117 if (repo_path == NULL)
7118 return got_error_from_errno2("realpath",
7119 optarg);
7120 got_path_strip_trailing_slashes(repo_path);
7121 break;
7122 case 'l':
7123 do_list = 1;
7124 break;
7125 default:
7126 usage_tag();
7127 /* NOTREACHED */
7131 argc -= optind;
7132 argv += optind;
7134 if (do_list) {
7135 if (commit_id_arg != NULL)
7136 errx(1,
7137 "-c option can only be used when creating a tag");
7138 if (tagmsg)
7139 option_conflict('l', 'm');
7140 if (argc > 0)
7141 usage_tag();
7142 } else if (argc != 1)
7143 usage_tag();
7145 tag_name = argv[0];
7147 #ifndef PROFILE
7148 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7149 "sendfd unveil", NULL) == -1)
7150 err(1, "pledge");
7151 #endif
7152 cwd = getcwd(NULL, 0);
7153 if (cwd == NULL) {
7154 error = got_error_from_errno("getcwd");
7155 goto done;
7158 error = got_repo_pack_fds_open(&pack_fds);
7159 if (error != NULL)
7160 goto done;
7162 if (repo_path == NULL) {
7163 error = got_worktree_open(&worktree, cwd);
7164 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7165 goto done;
7166 else
7167 error = NULL;
7168 if (worktree) {
7169 repo_path =
7170 strdup(got_worktree_get_repo_path(worktree));
7171 if (repo_path == NULL)
7172 error = got_error_from_errno("strdup");
7173 if (error)
7174 goto done;
7175 } else {
7176 repo_path = strdup(cwd);
7177 if (repo_path == NULL) {
7178 error = got_error_from_errno("strdup");
7179 goto done;
7184 if (do_list) {
7185 if (worktree) {
7186 /* Release work tree lock. */
7187 got_worktree_close(worktree);
7188 worktree = NULL;
7190 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7191 if (error != NULL)
7192 goto done;
7194 #ifndef PROFILE
7195 /* Remove "cpath" promise. */
7196 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7197 NULL) == -1)
7198 err(1, "pledge");
7199 #endif
7200 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7201 if (error)
7202 goto done;
7203 error = list_tags(repo);
7204 } else {
7205 error = get_gitconfig_path(&gitconfig_path);
7206 if (error)
7207 goto done;
7208 error = got_repo_open(&repo, repo_path, gitconfig_path,
7209 pack_fds);
7210 if (error != NULL)
7211 goto done;
7213 error = get_author(&tagger, repo, worktree);
7214 if (error)
7215 goto done;
7216 if (worktree) {
7217 /* Release work tree lock. */
7218 got_worktree_close(worktree);
7219 worktree = NULL;
7222 if (tagmsg) {
7223 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7224 if (error)
7225 goto done;
7228 if (commit_id_arg == NULL) {
7229 struct got_reference *head_ref;
7230 struct got_object_id *commit_id;
7231 error = got_ref_open(&head_ref, repo,
7232 worktree ? got_worktree_get_head_ref_name(worktree)
7233 : GOT_REF_HEAD, 0);
7234 if (error)
7235 goto done;
7236 error = got_ref_resolve(&commit_id, repo, head_ref);
7237 got_ref_close(head_ref);
7238 if (error)
7239 goto done;
7240 error = got_object_id_str(&commit_id_str, commit_id);
7241 free(commit_id);
7242 if (error)
7243 goto done;
7246 error = add_tag(repo, tagger, tag_name,
7247 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7249 done:
7250 if (repo) {
7251 const struct got_error *close_err = got_repo_close(repo);
7252 if (error == NULL)
7253 error = close_err;
7255 if (worktree)
7256 got_worktree_close(worktree);
7257 if (pack_fds) {
7258 const struct got_error *pack_err =
7259 got_repo_pack_fds_close(pack_fds);
7260 if (error == NULL)
7261 error = pack_err;
7262 pack_fds = NULL;
7264 free(cwd);
7265 free(repo_path);
7266 free(gitconfig_path);
7267 free(commit_id_str);
7268 free(tagger);
7269 return error;
7272 __dead static void
7273 usage_add(void)
7275 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7276 getprogname());
7277 exit(1);
7280 static const struct got_error *
7281 add_progress(void *arg, unsigned char status, const char *path)
7283 while (path[0] == '/')
7284 path++;
7285 printf("%c %s\n", status, path);
7286 return NULL;
7289 static const struct got_error *
7290 cmd_add(int argc, char *argv[])
7292 const struct got_error *error = NULL;
7293 struct got_repository *repo = NULL;
7294 struct got_worktree *worktree = NULL;
7295 char *cwd = NULL;
7296 struct got_pathlist_head paths;
7297 struct got_pathlist_entry *pe;
7298 int ch, can_recurse = 0, no_ignores = 0;
7299 int *pack_fds = NULL;
7301 TAILQ_INIT(&paths);
7303 while ((ch = getopt(argc, argv, "IR")) != -1) {
7304 switch (ch) {
7305 case 'I':
7306 no_ignores = 1;
7307 break;
7308 case 'R':
7309 can_recurse = 1;
7310 break;
7311 default:
7312 usage_add();
7313 /* NOTREACHED */
7317 argc -= optind;
7318 argv += optind;
7320 #ifndef PROFILE
7321 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7322 NULL) == -1)
7323 err(1, "pledge");
7324 #endif
7325 if (argc < 1)
7326 usage_add();
7328 cwd = getcwd(NULL, 0);
7329 if (cwd == NULL) {
7330 error = got_error_from_errno("getcwd");
7331 goto done;
7334 error = got_repo_pack_fds_open(&pack_fds);
7335 if (error != NULL)
7336 goto done;
7338 error = got_worktree_open(&worktree, cwd);
7339 if (error) {
7340 if (error->code == GOT_ERR_NOT_WORKTREE)
7341 error = wrap_not_worktree_error(error, "add", cwd);
7342 goto done;
7345 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7346 NULL, pack_fds);
7347 if (error != NULL)
7348 goto done;
7350 error = apply_unveil(got_repo_get_path(repo), 1,
7351 got_worktree_get_root_path(worktree));
7352 if (error)
7353 goto done;
7355 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7356 if (error)
7357 goto done;
7359 if (!can_recurse) {
7360 char *ondisk_path;
7361 struct stat sb;
7362 TAILQ_FOREACH(pe, &paths, entry) {
7363 if (asprintf(&ondisk_path, "%s/%s",
7364 got_worktree_get_root_path(worktree),
7365 pe->path) == -1) {
7366 error = got_error_from_errno("asprintf");
7367 goto done;
7369 if (lstat(ondisk_path, &sb) == -1) {
7370 if (errno == ENOENT) {
7371 free(ondisk_path);
7372 continue;
7374 error = got_error_from_errno2("lstat",
7375 ondisk_path);
7376 free(ondisk_path);
7377 goto done;
7379 free(ondisk_path);
7380 if (S_ISDIR(sb.st_mode)) {
7381 error = got_error_msg(GOT_ERR_BAD_PATH,
7382 "adding directories requires -R option");
7383 goto done;
7388 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7389 NULL, repo, no_ignores);
7390 done:
7391 if (repo) {
7392 const struct got_error *close_err = got_repo_close(repo);
7393 if (error == NULL)
7394 error = close_err;
7396 if (worktree)
7397 got_worktree_close(worktree);
7398 if (pack_fds) {
7399 const struct got_error *pack_err =
7400 got_repo_pack_fds_close(pack_fds);
7401 if (error == NULL)
7402 error = pack_err;
7403 pack_fds = NULL;
7405 TAILQ_FOREACH(pe, &paths, entry)
7406 free((char *)pe->path);
7407 got_pathlist_free(&paths);
7408 free(cwd);
7409 return error;
7412 __dead static void
7413 usage_remove(void)
7415 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7416 "path ...\n", getprogname());
7417 exit(1);
7420 static const struct got_error *
7421 print_remove_status(void *arg, unsigned char status,
7422 unsigned char staged_status, const char *path)
7424 while (path[0] == '/')
7425 path++;
7426 if (status == GOT_STATUS_NONEXISTENT)
7427 return NULL;
7428 if (status == staged_status && (status == GOT_STATUS_DELETE))
7429 status = GOT_STATUS_NO_CHANGE;
7430 printf("%c%c %s\n", status, staged_status, path);
7431 return NULL;
7434 static const struct got_error *
7435 cmd_remove(int argc, char *argv[])
7437 const struct got_error *error = NULL;
7438 struct got_worktree *worktree = NULL;
7439 struct got_repository *repo = NULL;
7440 const char *status_codes = NULL;
7441 char *cwd = NULL;
7442 struct got_pathlist_head paths;
7443 struct got_pathlist_entry *pe;
7444 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7445 int ignore_missing_paths = 0;
7446 int *pack_fds = NULL;
7448 TAILQ_INIT(&paths);
7450 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7451 switch (ch) {
7452 case 'f':
7453 delete_local_mods = 1;
7454 ignore_missing_paths = 1;
7455 break;
7456 case 'k':
7457 keep_on_disk = 1;
7458 break;
7459 case 'R':
7460 can_recurse = 1;
7461 break;
7462 case 's':
7463 for (i = 0; i < strlen(optarg); i++) {
7464 switch (optarg[i]) {
7465 case GOT_STATUS_MODIFY:
7466 delete_local_mods = 1;
7467 break;
7468 case GOT_STATUS_MISSING:
7469 ignore_missing_paths = 1;
7470 break;
7471 default:
7472 errx(1, "invalid status code '%c'",
7473 optarg[i]);
7476 status_codes = optarg;
7477 break;
7478 default:
7479 usage_remove();
7480 /* NOTREACHED */
7484 argc -= optind;
7485 argv += optind;
7487 #ifndef PROFILE
7488 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7489 NULL) == -1)
7490 err(1, "pledge");
7491 #endif
7492 if (argc < 1)
7493 usage_remove();
7495 cwd = getcwd(NULL, 0);
7496 if (cwd == NULL) {
7497 error = got_error_from_errno("getcwd");
7498 goto done;
7501 error = got_repo_pack_fds_open(&pack_fds);
7502 if (error != NULL)
7503 goto done;
7505 error = got_worktree_open(&worktree, cwd);
7506 if (error) {
7507 if (error->code == GOT_ERR_NOT_WORKTREE)
7508 error = wrap_not_worktree_error(error, "remove", cwd);
7509 goto done;
7512 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7513 NULL, pack_fds);
7514 if (error)
7515 goto done;
7517 error = apply_unveil(got_repo_get_path(repo), 1,
7518 got_worktree_get_root_path(worktree));
7519 if (error)
7520 goto done;
7522 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7523 if (error)
7524 goto done;
7526 if (!can_recurse) {
7527 char *ondisk_path;
7528 struct stat sb;
7529 TAILQ_FOREACH(pe, &paths, entry) {
7530 if (asprintf(&ondisk_path, "%s/%s",
7531 got_worktree_get_root_path(worktree),
7532 pe->path) == -1) {
7533 error = got_error_from_errno("asprintf");
7534 goto done;
7536 if (lstat(ondisk_path, &sb) == -1) {
7537 if (errno == ENOENT) {
7538 free(ondisk_path);
7539 continue;
7541 error = got_error_from_errno2("lstat",
7542 ondisk_path);
7543 free(ondisk_path);
7544 goto done;
7546 free(ondisk_path);
7547 if (S_ISDIR(sb.st_mode)) {
7548 error = got_error_msg(GOT_ERR_BAD_PATH,
7549 "removing directories requires -R option");
7550 goto done;
7555 error = got_worktree_schedule_delete(worktree, &paths,
7556 delete_local_mods, status_codes, print_remove_status, NULL,
7557 repo, keep_on_disk, ignore_missing_paths);
7558 done:
7559 if (repo) {
7560 const struct got_error *close_err = got_repo_close(repo);
7561 if (error == NULL)
7562 error = close_err;
7564 if (worktree)
7565 got_worktree_close(worktree);
7566 if (pack_fds) {
7567 const struct got_error *pack_err =
7568 got_repo_pack_fds_close(pack_fds);
7569 if (error == NULL)
7570 error = pack_err;
7571 pack_fds = NULL;
7573 TAILQ_FOREACH(pe, &paths, entry)
7574 free((char *)pe->path);
7575 got_pathlist_free(&paths);
7576 free(cwd);
7577 return error;
7580 __dead static void
7581 usage_patch(void)
7583 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7584 "[-R] [patchfile]\n", getprogname());
7585 exit(1);
7588 static const struct got_error *
7589 patch_from_stdin(int *patchfd)
7591 const struct got_error *err = NULL;
7592 ssize_t r;
7593 char *path, buf[BUFSIZ];
7594 sig_t sighup, sigint, sigquit;
7596 err = got_opentemp_named_fd(&path, patchfd,
7597 GOT_TMPDIR_STR "/got-patch");
7598 if (err)
7599 return err;
7600 unlink(path);
7601 free(path);
7603 sighup = signal(SIGHUP, SIG_DFL);
7604 sigint = signal(SIGINT, SIG_DFL);
7605 sigquit = signal(SIGQUIT, SIG_DFL);
7607 for (;;) {
7608 r = read(0, buf, sizeof(buf));
7609 if (r == -1) {
7610 err = got_error_from_errno("read");
7611 break;
7613 if (r == 0)
7614 break;
7615 if (write(*patchfd, buf, r) == -1) {
7616 err = got_error_from_errno("write");
7617 break;
7621 signal(SIGHUP, sighup);
7622 signal(SIGINT, sigint);
7623 signal(SIGQUIT, sigquit);
7625 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7626 err = got_error_from_errno("lseek");
7628 if (err != NULL) {
7629 close(*patchfd);
7630 *patchfd = -1;
7633 return err;
7636 static const struct got_error *
7637 patch_progress(void *arg, const char *old, const char *new,
7638 unsigned char status, const struct got_error *error, long old_from,
7639 long old_lines, long new_from, long new_lines, long offset,
7640 const struct got_error *hunk_err)
7642 const char *path = new == NULL ? old : new;
7644 while (*path == '/')
7645 path++;
7647 if (status != 0)
7648 printf("%c %s\n", status, path);
7650 if (error != NULL)
7651 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7653 if (offset != 0 || hunk_err != NULL) {
7654 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7655 old_lines, new_from, new_lines);
7656 if (hunk_err != NULL)
7657 printf("%s\n", hunk_err->msg);
7658 else
7659 printf("applied with offset %ld\n", offset);
7662 return NULL;
7665 static const struct got_error *
7666 cmd_patch(int argc, char *argv[])
7668 const struct got_error *error = NULL, *close_error = NULL;
7669 struct got_worktree *worktree = NULL;
7670 struct got_repository *repo = NULL;
7671 const char *errstr;
7672 char *cwd = NULL;
7673 int ch, nop = 0, strip = -1, reverse = 0;
7674 int patchfd;
7675 int *pack_fds = NULL;
7677 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7678 switch (ch) {
7679 case 'n':
7680 nop = 1;
7681 break;
7682 case 'p':
7683 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7684 if (errstr != NULL)
7685 errx(1, "pathname strip count is %s: %s",
7686 errstr, optarg);
7687 break;
7688 case 'R':
7689 reverse = 1;
7690 break;
7691 default:
7692 usage_patch();
7693 /* NOTREACHED */
7697 argc -= optind;
7698 argv += optind;
7700 if (argc == 0) {
7701 error = patch_from_stdin(&patchfd);
7702 if (error)
7703 return error;
7704 } else if (argc == 1) {
7705 patchfd = open(argv[0], O_RDONLY);
7706 if (patchfd == -1) {
7707 error = got_error_from_errno2("open", argv[0]);
7708 return error;
7710 } else
7711 usage_patch();
7713 if ((cwd = getcwd(NULL, 0)) == NULL) {
7714 error = got_error_from_errno("getcwd");
7715 goto done;
7718 error = got_repo_pack_fds_open(&pack_fds);
7719 if (error != NULL)
7720 goto done;
7722 error = got_worktree_open(&worktree, cwd);
7723 if (error != NULL)
7724 goto done;
7726 const char *repo_path = got_worktree_get_repo_path(worktree);
7727 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7728 if (error != NULL)
7729 goto done;
7731 error = apply_unveil(got_repo_get_path(repo), 0,
7732 got_worktree_get_root_path(worktree));
7733 if (error != NULL)
7734 goto done;
7736 #ifndef PROFILE
7737 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7738 NULL) == -1)
7739 err(1, "pledge");
7740 #endif
7742 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7743 &patch_progress, NULL, check_cancelled, NULL);
7745 done:
7746 if (repo) {
7747 close_error = got_repo_close(repo);
7748 if (error == NULL)
7749 error = close_error;
7751 if (worktree != NULL) {
7752 close_error = got_worktree_close(worktree);
7753 if (error == NULL)
7754 error = close_error;
7756 if (pack_fds) {
7757 const struct got_error *pack_err =
7758 got_repo_pack_fds_close(pack_fds);
7759 if (error == NULL)
7760 error = pack_err;
7761 pack_fds = NULL;
7763 free(cwd);
7764 return error;
7767 __dead static void
7768 usage_revert(void)
7770 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7771 "path ...\n", getprogname());
7772 exit(1);
7775 static const struct got_error *
7776 revert_progress(void *arg, unsigned char status, const char *path)
7778 if (status == GOT_STATUS_UNVERSIONED)
7779 return NULL;
7781 while (path[0] == '/')
7782 path++;
7783 printf("%c %s\n", status, path);
7784 return NULL;
7787 struct choose_patch_arg {
7788 FILE *patch_script_file;
7789 const char *action;
7792 static const struct got_error *
7793 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7794 int nchanges, const char *action)
7796 const struct got_error *err;
7797 char *line = NULL;
7798 size_t linesize = 0;
7799 ssize_t linelen;
7801 switch (status) {
7802 case GOT_STATUS_ADD:
7803 printf("A %s\n%s this addition? [y/n] ", path, action);
7804 break;
7805 case GOT_STATUS_DELETE:
7806 printf("D %s\n%s this deletion? [y/n] ", path, action);
7807 break;
7808 case GOT_STATUS_MODIFY:
7809 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7810 return got_error_from_errno("fseek");
7811 printf(GOT_COMMIT_SEP_STR);
7812 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7813 printf("%s", line);
7814 if (linelen == -1 && ferror(patch_file)) {
7815 err = got_error_from_errno("getline");
7816 free(line);
7817 return err;
7819 free(line);
7820 printf(GOT_COMMIT_SEP_STR);
7821 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7822 path, n, nchanges, action);
7823 break;
7824 default:
7825 return got_error_path(path, GOT_ERR_FILE_STATUS);
7828 return NULL;
7831 static const struct got_error *
7832 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7833 FILE *patch_file, int n, int nchanges)
7835 const struct got_error *err = NULL;
7836 char *line = NULL;
7837 size_t linesize = 0;
7838 ssize_t linelen;
7839 int resp = ' ';
7840 struct choose_patch_arg *a = arg;
7842 *choice = GOT_PATCH_CHOICE_NONE;
7844 if (a->patch_script_file) {
7845 char *nl;
7846 err = show_change(status, path, patch_file, n, nchanges,
7847 a->action);
7848 if (err)
7849 return err;
7850 linelen = getline(&line, &linesize, a->patch_script_file);
7851 if (linelen == -1) {
7852 if (ferror(a->patch_script_file))
7853 return got_error_from_errno("getline");
7854 return NULL;
7856 nl = strchr(line, '\n');
7857 if (nl)
7858 *nl = '\0';
7859 if (strcmp(line, "y") == 0) {
7860 *choice = GOT_PATCH_CHOICE_YES;
7861 printf("y\n");
7862 } else if (strcmp(line, "n") == 0) {
7863 *choice = GOT_PATCH_CHOICE_NO;
7864 printf("n\n");
7865 } else if (strcmp(line, "q") == 0 &&
7866 status == GOT_STATUS_MODIFY) {
7867 *choice = GOT_PATCH_CHOICE_QUIT;
7868 printf("q\n");
7869 } else
7870 printf("invalid response '%s'\n", line);
7871 free(line);
7872 return NULL;
7875 while (resp != 'y' && resp != 'n' && resp != 'q') {
7876 err = show_change(status, path, patch_file, n, nchanges,
7877 a->action);
7878 if (err)
7879 return err;
7880 resp = getchar();
7881 if (resp == '\n')
7882 resp = getchar();
7883 if (status == GOT_STATUS_MODIFY) {
7884 if (resp != 'y' && resp != 'n' && resp != 'q') {
7885 printf("invalid response '%c'\n", resp);
7886 resp = ' ';
7888 } else if (resp != 'y' && resp != 'n') {
7889 printf("invalid response '%c'\n", resp);
7890 resp = ' ';
7894 if (resp == 'y')
7895 *choice = GOT_PATCH_CHOICE_YES;
7896 else if (resp == 'n')
7897 *choice = GOT_PATCH_CHOICE_NO;
7898 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7899 *choice = GOT_PATCH_CHOICE_QUIT;
7901 return NULL;
7904 static const struct got_error *
7905 cmd_revert(int argc, char *argv[])
7907 const struct got_error *error = NULL;
7908 struct got_worktree *worktree = NULL;
7909 struct got_repository *repo = NULL;
7910 char *cwd = NULL, *path = NULL;
7911 struct got_pathlist_head paths;
7912 struct got_pathlist_entry *pe;
7913 int ch, can_recurse = 0, pflag = 0;
7914 FILE *patch_script_file = NULL;
7915 const char *patch_script_path = NULL;
7916 struct choose_patch_arg cpa;
7917 int *pack_fds = NULL;
7919 TAILQ_INIT(&paths);
7921 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7922 switch (ch) {
7923 case 'p':
7924 pflag = 1;
7925 break;
7926 case 'F':
7927 patch_script_path = optarg;
7928 break;
7929 case 'R':
7930 can_recurse = 1;
7931 break;
7932 default:
7933 usage_revert();
7934 /* NOTREACHED */
7938 argc -= optind;
7939 argv += optind;
7941 #ifndef PROFILE
7942 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7943 "unveil", NULL) == -1)
7944 err(1, "pledge");
7945 #endif
7946 if (argc < 1)
7947 usage_revert();
7948 if (patch_script_path && !pflag)
7949 errx(1, "-F option can only be used together with -p option");
7951 cwd = getcwd(NULL, 0);
7952 if (cwd == NULL) {
7953 error = got_error_from_errno("getcwd");
7954 goto done;
7957 error = got_repo_pack_fds_open(&pack_fds);
7958 if (error != NULL)
7959 goto done;
7961 error = got_worktree_open(&worktree, cwd);
7962 if (error) {
7963 if (error->code == GOT_ERR_NOT_WORKTREE)
7964 error = wrap_not_worktree_error(error, "revert", cwd);
7965 goto done;
7968 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7969 NULL, pack_fds);
7970 if (error != NULL)
7971 goto done;
7973 if (patch_script_path) {
7974 patch_script_file = fopen(patch_script_path, "re");
7975 if (patch_script_file == NULL) {
7976 error = got_error_from_errno2("fopen",
7977 patch_script_path);
7978 goto done;
7981 error = apply_unveil(got_repo_get_path(repo), 1,
7982 got_worktree_get_root_path(worktree));
7983 if (error)
7984 goto done;
7986 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7987 if (error)
7988 goto done;
7990 if (!can_recurse) {
7991 char *ondisk_path;
7992 struct stat sb;
7993 TAILQ_FOREACH(pe, &paths, entry) {
7994 if (asprintf(&ondisk_path, "%s/%s",
7995 got_worktree_get_root_path(worktree),
7996 pe->path) == -1) {
7997 error = got_error_from_errno("asprintf");
7998 goto done;
8000 if (lstat(ondisk_path, &sb) == -1) {
8001 if (errno == ENOENT) {
8002 free(ondisk_path);
8003 continue;
8005 error = got_error_from_errno2("lstat",
8006 ondisk_path);
8007 free(ondisk_path);
8008 goto done;
8010 free(ondisk_path);
8011 if (S_ISDIR(sb.st_mode)) {
8012 error = got_error_msg(GOT_ERR_BAD_PATH,
8013 "reverting directories requires -R option");
8014 goto done;
8019 cpa.patch_script_file = patch_script_file;
8020 cpa.action = "revert";
8021 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8022 pflag ? choose_patch : NULL, &cpa, repo);
8023 done:
8024 if (patch_script_file && fclose(patch_script_file) == EOF &&
8025 error == NULL)
8026 error = got_error_from_errno2("fclose", patch_script_path);
8027 if (repo) {
8028 const struct got_error *close_err = got_repo_close(repo);
8029 if (error == NULL)
8030 error = close_err;
8032 if (worktree)
8033 got_worktree_close(worktree);
8034 if (pack_fds) {
8035 const struct got_error *pack_err =
8036 got_repo_pack_fds_close(pack_fds);
8037 if (error == NULL)
8038 error = pack_err;
8039 pack_fds = NULL;
8041 free(path);
8042 free(cwd);
8043 return error;
8046 __dead static void
8047 usage_commit(void)
8049 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8050 "[path ...]\n", getprogname());
8051 exit(1);
8054 struct collect_commit_logmsg_arg {
8055 const char *cmdline_log;
8056 const char *prepared_log;
8057 int non_interactive;
8058 const char *editor;
8059 const char *worktree_path;
8060 const char *branch_name;
8061 const char *repo_path;
8062 char *logmsg_path;
8066 static const struct got_error *
8067 read_prepared_logmsg(char **logmsg, const char *path)
8069 const struct got_error *err = NULL;
8070 FILE *f = NULL;
8071 struct stat sb;
8072 size_t r;
8074 *logmsg = NULL;
8075 memset(&sb, 0, sizeof(sb));
8077 f = fopen(path, "re");
8078 if (f == NULL)
8079 return got_error_from_errno2("fopen", path);
8081 if (fstat(fileno(f), &sb) == -1) {
8082 err = got_error_from_errno2("fstat", path);
8083 goto done;
8085 if (sb.st_size == 0) {
8086 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8087 goto done;
8090 *logmsg = malloc(sb.st_size + 1);
8091 if (*logmsg == NULL) {
8092 err = got_error_from_errno("malloc");
8093 goto done;
8096 r = fread(*logmsg, 1, sb.st_size, f);
8097 if (r != sb.st_size) {
8098 if (ferror(f))
8099 err = got_error_from_errno2("fread", path);
8100 else
8101 err = got_error(GOT_ERR_IO);
8102 goto done;
8104 (*logmsg)[sb.st_size] = '\0';
8105 done:
8106 if (fclose(f) == EOF && err == NULL)
8107 err = got_error_from_errno2("fclose", path);
8108 if (err) {
8109 free(*logmsg);
8110 *logmsg = NULL;
8112 return err;
8116 static const struct got_error *
8117 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8118 void *arg)
8120 char *initial_content = NULL;
8121 struct got_pathlist_entry *pe;
8122 const struct got_error *err = NULL;
8123 char *template = NULL;
8124 struct collect_commit_logmsg_arg *a = arg;
8125 int initial_content_len;
8126 int fd = -1;
8127 size_t len;
8129 /* if a message was specified on the command line, just use it */
8130 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8131 len = strlen(a->cmdline_log) + 1;
8132 *logmsg = malloc(len + 1);
8133 if (*logmsg == NULL)
8134 return got_error_from_errno("malloc");
8135 strlcpy(*logmsg, a->cmdline_log, len);
8136 return NULL;
8137 } else if (a->prepared_log != NULL && a->non_interactive)
8138 return read_prepared_logmsg(logmsg, a->prepared_log);
8140 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8141 return got_error_from_errno("asprintf");
8143 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8144 if (err)
8145 goto done;
8147 if (a->prepared_log) {
8148 char *msg;
8149 err = read_prepared_logmsg(&msg, a->prepared_log);
8150 if (err)
8151 goto done;
8152 if (write(fd, msg, strlen(msg)) == -1) {
8153 err = got_error_from_errno2("write", a->logmsg_path);
8154 free(msg);
8155 goto done;
8157 free(msg);
8160 initial_content_len = asprintf(&initial_content,
8161 "\n# changes to be committed on branch %s:\n",
8162 a->branch_name);
8163 if (initial_content_len == -1) {
8164 err = got_error_from_errno("asprintf");
8165 goto done;
8168 if (write(fd, initial_content, initial_content_len) == -1) {
8169 err = got_error_from_errno2("write", a->logmsg_path);
8170 goto done;
8173 TAILQ_FOREACH(pe, commitable_paths, entry) {
8174 struct got_commitable *ct = pe->data;
8175 dprintf(fd, "# %c %s\n",
8176 got_commitable_get_status(ct),
8177 got_commitable_get_path(ct));
8180 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8181 initial_content_len, a->prepared_log ? 0 : 1);
8182 done:
8183 free(initial_content);
8184 free(template);
8186 if (fd != -1 && close(fd) == -1 && err == NULL)
8187 err = got_error_from_errno2("close", a->logmsg_path);
8189 /* Editor is done; we can now apply unveil(2) */
8190 if (err == NULL)
8191 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8192 if (err) {
8193 free(*logmsg);
8194 *logmsg = NULL;
8196 return err;
8199 static const struct got_error *
8200 cmd_commit(int argc, char *argv[])
8202 const struct got_error *error = NULL;
8203 struct got_worktree *worktree = NULL;
8204 struct got_repository *repo = NULL;
8205 char *cwd = NULL, *id_str = NULL;
8206 struct got_object_id *id = NULL;
8207 const char *logmsg = NULL;
8208 char *prepared_logmsg = NULL;
8209 struct collect_commit_logmsg_arg cl_arg;
8210 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8211 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8212 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8213 struct got_pathlist_head paths;
8214 int *pack_fds = NULL;
8216 TAILQ_INIT(&paths);
8217 cl_arg.logmsg_path = NULL;
8219 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8220 switch (ch) {
8221 case 'F':
8222 if (logmsg != NULL)
8223 option_conflict('F', 'm');
8224 prepared_logmsg = realpath(optarg, NULL);
8225 if (prepared_logmsg == NULL)
8226 return got_error_from_errno2("realpath",
8227 optarg);
8228 break;
8229 case 'm':
8230 if (prepared_logmsg)
8231 option_conflict('m', 'F');
8232 logmsg = optarg;
8233 break;
8234 case 'N':
8235 non_interactive = 1;
8236 break;
8237 case 'S':
8238 allow_bad_symlinks = 1;
8239 break;
8240 default:
8241 usage_commit();
8242 /* NOTREACHED */
8246 argc -= optind;
8247 argv += optind;
8249 #ifndef PROFILE
8250 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8251 "unveil", NULL) == -1)
8252 err(1, "pledge");
8253 #endif
8254 cwd = getcwd(NULL, 0);
8255 if (cwd == NULL) {
8256 error = got_error_from_errno("getcwd");
8257 goto done;
8260 error = got_repo_pack_fds_open(&pack_fds);
8261 if (error != NULL)
8262 goto done;
8264 error = got_worktree_open(&worktree, cwd);
8265 if (error) {
8266 if (error->code == GOT_ERR_NOT_WORKTREE)
8267 error = wrap_not_worktree_error(error, "commit", cwd);
8268 goto done;
8271 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8272 if (error)
8273 goto done;
8274 if (rebase_in_progress) {
8275 error = got_error(GOT_ERR_REBASING);
8276 goto done;
8279 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8280 worktree);
8281 if (error)
8282 goto done;
8284 error = get_gitconfig_path(&gitconfig_path);
8285 if (error)
8286 goto done;
8287 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8288 gitconfig_path, pack_fds);
8289 if (error != NULL)
8290 goto done;
8292 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8293 if (error)
8294 goto done;
8295 if (merge_in_progress) {
8296 error = got_error(GOT_ERR_MERGE_BUSY);
8297 goto done;
8300 error = get_author(&author, repo, worktree);
8301 if (error)
8302 return error;
8305 * unveil(2) traverses exec(2); if an editor is used we have
8306 * to apply unveil after the log message has been written.
8308 if (logmsg == NULL || strlen(logmsg) == 0)
8309 error = get_editor(&editor);
8310 else
8311 error = apply_unveil(got_repo_get_path(repo), 0,
8312 got_worktree_get_root_path(worktree));
8313 if (error)
8314 goto done;
8316 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8317 if (error)
8318 goto done;
8320 cl_arg.editor = editor;
8321 cl_arg.cmdline_log = logmsg;
8322 cl_arg.prepared_log = prepared_logmsg;
8323 cl_arg.non_interactive = non_interactive;
8324 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8325 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8326 if (!histedit_in_progress) {
8327 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8328 error = got_error(GOT_ERR_COMMIT_BRANCH);
8329 goto done;
8331 cl_arg.branch_name += 11;
8333 cl_arg.repo_path = got_repo_get_path(repo);
8334 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8335 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8336 print_status, NULL, repo);
8337 if (error) {
8338 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8339 cl_arg.logmsg_path != NULL)
8340 preserve_logmsg = 1;
8341 goto done;
8344 error = got_object_id_str(&id_str, id);
8345 if (error)
8346 goto done;
8347 printf("Created commit %s\n", id_str);
8348 done:
8349 if (preserve_logmsg) {
8350 fprintf(stderr, "%s: log message preserved in %s\n",
8351 getprogname(), cl_arg.logmsg_path);
8352 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8353 error == NULL)
8354 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8355 free(cl_arg.logmsg_path);
8356 if (repo) {
8357 const struct got_error *close_err = got_repo_close(repo);
8358 if (error == NULL)
8359 error = close_err;
8361 if (worktree)
8362 got_worktree_close(worktree);
8363 if (pack_fds) {
8364 const struct got_error *pack_err =
8365 got_repo_pack_fds_close(pack_fds);
8366 if (error == NULL)
8367 error = pack_err;
8368 pack_fds = NULL;
8370 free(cwd);
8371 free(id_str);
8372 free(gitconfig_path);
8373 free(editor);
8374 free(author);
8375 free(prepared_logmsg);
8376 return error;
8379 __dead static void
8380 usage_send(void)
8382 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8383 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8384 "[remote-repository]\n", getprogname());
8385 exit(1);
8388 static void
8389 print_load_info(int print_colored, int print_found, int print_trees,
8390 int ncolored, int nfound, int ntrees)
8392 if (print_colored) {
8393 printf("%d commit%s colored", ncolored,
8394 ncolored == 1 ? "" : "s");
8396 if (print_found) {
8397 printf("%s%d object%s found",
8398 ncolored > 0 ? "; " : "",
8399 nfound, nfound == 1 ? "" : "s");
8401 if (print_trees) {
8402 printf("; %d tree%s scanned", ntrees,
8403 ntrees == 1 ? "" : "s");
8407 struct got_send_progress_arg {
8408 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8409 int verbosity;
8410 int last_ncolored;
8411 int last_nfound;
8412 int last_ntrees;
8413 int loading_done;
8414 int last_ncommits;
8415 int last_nobj_total;
8416 int last_p_deltify;
8417 int last_p_written;
8418 int last_p_sent;
8419 int printed_something;
8420 int sent_something;
8421 struct got_pathlist_head *delete_branches;
8424 static const struct got_error *
8425 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8426 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8427 int nobj_written, off_t bytes_sent, const char *refname, int success)
8429 struct got_send_progress_arg *a = arg;
8430 char scaled_packsize[FMT_SCALED_STRSIZE];
8431 char scaled_sent[FMT_SCALED_STRSIZE];
8432 int p_deltify = 0, p_written = 0, p_sent = 0;
8433 int print_colored = 0, print_found = 0, print_trees = 0;
8434 int print_searching = 0, print_total = 0;
8435 int print_deltify = 0, print_written = 0, print_sent = 0;
8437 if (a->verbosity < 0)
8438 return NULL;
8440 if (refname) {
8441 const char *status = success ? "accepted" : "rejected";
8443 if (success) {
8444 struct got_pathlist_entry *pe;
8445 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8446 const char *branchname = pe->path;
8447 if (got_path_cmp(branchname, refname,
8448 strlen(branchname), strlen(refname)) == 0) {
8449 status = "deleted";
8450 a->sent_something = 1;
8451 break;
8456 if (a->printed_something)
8457 putchar('\n');
8458 printf("Server has %s %s", status, refname);
8459 a->printed_something = 1;
8460 return NULL;
8463 if (a->last_ncolored != ncolored) {
8464 print_colored = 1;
8465 a->last_ncolored = ncolored;
8468 if (a->last_nfound != nfound) {
8469 print_colored = 1;
8470 print_found = 1;
8471 a->last_nfound = nfound;
8474 if (a->last_ntrees != ntrees) {
8475 print_colored = 1;
8476 print_found = 1;
8477 print_trees = 1;
8478 a->last_ntrees = ntrees;
8481 if ((print_colored || print_found || print_trees) &&
8482 !a->loading_done) {
8483 printf("\r");
8484 print_load_info(print_colored, print_found, print_trees,
8485 ncolored, nfound, ntrees);
8486 a->printed_something = 1;
8487 fflush(stdout);
8488 return NULL;
8489 } else if (!a->loading_done) {
8490 printf("\r");
8491 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8492 printf("\n");
8493 a->loading_done = 1;
8496 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8497 return got_error_from_errno("fmt_scaled");
8498 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8499 return got_error_from_errno("fmt_scaled");
8501 if (a->last_ncommits != ncommits) {
8502 print_searching = 1;
8503 a->last_ncommits = ncommits;
8506 if (a->last_nobj_total != nobj_total) {
8507 print_searching = 1;
8508 print_total = 1;
8509 a->last_nobj_total = nobj_total;
8512 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8513 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8514 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8515 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8516 return got_error(GOT_ERR_NO_SPACE);
8519 if (nobj_deltify > 0 || nobj_written > 0) {
8520 if (nobj_deltify > 0) {
8521 p_deltify = (nobj_deltify * 100) / nobj_total;
8522 if (p_deltify != a->last_p_deltify) {
8523 a->last_p_deltify = p_deltify;
8524 print_searching = 1;
8525 print_total = 1;
8526 print_deltify = 1;
8529 if (nobj_written > 0) {
8530 p_written = (nobj_written * 100) / nobj_total;
8531 if (p_written != a->last_p_written) {
8532 a->last_p_written = p_written;
8533 print_searching = 1;
8534 print_total = 1;
8535 print_deltify = 1;
8536 print_written = 1;
8541 if (bytes_sent > 0) {
8542 p_sent = (bytes_sent * 100) / packfile_size;
8543 if (p_sent != a->last_p_sent) {
8544 a->last_p_sent = p_sent;
8545 print_searching = 1;
8546 print_total = 1;
8547 print_deltify = 1;
8548 print_written = 1;
8549 print_sent = 1;
8551 a->sent_something = 1;
8554 if (print_searching || print_total || print_deltify || print_written ||
8555 print_sent)
8556 printf("\r");
8557 if (print_searching)
8558 printf("packing %d reference%s", ncommits,
8559 ncommits == 1 ? "" : "s");
8560 if (print_total)
8561 printf("; %d object%s", nobj_total,
8562 nobj_total == 1 ? "" : "s");
8563 if (print_deltify)
8564 printf("; deltify: %d%%", p_deltify);
8565 if (print_sent)
8566 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8567 scaled_packsize, p_sent);
8568 else if (print_written)
8569 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8570 scaled_packsize, p_written);
8571 if (print_searching || print_total || print_deltify ||
8572 print_written || print_sent) {
8573 a->printed_something = 1;
8574 fflush(stdout);
8576 return NULL;
8579 static const struct got_error *
8580 cmd_send(int argc, char *argv[])
8582 const struct got_error *error = NULL;
8583 char *cwd = NULL, *repo_path = NULL;
8584 const char *remote_name;
8585 char *proto = NULL, *host = NULL, *port = NULL;
8586 char *repo_name = NULL, *server_path = NULL;
8587 const struct got_remote_repo *remotes, *remote = NULL;
8588 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8589 struct got_repository *repo = NULL;
8590 struct got_worktree *worktree = NULL;
8591 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8592 struct got_pathlist_head branches;
8593 struct got_pathlist_head tags;
8594 struct got_reflist_head all_branches;
8595 struct got_reflist_head all_tags;
8596 struct got_pathlist_head delete_args;
8597 struct got_pathlist_head delete_branches;
8598 struct got_reflist_entry *re;
8599 struct got_pathlist_entry *pe;
8600 int i, ch, sendfd = -1, sendstatus;
8601 pid_t sendpid = -1;
8602 struct got_send_progress_arg spa;
8603 int verbosity = 0, overwrite_refs = 0;
8604 int send_all_branches = 0, send_all_tags = 0;
8605 struct got_reference *ref = NULL;
8606 int *pack_fds = NULL;
8608 TAILQ_INIT(&branches);
8609 TAILQ_INIT(&tags);
8610 TAILQ_INIT(&all_branches);
8611 TAILQ_INIT(&all_tags);
8612 TAILQ_INIT(&delete_args);
8613 TAILQ_INIT(&delete_branches);
8615 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8616 switch (ch) {
8617 case 'a':
8618 send_all_branches = 1;
8619 break;
8620 case 'b':
8621 error = got_pathlist_append(&branches, optarg, NULL);
8622 if (error)
8623 return error;
8624 nbranches++;
8625 break;
8626 case 'd':
8627 error = got_pathlist_append(&delete_args, optarg, NULL);
8628 if (error)
8629 return error;
8630 break;
8631 case 'f':
8632 overwrite_refs = 1;
8633 break;
8634 case 'r':
8635 repo_path = realpath(optarg, NULL);
8636 if (repo_path == NULL)
8637 return got_error_from_errno2("realpath",
8638 optarg);
8639 got_path_strip_trailing_slashes(repo_path);
8640 break;
8641 case 't':
8642 error = got_pathlist_append(&tags, optarg, NULL);
8643 if (error)
8644 return error;
8645 ntags++;
8646 break;
8647 case 'T':
8648 send_all_tags = 1;
8649 break;
8650 case 'v':
8651 if (verbosity < 0)
8652 verbosity = 0;
8653 else if (verbosity < 3)
8654 verbosity++;
8655 break;
8656 case 'q':
8657 verbosity = -1;
8658 break;
8659 default:
8660 usage_send();
8661 /* NOTREACHED */
8664 argc -= optind;
8665 argv += optind;
8667 if (send_all_branches && !TAILQ_EMPTY(&branches))
8668 option_conflict('a', 'b');
8669 if (send_all_tags && !TAILQ_EMPTY(&tags))
8670 option_conflict('T', 't');
8673 if (argc == 0)
8674 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8675 else if (argc == 1)
8676 remote_name = argv[0];
8677 else
8678 usage_send();
8680 cwd = getcwd(NULL, 0);
8681 if (cwd == NULL) {
8682 error = got_error_from_errno("getcwd");
8683 goto done;
8686 error = got_repo_pack_fds_open(&pack_fds);
8687 if (error != NULL)
8688 goto done;
8690 if (repo_path == NULL) {
8691 error = got_worktree_open(&worktree, cwd);
8692 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8693 goto done;
8694 else
8695 error = NULL;
8696 if (worktree) {
8697 repo_path =
8698 strdup(got_worktree_get_repo_path(worktree));
8699 if (repo_path == NULL)
8700 error = got_error_from_errno("strdup");
8701 if (error)
8702 goto done;
8703 } else {
8704 repo_path = strdup(cwd);
8705 if (repo_path == NULL) {
8706 error = got_error_from_errno("strdup");
8707 goto done;
8712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8713 if (error)
8714 goto done;
8716 if (worktree) {
8717 worktree_conf = got_worktree_get_gotconfig(worktree);
8718 if (worktree_conf) {
8719 got_gotconfig_get_remotes(&nremotes, &remotes,
8720 worktree_conf);
8721 for (i = 0; i < nremotes; i++) {
8722 if (strcmp(remotes[i].name, remote_name) == 0) {
8723 remote = &remotes[i];
8724 break;
8729 if (remote == NULL) {
8730 repo_conf = got_repo_get_gotconfig(repo);
8731 if (repo_conf) {
8732 got_gotconfig_get_remotes(&nremotes, &remotes,
8733 repo_conf);
8734 for (i = 0; i < nremotes; i++) {
8735 if (strcmp(remotes[i].name, remote_name) == 0) {
8736 remote = &remotes[i];
8737 break;
8742 if (remote == NULL) {
8743 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8744 for (i = 0; i < nremotes; i++) {
8745 if (strcmp(remotes[i].name, remote_name) == 0) {
8746 remote = &remotes[i];
8747 break;
8751 if (remote == NULL) {
8752 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8753 goto done;
8756 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8757 &repo_name, remote->send_url);
8758 if (error)
8759 goto done;
8761 if (strcmp(proto, "git") == 0) {
8762 #ifndef PROFILE
8763 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8764 "sendfd dns inet unveil", NULL) == -1)
8765 err(1, "pledge");
8766 #endif
8767 } else if (strcmp(proto, "git+ssh") == 0 ||
8768 strcmp(proto, "ssh") == 0) {
8769 #ifndef PROFILE
8770 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8771 "sendfd unveil", NULL) == -1)
8772 err(1, "pledge");
8773 #endif
8774 } else if (strcmp(proto, "http") == 0 ||
8775 strcmp(proto, "git+http") == 0) {
8776 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8777 goto done;
8778 } else {
8779 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8780 goto done;
8783 error = got_dial_apply_unveil(proto);
8784 if (error)
8785 goto done;
8787 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8788 if (error)
8789 goto done;
8791 if (send_all_branches) {
8792 error = got_ref_list(&all_branches, repo, "refs/heads",
8793 got_ref_cmp_by_name, NULL);
8794 if (error)
8795 goto done;
8796 TAILQ_FOREACH(re, &all_branches, entry) {
8797 const char *branchname = got_ref_get_name(re->ref);
8798 error = got_pathlist_append(&branches,
8799 branchname, NULL);
8800 if (error)
8801 goto done;
8802 nbranches++;
8804 } else if (nbranches == 0) {
8805 for (i = 0; i < remote->nsend_branches; i++) {
8806 got_pathlist_append(&branches,
8807 remote->send_branches[i], NULL);
8811 if (send_all_tags) {
8812 error = got_ref_list(&all_tags, repo, "refs/tags",
8813 got_ref_cmp_by_name, NULL);
8814 if (error)
8815 goto done;
8816 TAILQ_FOREACH(re, &all_tags, entry) {
8817 const char *tagname = got_ref_get_name(re->ref);
8818 error = got_pathlist_append(&tags,
8819 tagname, NULL);
8820 if (error)
8821 goto done;
8822 ntags++;
8827 * To prevent accidents only branches in refs/heads/ can be deleted
8828 * with 'got send -d'.
8829 * Deleting anything else requires local repository access or Git.
8831 TAILQ_FOREACH(pe, &delete_args, entry) {
8832 const char *branchname = pe->path;
8833 char *s;
8834 struct got_pathlist_entry *new;
8835 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8836 s = strdup(branchname);
8837 if (s == NULL) {
8838 error = got_error_from_errno("strdup");
8839 goto done;
8841 } else {
8842 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8843 error = got_error_from_errno("asprintf");
8844 goto done;
8847 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8848 if (error || new == NULL /* duplicate */)
8849 free(s);
8850 if (error)
8851 goto done;
8852 ndelete_branches++;
8855 if (nbranches == 0 && ndelete_branches == 0) {
8856 struct got_reference *head_ref;
8857 if (worktree)
8858 error = got_ref_open(&head_ref, repo,
8859 got_worktree_get_head_ref_name(worktree), 0);
8860 else
8861 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8862 if (error)
8863 goto done;
8864 if (got_ref_is_symbolic(head_ref)) {
8865 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8866 got_ref_close(head_ref);
8867 if (error)
8868 goto done;
8869 } else
8870 ref = head_ref;
8871 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8872 NULL);
8873 if (error)
8874 goto done;
8875 nbranches++;
8878 if (verbosity >= 0)
8879 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8880 port ? ":" : "", port ? port : "");
8882 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8883 server_path, verbosity);
8884 if (error)
8885 goto done;
8887 memset(&spa, 0, sizeof(spa));
8888 spa.last_scaled_packsize[0] = '\0';
8889 spa.last_p_deltify = -1;
8890 spa.last_p_written = -1;
8891 spa.verbosity = verbosity;
8892 spa.delete_branches = &delete_branches;
8893 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8894 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8895 check_cancelled, NULL);
8896 if (spa.printed_something)
8897 putchar('\n');
8898 if (error)
8899 goto done;
8900 if (!spa.sent_something && verbosity >= 0)
8901 printf("Already up-to-date\n");
8902 done:
8903 if (sendpid > 0) {
8904 if (kill(sendpid, SIGTERM) == -1)
8905 error = got_error_from_errno("kill");
8906 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8907 error = got_error_from_errno("waitpid");
8909 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8910 error = got_error_from_errno("close");
8911 if (repo) {
8912 const struct got_error *close_err = got_repo_close(repo);
8913 if (error == NULL)
8914 error = close_err;
8916 if (worktree)
8917 got_worktree_close(worktree);
8918 if (pack_fds) {
8919 const struct got_error *pack_err =
8920 got_repo_pack_fds_close(pack_fds);
8921 if (error == NULL)
8922 error = pack_err;
8923 pack_fds = NULL;
8925 if (ref)
8926 got_ref_close(ref);
8927 got_pathlist_free(&branches);
8928 got_pathlist_free(&tags);
8929 got_ref_list_free(&all_branches);
8930 got_ref_list_free(&all_tags);
8931 got_pathlist_free(&delete_args);
8932 TAILQ_FOREACH(pe, &delete_branches, entry)
8933 free((char *)pe->path);
8934 got_pathlist_free(&delete_branches);
8935 free(cwd);
8936 free(repo_path);
8937 free(proto);
8938 free(host);
8939 free(port);
8940 free(server_path);
8941 free(repo_name);
8942 return error;
8945 __dead static void
8946 usage_cherrypick(void)
8948 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8949 exit(1);
8952 static const struct got_error *
8953 cmd_cherrypick(int argc, char *argv[])
8955 const struct got_error *error = NULL;
8956 struct got_worktree *worktree = NULL;
8957 struct got_repository *repo = NULL;
8958 char *cwd = NULL, *commit_id_str = NULL;
8959 struct got_object_id *commit_id = NULL;
8960 struct got_commit_object *commit = NULL;
8961 struct got_object_qid *pid;
8962 int ch;
8963 struct got_update_progress_arg upa;
8964 int *pack_fds = NULL;
8966 while ((ch = getopt(argc, argv, "")) != -1) {
8967 switch (ch) {
8968 default:
8969 usage_cherrypick();
8970 /* NOTREACHED */
8974 argc -= optind;
8975 argv += optind;
8977 #ifndef PROFILE
8978 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8979 "unveil", NULL) == -1)
8980 err(1, "pledge");
8981 #endif
8982 if (argc != 1)
8983 usage_cherrypick();
8985 cwd = getcwd(NULL, 0);
8986 if (cwd == NULL) {
8987 error = got_error_from_errno("getcwd");
8988 goto done;
8991 error = got_repo_pack_fds_open(&pack_fds);
8992 if (error != NULL)
8993 goto done;
8995 error = got_worktree_open(&worktree, cwd);
8996 if (error) {
8997 if (error->code == GOT_ERR_NOT_WORKTREE)
8998 error = wrap_not_worktree_error(error, "cherrypick",
8999 cwd);
9000 goto done;
9003 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9004 NULL, pack_fds);
9005 if (error != NULL)
9006 goto done;
9008 error = apply_unveil(got_repo_get_path(repo), 0,
9009 got_worktree_get_root_path(worktree));
9010 if (error)
9011 goto done;
9013 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9014 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9015 if (error)
9016 goto done;
9017 error = got_object_id_str(&commit_id_str, commit_id);
9018 if (error)
9019 goto done;
9021 error = got_object_open_as_commit(&commit, repo, commit_id);
9022 if (error)
9023 goto done;
9024 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9025 memset(&upa, 0, sizeof(upa));
9026 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9027 commit_id, repo, update_progress, &upa, check_cancelled,
9028 NULL);
9029 if (error != NULL)
9030 goto done;
9032 if (upa.did_something)
9033 printf("Merged commit %s\n", commit_id_str);
9034 print_merge_progress_stats(&upa);
9035 done:
9036 if (commit)
9037 got_object_commit_close(commit);
9038 free(commit_id_str);
9039 if (worktree)
9040 got_worktree_close(worktree);
9041 if (repo) {
9042 const struct got_error *close_err = got_repo_close(repo);
9043 if (error == NULL)
9044 error = close_err;
9046 if (pack_fds) {
9047 const struct got_error *pack_err =
9048 got_repo_pack_fds_close(pack_fds);
9049 if (error == NULL)
9050 error = pack_err;
9051 pack_fds = NULL;
9054 return error;
9057 __dead static void
9058 usage_backout(void)
9060 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9061 exit(1);
9064 static const struct got_error *
9065 cmd_backout(int argc, char *argv[])
9067 const struct got_error *error = NULL;
9068 struct got_worktree *worktree = NULL;
9069 struct got_repository *repo = NULL;
9070 char *cwd = NULL, *commit_id_str = NULL;
9071 struct got_object_id *commit_id = NULL;
9072 struct got_commit_object *commit = NULL;
9073 struct got_object_qid *pid;
9074 int ch;
9075 struct got_update_progress_arg upa;
9076 int *pack_fds = NULL;
9078 while ((ch = getopt(argc, argv, "")) != -1) {
9079 switch (ch) {
9080 default:
9081 usage_backout();
9082 /* NOTREACHED */
9086 argc -= optind;
9087 argv += optind;
9089 #ifndef PROFILE
9090 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9091 "unveil", NULL) == -1)
9092 err(1, "pledge");
9093 #endif
9094 if (argc != 1)
9095 usage_backout();
9097 cwd = getcwd(NULL, 0);
9098 if (cwd == NULL) {
9099 error = got_error_from_errno("getcwd");
9100 goto done;
9103 error = got_repo_pack_fds_open(&pack_fds);
9104 if (error != NULL)
9105 goto done;
9107 error = got_worktree_open(&worktree, cwd);
9108 if (error) {
9109 if (error->code == GOT_ERR_NOT_WORKTREE)
9110 error = wrap_not_worktree_error(error, "backout", cwd);
9111 goto done;
9114 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9115 NULL, pack_fds);
9116 if (error != NULL)
9117 goto done;
9119 error = apply_unveil(got_repo_get_path(repo), 0,
9120 got_worktree_get_root_path(worktree));
9121 if (error)
9122 goto done;
9124 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9125 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9126 if (error)
9127 goto done;
9128 error = got_object_id_str(&commit_id_str, commit_id);
9129 if (error)
9130 goto done;
9132 error = got_object_open_as_commit(&commit, repo, commit_id);
9133 if (error)
9134 goto done;
9135 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9136 if (pid == NULL) {
9137 error = got_error(GOT_ERR_ROOT_COMMIT);
9138 goto done;
9141 memset(&upa, 0, sizeof(upa));
9142 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9143 repo, update_progress, &upa, check_cancelled, NULL);
9144 if (error != NULL)
9145 goto done;
9147 if (upa.did_something)
9148 printf("Backed out commit %s\n", commit_id_str);
9149 print_merge_progress_stats(&upa);
9150 done:
9151 if (commit)
9152 got_object_commit_close(commit);
9153 free(commit_id_str);
9154 if (worktree)
9155 got_worktree_close(worktree);
9156 if (repo) {
9157 const struct got_error *close_err = got_repo_close(repo);
9158 if (error == NULL)
9159 error = close_err;
9161 if (pack_fds) {
9162 const struct got_error *pack_err =
9163 got_repo_pack_fds_close(pack_fds);
9164 if (error == NULL)
9165 error = pack_err;
9166 pack_fds = NULL;
9168 return error;
9171 __dead static void
9172 usage_rebase(void)
9174 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9175 getprogname());
9176 exit(1);
9179 void
9180 trim_logmsg(char *logmsg, int limit)
9182 char *nl;
9183 size_t len;
9185 len = strlen(logmsg);
9186 if (len > limit)
9187 len = limit;
9188 logmsg[len] = '\0';
9189 nl = strchr(logmsg, '\n');
9190 if (nl)
9191 *nl = '\0';
9194 static const struct got_error *
9195 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9197 const struct got_error *err;
9198 char *logmsg0 = NULL;
9199 const char *s;
9201 err = got_object_commit_get_logmsg(&logmsg0, commit);
9202 if (err)
9203 return err;
9205 s = logmsg0;
9206 while (isspace((unsigned char)s[0]))
9207 s++;
9209 *logmsg = strdup(s);
9210 if (*logmsg == NULL) {
9211 err = got_error_from_errno("strdup");
9212 goto done;
9215 trim_logmsg(*logmsg, limit);
9216 done:
9217 free(logmsg0);
9218 return err;
9221 static const struct got_error *
9222 show_rebase_merge_conflict(struct got_object_id *id,
9223 struct got_repository *repo)
9225 const struct got_error *err;
9226 struct got_commit_object *commit = NULL;
9227 char *id_str = NULL, *logmsg = NULL;
9229 err = got_object_open_as_commit(&commit, repo, id);
9230 if (err)
9231 return err;
9233 err = got_object_id_str(&id_str, id);
9234 if (err)
9235 goto done;
9237 id_str[12] = '\0';
9239 err = get_short_logmsg(&logmsg, 42, commit);
9240 if (err)
9241 goto done;
9243 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9244 done:
9245 free(id_str);
9246 got_object_commit_close(commit);
9247 free(logmsg);
9248 return err;
9251 static const struct got_error *
9252 show_rebase_progress(struct got_commit_object *commit,
9253 struct got_object_id *old_id, struct got_object_id *new_id)
9255 const struct got_error *err;
9256 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9258 err = got_object_id_str(&old_id_str, old_id);
9259 if (err)
9260 goto done;
9262 if (new_id) {
9263 err = got_object_id_str(&new_id_str, new_id);
9264 if (err)
9265 goto done;
9268 old_id_str[12] = '\0';
9269 if (new_id_str)
9270 new_id_str[12] = '\0';
9272 err = get_short_logmsg(&logmsg, 42, commit);
9273 if (err)
9274 goto done;
9276 printf("%s -> %s: %s\n", old_id_str,
9277 new_id_str ? new_id_str : "no-op change", logmsg);
9278 done:
9279 free(old_id_str);
9280 free(new_id_str);
9281 free(logmsg);
9282 return err;
9285 static const struct got_error *
9286 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9287 struct got_reference *branch, struct got_reference *new_base_branch,
9288 struct got_reference *tmp_branch, struct got_repository *repo,
9289 int create_backup)
9291 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9292 return got_worktree_rebase_complete(worktree, fileindex,
9293 new_base_branch, tmp_branch, branch, repo, create_backup);
9296 static const struct got_error *
9297 rebase_commit(struct got_pathlist_head *merged_paths,
9298 struct got_worktree *worktree, struct got_fileindex *fileindex,
9299 struct got_reference *tmp_branch,
9300 struct got_object_id *commit_id, struct got_repository *repo)
9302 const struct got_error *error;
9303 struct got_commit_object *commit;
9304 struct got_object_id *new_commit_id;
9306 error = got_object_open_as_commit(&commit, repo, commit_id);
9307 if (error)
9308 return error;
9310 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9311 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9312 if (error) {
9313 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9314 goto done;
9315 error = show_rebase_progress(commit, commit_id, NULL);
9316 } else {
9317 error = show_rebase_progress(commit, commit_id, new_commit_id);
9318 free(new_commit_id);
9320 done:
9321 got_object_commit_close(commit);
9322 return error;
9325 struct check_path_prefix_arg {
9326 const char *path_prefix;
9327 size_t len;
9328 int errcode;
9331 static const struct got_error *
9332 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9333 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9334 struct got_object_id *id1, struct got_object_id *id2,
9335 const char *path1, const char *path2,
9336 mode_t mode1, mode_t mode2, struct got_repository *repo)
9338 struct check_path_prefix_arg *a = arg;
9340 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9341 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9342 return got_error(a->errcode);
9344 return NULL;
9347 static const struct got_error *
9348 check_path_prefix(struct got_object_id *parent_id,
9349 struct got_object_id *commit_id, const char *path_prefix,
9350 int errcode, struct got_repository *repo)
9352 const struct got_error *err;
9353 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9354 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9355 struct check_path_prefix_arg cpp_arg;
9357 if (got_path_is_root_dir(path_prefix))
9358 return NULL;
9360 err = got_object_open_as_commit(&commit, repo, commit_id);
9361 if (err)
9362 goto done;
9364 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9365 if (err)
9366 goto done;
9368 err = got_object_open_as_tree(&tree1, repo,
9369 got_object_commit_get_tree_id(parent_commit));
9370 if (err)
9371 goto done;
9373 err = got_object_open_as_tree(&tree2, repo,
9374 got_object_commit_get_tree_id(commit));
9375 if (err)
9376 goto done;
9378 cpp_arg.path_prefix = path_prefix;
9379 while (cpp_arg.path_prefix[0] == '/')
9380 cpp_arg.path_prefix++;
9381 cpp_arg.len = strlen(cpp_arg.path_prefix);
9382 cpp_arg.errcode = errcode;
9383 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9384 check_path_prefix_in_diff, &cpp_arg, 0);
9385 done:
9386 if (tree1)
9387 got_object_tree_close(tree1);
9388 if (tree2)
9389 got_object_tree_close(tree2);
9390 if (commit)
9391 got_object_commit_close(commit);
9392 if (parent_commit)
9393 got_object_commit_close(parent_commit);
9394 return err;
9397 static const struct got_error *
9398 collect_commits(struct got_object_id_queue *commits,
9399 struct got_object_id *initial_commit_id,
9400 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9401 const char *path_prefix, int path_prefix_errcode,
9402 struct got_repository *repo)
9404 const struct got_error *err = NULL;
9405 struct got_commit_graph *graph = NULL;
9406 struct got_object_id *parent_id = NULL;
9407 struct got_object_qid *qid;
9408 struct got_object_id *commit_id = initial_commit_id;
9410 err = got_commit_graph_open(&graph, "/", 1);
9411 if (err)
9412 return err;
9414 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9415 check_cancelled, NULL);
9416 if (err)
9417 goto done;
9418 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9419 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9420 check_cancelled, NULL);
9421 if (err) {
9422 if (err->code == GOT_ERR_ITER_COMPLETED) {
9423 err = got_error_msg(GOT_ERR_ANCESTRY,
9424 "ran out of commits to rebase before "
9425 "youngest common ancestor commit has "
9426 "been reached?!?");
9428 goto done;
9429 } else {
9430 err = check_path_prefix(parent_id, commit_id,
9431 path_prefix, path_prefix_errcode, repo);
9432 if (err)
9433 goto done;
9435 err = got_object_qid_alloc(&qid, commit_id);
9436 if (err)
9437 goto done;
9438 STAILQ_INSERT_HEAD(commits, qid, entry);
9439 commit_id = parent_id;
9442 done:
9443 got_commit_graph_close(graph);
9444 return err;
9447 static const struct got_error *
9448 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9450 const struct got_error *err = NULL;
9451 time_t committer_time;
9452 struct tm tm;
9453 char datebuf[11]; /* YYYY-MM-DD + NUL */
9454 char *author0 = NULL, *author, *smallerthan;
9455 char *logmsg0 = NULL, *logmsg, *newline;
9457 committer_time = got_object_commit_get_committer_time(commit);
9458 if (gmtime_r(&committer_time, &tm) == NULL)
9459 return got_error_from_errno("gmtime_r");
9460 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9461 return got_error(GOT_ERR_NO_SPACE);
9463 author0 = strdup(got_object_commit_get_author(commit));
9464 if (author0 == NULL)
9465 return got_error_from_errno("strdup");
9466 author = author0;
9467 smallerthan = strchr(author, '<');
9468 if (smallerthan && smallerthan[1] != '\0')
9469 author = smallerthan + 1;
9470 author[strcspn(author, "@>")] = '\0';
9472 err = got_object_commit_get_logmsg(&logmsg0, commit);
9473 if (err)
9474 goto done;
9475 logmsg = logmsg0;
9476 while (*logmsg == '\n')
9477 logmsg++;
9478 newline = strchr(logmsg, '\n');
9479 if (newline)
9480 *newline = '\0';
9482 if (asprintf(brief_str, "%s %s %s",
9483 datebuf, author, logmsg) == -1)
9484 err = got_error_from_errno("asprintf");
9485 done:
9486 free(author0);
9487 free(logmsg0);
9488 return err;
9491 static const struct got_error *
9492 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9493 struct got_repository *repo)
9495 const struct got_error *err;
9496 char *id_str;
9498 err = got_object_id_str(&id_str, id);
9499 if (err)
9500 return err;
9502 err = got_ref_delete(ref, repo);
9503 if (err)
9504 goto done;
9506 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9507 done:
9508 free(id_str);
9509 return err;
9512 static const struct got_error *
9513 print_backup_ref(const char *branch_name, const char *new_id_str,
9514 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9515 struct got_reflist_object_id_map *refs_idmap,
9516 struct got_repository *repo)
9518 const struct got_error *err = NULL;
9519 struct got_reflist_head *refs;
9520 char *refs_str = NULL;
9521 struct got_object_id *new_commit_id = NULL;
9522 struct got_commit_object *new_commit = NULL;
9523 char *new_commit_brief_str = NULL;
9524 struct got_object_id *yca_id = NULL;
9525 struct got_commit_object *yca_commit = NULL;
9526 char *yca_id_str = NULL, *yca_brief_str = NULL;
9527 char *custom_refs_str;
9529 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9530 return got_error_from_errno("asprintf");
9532 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9533 0, 0, refs_idmap, custom_refs_str);
9534 if (err)
9535 goto done;
9537 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9538 if (err)
9539 goto done;
9541 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9542 if (refs) {
9543 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9544 if (err)
9545 goto done;
9548 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9549 if (err)
9550 goto done;
9552 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9553 if (err)
9554 goto done;
9556 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9557 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9558 if (err)
9559 goto done;
9561 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9562 refs_str ? " (" : "", refs_str ? refs_str : "",
9563 refs_str ? ")" : "", new_commit_brief_str);
9564 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9565 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9566 free(refs_str);
9567 refs_str = NULL;
9569 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9570 if (err)
9571 goto done;
9573 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9574 if (err)
9575 goto done;
9577 err = got_object_id_str(&yca_id_str, yca_id);
9578 if (err)
9579 goto done;
9581 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9582 if (refs) {
9583 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9584 if (err)
9585 goto done;
9587 printf("history forked at %s%s%s%s\n %s\n",
9588 yca_id_str,
9589 refs_str ? " (" : "", refs_str ? refs_str : "",
9590 refs_str ? ")" : "", yca_brief_str);
9592 done:
9593 free(custom_refs_str);
9594 free(new_commit_id);
9595 free(refs_str);
9596 free(yca_id);
9597 free(yca_id_str);
9598 free(yca_brief_str);
9599 if (new_commit)
9600 got_object_commit_close(new_commit);
9601 if (yca_commit)
9602 got_object_commit_close(yca_commit);
9604 return NULL;
9607 static const struct got_error *
9608 process_backup_refs(const char *backup_ref_prefix,
9609 const char *wanted_branch_name,
9610 int delete, struct got_repository *repo)
9612 const struct got_error *err;
9613 struct got_reflist_head refs, backup_refs;
9614 struct got_reflist_entry *re;
9615 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9616 struct got_object_id *old_commit_id = NULL;
9617 char *branch_name = NULL;
9618 struct got_commit_object *old_commit = NULL;
9619 struct got_reflist_object_id_map *refs_idmap = NULL;
9620 int wanted_branch_found = 0;
9622 TAILQ_INIT(&refs);
9623 TAILQ_INIT(&backup_refs);
9625 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9626 if (err)
9627 return err;
9629 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9630 if (err)
9631 goto done;
9633 if (wanted_branch_name) {
9634 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9635 wanted_branch_name += 11;
9638 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9639 got_ref_cmp_by_commit_timestamp_descending, repo);
9640 if (err)
9641 goto done;
9643 TAILQ_FOREACH(re, &backup_refs, entry) {
9644 const char *refname = got_ref_get_name(re->ref);
9645 char *slash;
9647 err = check_cancelled(NULL);
9648 if (err)
9649 break;
9651 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9652 if (err)
9653 break;
9655 err = got_object_open_as_commit(&old_commit, repo,
9656 old_commit_id);
9657 if (err)
9658 break;
9660 if (strncmp(backup_ref_prefix, refname,
9661 backup_ref_prefix_len) == 0)
9662 refname += backup_ref_prefix_len;
9664 while (refname[0] == '/')
9665 refname++;
9667 branch_name = strdup(refname);
9668 if (branch_name == NULL) {
9669 err = got_error_from_errno("strdup");
9670 break;
9672 slash = strrchr(branch_name, '/');
9673 if (slash) {
9674 *slash = '\0';
9675 refname += strlen(branch_name) + 1;
9678 if (wanted_branch_name == NULL ||
9679 strcmp(wanted_branch_name, branch_name) == 0) {
9680 wanted_branch_found = 1;
9681 if (delete) {
9682 err = delete_backup_ref(re->ref,
9683 old_commit_id, repo);
9684 } else {
9685 err = print_backup_ref(branch_name, refname,
9686 old_commit_id, old_commit, refs_idmap,
9687 repo);
9689 if (err)
9690 break;
9693 free(old_commit_id);
9694 old_commit_id = NULL;
9695 free(branch_name);
9696 branch_name = NULL;
9697 got_object_commit_close(old_commit);
9698 old_commit = NULL;
9701 if (wanted_branch_name && !wanted_branch_found) {
9702 err = got_error_fmt(GOT_ERR_NOT_REF,
9703 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9705 done:
9706 if (refs_idmap)
9707 got_reflist_object_id_map_free(refs_idmap);
9708 got_ref_list_free(&refs);
9709 got_ref_list_free(&backup_refs);
9710 free(old_commit_id);
9711 free(branch_name);
9712 if (old_commit)
9713 got_object_commit_close(old_commit);
9714 return err;
9717 static const struct got_error *
9718 abort_progress(void *arg, unsigned char status, const char *path)
9721 * Unversioned files should not clutter progress output when
9722 * an operation is aborted.
9724 if (status == GOT_STATUS_UNVERSIONED)
9725 return NULL;
9727 return update_progress(arg, status, path);
9730 static const struct got_error *
9731 cmd_rebase(int argc, char *argv[])
9733 const struct got_error *error = NULL;
9734 struct got_worktree *worktree = NULL;
9735 struct got_repository *repo = NULL;
9736 struct got_fileindex *fileindex = NULL;
9737 char *cwd = NULL;
9738 struct got_reference *branch = NULL;
9739 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9740 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9741 struct got_object_id *resume_commit_id = NULL;
9742 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9743 struct got_commit_object *commit = NULL;
9744 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9745 int histedit_in_progress = 0, merge_in_progress = 0;
9746 int create_backup = 1, list_backups = 0, delete_backups = 0;
9747 struct got_object_id_queue commits;
9748 struct got_pathlist_head merged_paths;
9749 const struct got_object_id_queue *parent_ids;
9750 struct got_object_qid *qid, *pid;
9751 struct got_update_progress_arg upa;
9752 int *pack_fds = NULL;
9754 STAILQ_INIT(&commits);
9755 TAILQ_INIT(&merged_paths);
9756 memset(&upa, 0, sizeof(upa));
9758 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9759 switch (ch) {
9760 case 'a':
9761 abort_rebase = 1;
9762 break;
9763 case 'c':
9764 continue_rebase = 1;
9765 break;
9766 case 'l':
9767 list_backups = 1;
9768 break;
9769 case 'X':
9770 delete_backups = 1;
9771 break;
9772 default:
9773 usage_rebase();
9774 /* NOTREACHED */
9778 argc -= optind;
9779 argv += optind;
9781 #ifndef PROFILE
9782 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9783 "unveil", NULL) == -1)
9784 err(1, "pledge");
9785 #endif
9786 if (list_backups) {
9787 if (abort_rebase)
9788 option_conflict('l', 'a');
9789 if (continue_rebase)
9790 option_conflict('l', 'c');
9791 if (delete_backups)
9792 option_conflict('l', 'X');
9793 if (argc != 0 && argc != 1)
9794 usage_rebase();
9795 } else if (delete_backups) {
9796 if (abort_rebase)
9797 option_conflict('X', 'a');
9798 if (continue_rebase)
9799 option_conflict('X', 'c');
9800 if (list_backups)
9801 option_conflict('l', 'X');
9802 if (argc != 0 && argc != 1)
9803 usage_rebase();
9804 } else {
9805 if (abort_rebase && continue_rebase)
9806 usage_rebase();
9807 else if (abort_rebase || continue_rebase) {
9808 if (argc != 0)
9809 usage_rebase();
9810 } else if (argc != 1)
9811 usage_rebase();
9814 cwd = getcwd(NULL, 0);
9815 if (cwd == NULL) {
9816 error = got_error_from_errno("getcwd");
9817 goto done;
9820 error = got_repo_pack_fds_open(&pack_fds);
9821 if (error != NULL)
9822 goto done;
9824 error = got_worktree_open(&worktree, cwd);
9825 if (error) {
9826 if (list_backups || delete_backups) {
9827 if (error->code != GOT_ERR_NOT_WORKTREE)
9828 goto done;
9829 } else {
9830 if (error->code == GOT_ERR_NOT_WORKTREE)
9831 error = wrap_not_worktree_error(error,
9832 "rebase", cwd);
9833 goto done;
9837 error = got_repo_open(&repo,
9838 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9839 pack_fds);
9840 if (error != NULL)
9841 goto done;
9843 error = apply_unveil(got_repo_get_path(repo), 0,
9844 worktree ? got_worktree_get_root_path(worktree) : NULL);
9845 if (error)
9846 goto done;
9848 if (list_backups || delete_backups) {
9849 error = process_backup_refs(
9850 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9851 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9852 goto done; /* nothing else to do */
9855 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9856 worktree);
9857 if (error)
9858 goto done;
9859 if (histedit_in_progress) {
9860 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9861 goto done;
9864 error = got_worktree_merge_in_progress(&merge_in_progress,
9865 worktree, repo);
9866 if (error)
9867 goto done;
9868 if (merge_in_progress) {
9869 error = got_error(GOT_ERR_MERGE_BUSY);
9870 goto done;
9873 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9874 if (error)
9875 goto done;
9877 if (abort_rebase) {
9878 if (!rebase_in_progress) {
9879 error = got_error(GOT_ERR_NOT_REBASING);
9880 goto done;
9882 error = got_worktree_rebase_continue(&resume_commit_id,
9883 &new_base_branch, &tmp_branch, &branch, &fileindex,
9884 worktree, repo);
9885 if (error)
9886 goto done;
9887 printf("Switching work tree to %s\n",
9888 got_ref_get_symref_target(new_base_branch));
9889 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9890 new_base_branch, abort_progress, &upa);
9891 if (error)
9892 goto done;
9893 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9894 print_merge_progress_stats(&upa);
9895 goto done; /* nothing else to do */
9898 if (continue_rebase) {
9899 if (!rebase_in_progress) {
9900 error = got_error(GOT_ERR_NOT_REBASING);
9901 goto done;
9903 error = got_worktree_rebase_continue(&resume_commit_id,
9904 &new_base_branch, &tmp_branch, &branch, &fileindex,
9905 worktree, repo);
9906 if (error)
9907 goto done;
9909 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9910 resume_commit_id, repo);
9911 if (error)
9912 goto done;
9914 yca_id = got_object_id_dup(resume_commit_id);
9915 if (yca_id == NULL) {
9916 error = got_error_from_errno("got_object_id_dup");
9917 goto done;
9919 } else {
9920 error = got_ref_open(&branch, repo, argv[0], 0);
9921 if (error != NULL)
9922 goto done;
9925 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9926 if (error)
9927 goto done;
9929 if (!continue_rebase) {
9930 struct got_object_id *base_commit_id;
9932 base_commit_id = got_worktree_get_base_commit_id(worktree);
9933 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9934 base_commit_id, branch_head_commit_id, 1, repo,
9935 check_cancelled, NULL);
9936 if (error)
9937 goto done;
9938 if (yca_id == NULL) {
9939 error = got_error_msg(GOT_ERR_ANCESTRY,
9940 "specified branch shares no common ancestry "
9941 "with work tree's branch");
9942 goto done;
9945 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9946 if (error) {
9947 if (error->code != GOT_ERR_ANCESTRY)
9948 goto done;
9949 error = NULL;
9950 } else {
9951 struct got_pathlist_head paths;
9952 printf("%s is already based on %s\n",
9953 got_ref_get_name(branch),
9954 got_worktree_get_head_ref_name(worktree));
9955 error = switch_head_ref(branch, branch_head_commit_id,
9956 worktree, repo);
9957 if (error)
9958 goto done;
9959 error = got_worktree_set_base_commit_id(worktree, repo,
9960 branch_head_commit_id);
9961 if (error)
9962 goto done;
9963 TAILQ_INIT(&paths);
9964 error = got_pathlist_append(&paths, "", NULL);
9965 if (error)
9966 goto done;
9967 error = got_worktree_checkout_files(worktree,
9968 &paths, repo, update_progress, &upa,
9969 check_cancelled, NULL);
9970 got_pathlist_free(&paths);
9971 if (error)
9972 goto done;
9973 if (upa.did_something) {
9974 char *id_str;
9975 error = got_object_id_str(&id_str,
9976 branch_head_commit_id);
9977 if (error)
9978 goto done;
9979 printf("Updated to %s: %s\n",
9980 got_worktree_get_head_ref_name(worktree),
9981 id_str);
9982 free(id_str);
9983 } else
9984 printf("Already up-to-date\n");
9985 print_update_progress_stats(&upa);
9986 goto done;
9990 commit_id = branch_head_commit_id;
9991 error = got_object_open_as_commit(&commit, repo, commit_id);
9992 if (error)
9993 goto done;
9995 parent_ids = got_object_commit_get_parent_ids(commit);
9996 pid = STAILQ_FIRST(parent_ids);
9997 if (pid == NULL) {
9998 error = got_error(GOT_ERR_EMPTY_REBASE);
9999 goto done;
10001 error = collect_commits(&commits, commit_id, &pid->id,
10002 yca_id, got_worktree_get_path_prefix(worktree),
10003 GOT_ERR_REBASE_PATH, repo);
10004 got_object_commit_close(commit);
10005 commit = NULL;
10006 if (error)
10007 goto done;
10009 if (!continue_rebase) {
10010 error = got_worktree_rebase_prepare(&new_base_branch,
10011 &tmp_branch, &fileindex, worktree, branch, repo);
10012 if (error)
10013 goto done;
10016 if (STAILQ_EMPTY(&commits)) {
10017 if (continue_rebase) {
10018 error = rebase_complete(worktree, fileindex,
10019 branch, new_base_branch, tmp_branch, repo,
10020 create_backup);
10021 goto done;
10022 } else {
10023 /* Fast-forward the reference of the branch. */
10024 struct got_object_id *new_head_commit_id;
10025 char *id_str;
10026 error = got_ref_resolve(&new_head_commit_id, repo,
10027 new_base_branch);
10028 if (error)
10029 goto done;
10030 error = got_object_id_str(&id_str, new_head_commit_id);
10031 printf("Forwarding %s to commit %s\n",
10032 got_ref_get_name(branch), id_str);
10033 free(id_str);
10034 error = got_ref_change_ref(branch,
10035 new_head_commit_id);
10036 if (error)
10037 goto done;
10038 /* No backup needed since objects did not change. */
10039 create_backup = 0;
10043 pid = NULL;
10044 STAILQ_FOREACH(qid, &commits, entry) {
10046 commit_id = &qid->id;
10047 parent_id = pid ? &pid->id : yca_id;
10048 pid = qid;
10050 memset(&upa, 0, sizeof(upa));
10051 error = got_worktree_rebase_merge_files(&merged_paths,
10052 worktree, fileindex, parent_id, commit_id, repo,
10053 update_progress, &upa, check_cancelled, NULL);
10054 if (error)
10055 goto done;
10057 print_merge_progress_stats(&upa);
10058 if (upa.conflicts > 0 || upa.missing > 0 ||
10059 upa.not_deleted > 0 || upa.unversioned > 0) {
10060 if (upa.conflicts > 0) {
10061 error = show_rebase_merge_conflict(&qid->id,
10062 repo);
10063 if (error)
10064 goto done;
10066 got_worktree_rebase_pathlist_free(&merged_paths);
10067 break;
10070 error = rebase_commit(&merged_paths, worktree, fileindex,
10071 tmp_branch, commit_id, repo);
10072 got_worktree_rebase_pathlist_free(&merged_paths);
10073 if (error)
10074 goto done;
10077 if (upa.conflicts > 0 || upa.missing > 0 ||
10078 upa.not_deleted > 0 || upa.unversioned > 0) {
10079 error = got_worktree_rebase_postpone(worktree, fileindex);
10080 if (error)
10081 goto done;
10082 if (upa.conflicts > 0 && upa.missing == 0 &&
10083 upa.not_deleted == 0 && upa.unversioned == 0) {
10084 error = got_error_msg(GOT_ERR_CONFLICTS,
10085 "conflicts must be resolved before rebasing "
10086 "can continue");
10087 } else if (upa.conflicts > 0) {
10088 error = got_error_msg(GOT_ERR_CONFLICTS,
10089 "conflicts must be resolved before rebasing "
10090 "can continue; changes destined for some "
10091 "files were not yet merged and should be "
10092 "merged manually if required before the "
10093 "rebase operation is continued");
10094 } else {
10095 error = got_error_msg(GOT_ERR_CONFLICTS,
10096 "changes destined for some files were not "
10097 "yet merged and should be merged manually "
10098 "if required before the rebase operation "
10099 "is continued");
10101 } else
10102 error = rebase_complete(worktree, fileindex, branch,
10103 new_base_branch, tmp_branch, repo, create_backup);
10104 done:
10105 got_object_id_queue_free(&commits);
10106 free(branch_head_commit_id);
10107 free(resume_commit_id);
10108 free(yca_id);
10109 if (commit)
10110 got_object_commit_close(commit);
10111 if (branch)
10112 got_ref_close(branch);
10113 if (new_base_branch)
10114 got_ref_close(new_base_branch);
10115 if (tmp_branch)
10116 got_ref_close(tmp_branch);
10117 if (worktree)
10118 got_worktree_close(worktree);
10119 if (repo) {
10120 const struct got_error *close_err = got_repo_close(repo);
10121 if (error == NULL)
10122 error = close_err;
10124 if (pack_fds) {
10125 const struct got_error *pack_err =
10126 got_repo_pack_fds_close(pack_fds);
10127 if (error == NULL)
10128 error = pack_err;
10129 pack_fds = NULL;
10131 return error;
10134 __dead static void
10135 usage_histedit(void)
10137 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10138 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10139 getprogname());
10140 exit(1);
10143 #define GOT_HISTEDIT_PICK 'p'
10144 #define GOT_HISTEDIT_EDIT 'e'
10145 #define GOT_HISTEDIT_FOLD 'f'
10146 #define GOT_HISTEDIT_DROP 'd'
10147 #define GOT_HISTEDIT_MESG 'm'
10149 static const struct got_histedit_cmd {
10150 unsigned char code;
10151 const char *name;
10152 const char *desc;
10153 } got_histedit_cmds[] = {
10154 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10155 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10156 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10157 "be used" },
10158 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10159 { GOT_HISTEDIT_MESG, "mesg",
10160 "single-line log message for commit above (open editor if empty)" },
10163 struct got_histedit_list_entry {
10164 TAILQ_ENTRY(got_histedit_list_entry) entry;
10165 struct got_object_id *commit_id;
10166 const struct got_histedit_cmd *cmd;
10167 char *logmsg;
10169 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10171 static const struct got_error *
10172 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10173 FILE *f, struct got_repository *repo)
10175 const struct got_error *err = NULL;
10176 char *logmsg = NULL, *id_str = NULL;
10177 struct got_commit_object *commit = NULL;
10178 int n;
10180 err = got_object_open_as_commit(&commit, repo, commit_id);
10181 if (err)
10182 goto done;
10184 err = get_short_logmsg(&logmsg, 34, commit);
10185 if (err)
10186 goto done;
10188 err = got_object_id_str(&id_str, commit_id);
10189 if (err)
10190 goto done;
10192 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10193 if (n < 0)
10194 err = got_ferror(f, GOT_ERR_IO);
10195 done:
10196 if (commit)
10197 got_object_commit_close(commit);
10198 free(id_str);
10199 free(logmsg);
10200 return err;
10203 static const struct got_error *
10204 histedit_write_commit_list(struct got_object_id_queue *commits,
10205 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10206 struct got_repository *repo)
10208 const struct got_error *err = NULL;
10209 struct got_object_qid *qid;
10210 const char *histedit_cmd = NULL;
10212 if (STAILQ_EMPTY(commits))
10213 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10215 STAILQ_FOREACH(qid, commits, entry) {
10216 histedit_cmd = got_histedit_cmds[0].name;
10217 if (edit_only)
10218 histedit_cmd = "edit";
10219 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10220 histedit_cmd = "fold";
10221 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10222 if (err)
10223 break;
10224 if (edit_logmsg_only) {
10225 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10226 if (n < 0) {
10227 err = got_ferror(f, GOT_ERR_IO);
10228 break;
10233 return err;
10236 static const struct got_error *
10237 write_cmd_list(FILE *f, const char *branch_name,
10238 struct got_object_id_queue *commits)
10240 const struct got_error *err = NULL;
10241 size_t i;
10242 int n;
10243 char *id_str;
10244 struct got_object_qid *qid;
10246 qid = STAILQ_FIRST(commits);
10247 err = got_object_id_str(&id_str, &qid->id);
10248 if (err)
10249 return err;
10251 n = fprintf(f,
10252 "# Editing the history of branch '%s' starting at\n"
10253 "# commit %s\n"
10254 "# Commits will be processed in order from top to "
10255 "bottom of this file.\n", branch_name, id_str);
10256 if (n < 0) {
10257 err = got_ferror(f, GOT_ERR_IO);
10258 goto done;
10261 n = fprintf(f, "# Available histedit commands:\n");
10262 if (n < 0) {
10263 err = got_ferror(f, GOT_ERR_IO);
10264 goto done;
10267 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10268 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10269 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10270 cmd->desc);
10271 if (n < 0) {
10272 err = got_ferror(f, GOT_ERR_IO);
10273 break;
10276 done:
10277 free(id_str);
10278 return err;
10281 static const struct got_error *
10282 histedit_syntax_error(int lineno)
10284 static char msg[42];
10285 int ret;
10287 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10288 lineno);
10289 if (ret == -1 || ret >= sizeof(msg))
10290 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10292 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10295 static const struct got_error *
10296 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10297 char *logmsg, struct got_repository *repo)
10299 const struct got_error *err;
10300 struct got_commit_object *folded_commit = NULL;
10301 char *id_str, *folded_logmsg = NULL;
10303 err = got_object_id_str(&id_str, hle->commit_id);
10304 if (err)
10305 return err;
10307 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10308 if (err)
10309 goto done;
10311 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10312 if (err)
10313 goto done;
10314 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10315 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10316 folded_logmsg) == -1) {
10317 err = got_error_from_errno("asprintf");
10319 done:
10320 if (folded_commit)
10321 got_object_commit_close(folded_commit);
10322 free(id_str);
10323 free(folded_logmsg);
10324 return err;
10327 static struct got_histedit_list_entry *
10328 get_folded_commits(struct got_histedit_list_entry *hle)
10330 struct got_histedit_list_entry *prev, *folded = NULL;
10332 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10333 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10334 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10335 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10336 folded = prev;
10337 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10340 return folded;
10343 static const struct got_error *
10344 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10345 struct got_repository *repo)
10347 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10348 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10349 const struct got_error *err = NULL;
10350 struct got_commit_object *commit = NULL;
10351 int logmsg_len;
10352 int fd;
10353 struct got_histedit_list_entry *folded = NULL;
10355 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10356 if (err)
10357 return err;
10359 folded = get_folded_commits(hle);
10360 if (folded) {
10361 while (folded != hle) {
10362 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10363 folded = TAILQ_NEXT(folded, entry);
10364 continue;
10366 err = append_folded_commit_msg(&new_msg, folded,
10367 logmsg, repo);
10368 if (err)
10369 goto done;
10370 free(logmsg);
10371 logmsg = new_msg;
10372 folded = TAILQ_NEXT(folded, entry);
10376 err = got_object_id_str(&id_str, hle->commit_id);
10377 if (err)
10378 goto done;
10379 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10380 if (err)
10381 goto done;
10382 logmsg_len = asprintf(&new_msg,
10383 "%s\n# original log message of commit %s: %s",
10384 logmsg ? logmsg : "", id_str, orig_logmsg);
10385 if (logmsg_len == -1) {
10386 err = got_error_from_errno("asprintf");
10387 goto done;
10389 free(logmsg);
10390 logmsg = new_msg;
10392 err = got_object_id_str(&id_str, hle->commit_id);
10393 if (err)
10394 goto done;
10396 err = got_opentemp_named_fd(&logmsg_path, &fd,
10397 GOT_TMPDIR_STR "/got-logmsg");
10398 if (err)
10399 goto done;
10401 write(fd, logmsg, logmsg_len);
10402 close(fd);
10404 err = get_editor(&editor);
10405 if (err)
10406 goto done;
10408 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10409 logmsg_len, 0);
10410 if (err) {
10411 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10412 goto done;
10413 err = NULL;
10414 hle->logmsg = strdup(new_msg);
10415 if (hle->logmsg == NULL)
10416 err = got_error_from_errno("strdup");
10418 done:
10419 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10420 err = got_error_from_errno2("unlink", logmsg_path);
10421 free(logmsg_path);
10422 free(logmsg);
10423 free(orig_logmsg);
10424 free(editor);
10425 if (commit)
10426 got_object_commit_close(commit);
10427 return err;
10430 static const struct got_error *
10431 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10432 FILE *f, struct got_repository *repo)
10434 const struct got_error *err = NULL;
10435 char *line = NULL, *p, *end;
10436 size_t i, size;
10437 ssize_t len;
10438 int lineno = 0;
10439 const struct got_histedit_cmd *cmd;
10440 struct got_object_id *commit_id = NULL;
10441 struct got_histedit_list_entry *hle = NULL;
10443 for (;;) {
10444 len = getline(&line, &size, f);
10445 if (len == -1) {
10446 const struct got_error *getline_err;
10447 if (feof(f))
10448 break;
10449 getline_err = got_error_from_errno("getline");
10450 err = got_ferror(f, getline_err->code);
10451 break;
10453 lineno++;
10454 p = line;
10455 while (isspace((unsigned char)p[0]))
10456 p++;
10457 if (p[0] == '#' || p[0] == '\0') {
10458 free(line);
10459 line = NULL;
10460 continue;
10462 cmd = NULL;
10463 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10464 cmd = &got_histedit_cmds[i];
10465 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10466 isspace((unsigned char)p[strlen(cmd->name)])) {
10467 p += strlen(cmd->name);
10468 break;
10470 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10471 p++;
10472 break;
10475 if (i == nitems(got_histedit_cmds)) {
10476 err = histedit_syntax_error(lineno);
10477 break;
10479 while (isspace((unsigned char)p[0]))
10480 p++;
10481 if (cmd->code == GOT_HISTEDIT_MESG) {
10482 if (hle == NULL || hle->logmsg != NULL) {
10483 err = got_error(GOT_ERR_HISTEDIT_CMD);
10484 break;
10486 if (p[0] == '\0') {
10487 err = histedit_edit_logmsg(hle, repo);
10488 if (err)
10489 break;
10490 } else {
10491 hle->logmsg = strdup(p);
10492 if (hle->logmsg == NULL) {
10493 err = got_error_from_errno("strdup");
10494 break;
10497 free(line);
10498 line = NULL;
10499 continue;
10500 } else {
10501 end = p;
10502 while (end[0] && !isspace((unsigned char)end[0]))
10503 end++;
10504 *end = '\0';
10506 err = got_object_resolve_id_str(&commit_id, repo, p);
10507 if (err) {
10508 /* override error code */
10509 err = histedit_syntax_error(lineno);
10510 break;
10513 hle = malloc(sizeof(*hle));
10514 if (hle == NULL) {
10515 err = got_error_from_errno("malloc");
10516 break;
10518 hle->cmd = cmd;
10519 hle->commit_id = commit_id;
10520 hle->logmsg = NULL;
10521 commit_id = NULL;
10522 free(line);
10523 line = NULL;
10524 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10527 free(line);
10528 free(commit_id);
10529 return err;
10532 static const struct got_error *
10533 histedit_check_script(struct got_histedit_list *histedit_cmds,
10534 struct got_object_id_queue *commits, struct got_repository *repo)
10536 const struct got_error *err = NULL;
10537 struct got_object_qid *qid;
10538 struct got_histedit_list_entry *hle;
10539 static char msg[92];
10540 char *id_str;
10542 if (TAILQ_EMPTY(histedit_cmds))
10543 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10544 "histedit script contains no commands");
10545 if (STAILQ_EMPTY(commits))
10546 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10548 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10549 struct got_histedit_list_entry *hle2;
10550 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10551 if (hle == hle2)
10552 continue;
10553 if (got_object_id_cmp(hle->commit_id,
10554 hle2->commit_id) != 0)
10555 continue;
10556 err = got_object_id_str(&id_str, hle->commit_id);
10557 if (err)
10558 return err;
10559 snprintf(msg, sizeof(msg), "commit %s is listed "
10560 "more than once in histedit script", id_str);
10561 free(id_str);
10562 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10566 STAILQ_FOREACH(qid, commits, entry) {
10567 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10568 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10569 break;
10571 if (hle == NULL) {
10572 err = got_object_id_str(&id_str, &qid->id);
10573 if (err)
10574 return err;
10575 snprintf(msg, sizeof(msg),
10576 "commit %s missing from histedit script", id_str);
10577 free(id_str);
10578 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10582 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10583 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10584 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10585 "last commit in histedit script cannot be folded");
10587 return NULL;
10590 static const struct got_error *
10591 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10592 const char *path, struct got_object_id_queue *commits,
10593 struct got_repository *repo)
10595 const struct got_error *err = NULL;
10596 char *editor;
10597 FILE *f = NULL;
10599 err = get_editor(&editor);
10600 if (err)
10601 return err;
10603 if (spawn_editor(editor, path) == -1) {
10604 err = got_error_from_errno("failed spawning editor");
10605 goto done;
10608 f = fopen(path, "re");
10609 if (f == NULL) {
10610 err = got_error_from_errno("fopen");
10611 goto done;
10613 err = histedit_parse_list(histedit_cmds, f, repo);
10614 if (err)
10615 goto done;
10617 err = histedit_check_script(histedit_cmds, commits, repo);
10618 done:
10619 if (f && fclose(f) == EOF && err == NULL)
10620 err = got_error_from_errno("fclose");
10621 free(editor);
10622 return err;
10625 static const struct got_error *
10626 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10627 struct got_object_id_queue *, const char *, const char *,
10628 struct got_repository *);
10630 static const struct got_error *
10631 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10632 struct got_object_id_queue *commits, const char *branch_name,
10633 int edit_logmsg_only, int fold_only, int edit_only,
10634 struct got_repository *repo)
10636 const struct got_error *err;
10637 FILE *f = NULL;
10638 char *path = NULL;
10640 err = got_opentemp_named(&path, &f, "got-histedit");
10641 if (err)
10642 return err;
10644 err = write_cmd_list(f, branch_name, commits);
10645 if (err)
10646 goto done;
10648 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10649 fold_only, edit_only, repo);
10650 if (err)
10651 goto done;
10653 if (edit_logmsg_only || fold_only || edit_only) {
10654 rewind(f);
10655 err = histedit_parse_list(histedit_cmds, f, repo);
10656 } else {
10657 if (fclose(f) == EOF) {
10658 err = got_error_from_errno("fclose");
10659 goto done;
10661 f = NULL;
10662 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10663 if (err) {
10664 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10665 err->code != GOT_ERR_HISTEDIT_CMD)
10666 goto done;
10667 err = histedit_edit_list_retry(histedit_cmds, err,
10668 commits, path, branch_name, repo);
10671 done:
10672 if (f && fclose(f) == EOF && err == NULL)
10673 err = got_error_from_errno("fclose");
10674 if (path && unlink(path) != 0 && err == NULL)
10675 err = got_error_from_errno2("unlink", path);
10676 free(path);
10677 return err;
10680 static const struct got_error *
10681 histedit_save_list(struct got_histedit_list *histedit_cmds,
10682 struct got_worktree *worktree, struct got_repository *repo)
10684 const struct got_error *err = NULL;
10685 char *path = NULL;
10686 FILE *f = NULL;
10687 struct got_histedit_list_entry *hle;
10688 struct got_commit_object *commit = NULL;
10690 err = got_worktree_get_histedit_script_path(&path, worktree);
10691 if (err)
10692 return err;
10694 f = fopen(path, "we");
10695 if (f == NULL) {
10696 err = got_error_from_errno2("fopen", path);
10697 goto done;
10699 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10700 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10701 repo);
10702 if (err)
10703 break;
10705 if (hle->logmsg) {
10706 int n = fprintf(f, "%c %s\n",
10707 GOT_HISTEDIT_MESG, hle->logmsg);
10708 if (n < 0) {
10709 err = got_ferror(f, GOT_ERR_IO);
10710 break;
10714 done:
10715 if (f && fclose(f) == EOF && err == NULL)
10716 err = got_error_from_errno("fclose");
10717 free(path);
10718 if (commit)
10719 got_object_commit_close(commit);
10720 return err;
10723 void
10724 histedit_free_list(struct got_histedit_list *histedit_cmds)
10726 struct got_histedit_list_entry *hle;
10728 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10729 TAILQ_REMOVE(histedit_cmds, hle, entry);
10730 free(hle);
10734 static const struct got_error *
10735 histedit_load_list(struct got_histedit_list *histedit_cmds,
10736 const char *path, struct got_repository *repo)
10738 const struct got_error *err = NULL;
10739 FILE *f = NULL;
10741 f = fopen(path, "re");
10742 if (f == NULL) {
10743 err = got_error_from_errno2("fopen", path);
10744 goto done;
10747 err = histedit_parse_list(histedit_cmds, f, repo);
10748 done:
10749 if (f && fclose(f) == EOF && err == NULL)
10750 err = got_error_from_errno("fclose");
10751 return err;
10754 static const struct got_error *
10755 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10756 const struct got_error *edit_err, struct got_object_id_queue *commits,
10757 const char *path, const char *branch_name, struct got_repository *repo)
10759 const struct got_error *err = NULL, *prev_err = edit_err;
10760 int resp = ' ';
10762 while (resp != 'c' && resp != 'r' && resp != 'a') {
10763 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10764 "or (a)bort: ", getprogname(), prev_err->msg);
10765 resp = getchar();
10766 if (resp == '\n')
10767 resp = getchar();
10768 if (resp == 'c') {
10769 histedit_free_list(histedit_cmds);
10770 err = histedit_run_editor(histedit_cmds, path, commits,
10771 repo);
10772 if (err) {
10773 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10774 err->code != GOT_ERR_HISTEDIT_CMD)
10775 break;
10776 prev_err = err;
10777 resp = ' ';
10778 continue;
10780 break;
10781 } else if (resp == 'r') {
10782 histedit_free_list(histedit_cmds);
10783 err = histedit_edit_script(histedit_cmds,
10784 commits, branch_name, 0, 0, 0, repo);
10785 if (err) {
10786 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10787 err->code != GOT_ERR_HISTEDIT_CMD)
10788 break;
10789 prev_err = err;
10790 resp = ' ';
10791 continue;
10793 break;
10794 } else if (resp == 'a') {
10795 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10796 break;
10797 } else
10798 printf("invalid response '%c'\n", resp);
10801 return err;
10804 static const struct got_error *
10805 histedit_complete(struct got_worktree *worktree,
10806 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10807 struct got_reference *branch, struct got_repository *repo)
10809 printf("Switching work tree to %s\n",
10810 got_ref_get_symref_target(branch));
10811 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10812 branch, repo);
10815 static const struct got_error *
10816 show_histedit_progress(struct got_commit_object *commit,
10817 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10819 const struct got_error *err;
10820 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10822 err = got_object_id_str(&old_id_str, hle->commit_id);
10823 if (err)
10824 goto done;
10826 if (new_id) {
10827 err = got_object_id_str(&new_id_str, new_id);
10828 if (err)
10829 goto done;
10832 old_id_str[12] = '\0';
10833 if (new_id_str)
10834 new_id_str[12] = '\0';
10836 if (hle->logmsg) {
10837 logmsg = strdup(hle->logmsg);
10838 if (logmsg == NULL) {
10839 err = got_error_from_errno("strdup");
10840 goto done;
10842 trim_logmsg(logmsg, 42);
10843 } else {
10844 err = get_short_logmsg(&logmsg, 42, commit);
10845 if (err)
10846 goto done;
10849 switch (hle->cmd->code) {
10850 case GOT_HISTEDIT_PICK:
10851 case GOT_HISTEDIT_EDIT:
10852 printf("%s -> %s: %s\n", old_id_str,
10853 new_id_str ? new_id_str : "no-op change", logmsg);
10854 break;
10855 case GOT_HISTEDIT_DROP:
10856 case GOT_HISTEDIT_FOLD:
10857 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10858 logmsg);
10859 break;
10860 default:
10861 break;
10863 done:
10864 free(old_id_str);
10865 free(new_id_str);
10866 return err;
10869 static const struct got_error *
10870 histedit_commit(struct got_pathlist_head *merged_paths,
10871 struct got_worktree *worktree, struct got_fileindex *fileindex,
10872 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10873 struct got_repository *repo)
10875 const struct got_error *err;
10876 struct got_commit_object *commit;
10877 struct got_object_id *new_commit_id;
10879 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10880 && hle->logmsg == NULL) {
10881 err = histedit_edit_logmsg(hle, repo);
10882 if (err)
10883 return err;
10886 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10887 if (err)
10888 return err;
10890 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10891 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10892 hle->logmsg, repo);
10893 if (err) {
10894 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10895 goto done;
10896 err = show_histedit_progress(commit, hle, NULL);
10897 } else {
10898 err = show_histedit_progress(commit, hle, new_commit_id);
10899 free(new_commit_id);
10901 done:
10902 got_object_commit_close(commit);
10903 return err;
10906 static const struct got_error *
10907 histedit_skip_commit(struct got_histedit_list_entry *hle,
10908 struct got_worktree *worktree, struct got_repository *repo)
10910 const struct got_error *error;
10911 struct got_commit_object *commit;
10913 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10914 repo);
10915 if (error)
10916 return error;
10918 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10919 if (error)
10920 return error;
10922 error = show_histedit_progress(commit, hle, NULL);
10923 got_object_commit_close(commit);
10924 return error;
10927 static const struct got_error *
10928 check_local_changes(void *arg, unsigned char status,
10929 unsigned char staged_status, const char *path,
10930 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10931 struct got_object_id *commit_id, int dirfd, const char *de_name)
10933 int *have_local_changes = arg;
10935 switch (status) {
10936 case GOT_STATUS_ADD:
10937 case GOT_STATUS_DELETE:
10938 case GOT_STATUS_MODIFY:
10939 case GOT_STATUS_CONFLICT:
10940 *have_local_changes = 1;
10941 return got_error(GOT_ERR_CANCELLED);
10942 default:
10943 break;
10946 switch (staged_status) {
10947 case GOT_STATUS_ADD:
10948 case GOT_STATUS_DELETE:
10949 case GOT_STATUS_MODIFY:
10950 *have_local_changes = 1;
10951 return got_error(GOT_ERR_CANCELLED);
10952 default:
10953 break;
10956 return NULL;
10959 static const struct got_error *
10960 cmd_histedit(int argc, char *argv[])
10962 const struct got_error *error = NULL;
10963 struct got_worktree *worktree = NULL;
10964 struct got_fileindex *fileindex = NULL;
10965 struct got_repository *repo = NULL;
10966 char *cwd = NULL;
10967 struct got_reference *branch = NULL;
10968 struct got_reference *tmp_branch = NULL;
10969 struct got_object_id *resume_commit_id = NULL;
10970 struct got_object_id *base_commit_id = NULL;
10971 struct got_object_id *head_commit_id = NULL;
10972 struct got_commit_object *commit = NULL;
10973 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10974 struct got_update_progress_arg upa;
10975 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10976 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10977 int list_backups = 0, delete_backups = 0;
10978 const char *edit_script_path = NULL;
10979 struct got_object_id_queue commits;
10980 struct got_pathlist_head merged_paths;
10981 const struct got_object_id_queue *parent_ids;
10982 struct got_object_qid *pid;
10983 struct got_histedit_list histedit_cmds;
10984 struct got_histedit_list_entry *hle;
10985 int *pack_fds = NULL;
10987 STAILQ_INIT(&commits);
10988 TAILQ_INIT(&histedit_cmds);
10989 TAILQ_INIT(&merged_paths);
10990 memset(&upa, 0, sizeof(upa));
10992 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10993 switch (ch) {
10994 case 'a':
10995 abort_edit = 1;
10996 break;
10997 case 'c':
10998 continue_edit = 1;
10999 break;
11000 case 'e':
11001 edit_only = 1;
11002 break;
11003 case 'f':
11004 fold_only = 1;
11005 break;
11006 case 'F':
11007 edit_script_path = optarg;
11008 break;
11009 case 'm':
11010 edit_logmsg_only = 1;
11011 break;
11012 case 'l':
11013 list_backups = 1;
11014 break;
11015 case 'X':
11016 delete_backups = 1;
11017 break;
11018 default:
11019 usage_histedit();
11020 /* NOTREACHED */
11024 argc -= optind;
11025 argv += optind;
11027 #ifndef PROFILE
11028 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11029 "unveil", NULL) == -1)
11030 err(1, "pledge");
11031 #endif
11032 if (abort_edit && continue_edit)
11033 option_conflict('a', 'c');
11034 if (edit_script_path && edit_logmsg_only)
11035 option_conflict('F', 'm');
11036 if (abort_edit && edit_logmsg_only)
11037 option_conflict('a', 'm');
11038 if (continue_edit && edit_logmsg_only)
11039 option_conflict('c', 'm');
11040 if (abort_edit && fold_only)
11041 option_conflict('a', 'f');
11042 if (continue_edit && fold_only)
11043 option_conflict('c', 'f');
11044 if (fold_only && edit_logmsg_only)
11045 option_conflict('f', 'm');
11046 if (edit_script_path && fold_only)
11047 option_conflict('F', 'f');
11048 if (abort_edit && edit_only)
11049 option_conflict('a', 'e');
11050 if (continue_edit && edit_only)
11051 option_conflict('c', 'e');
11052 if (edit_only && edit_logmsg_only)
11053 option_conflict('e', 'm');
11054 if (edit_script_path && edit_only)
11055 option_conflict('F', 'e');
11056 if (list_backups) {
11057 if (abort_edit)
11058 option_conflict('l', 'a');
11059 if (continue_edit)
11060 option_conflict('l', 'c');
11061 if (edit_script_path)
11062 option_conflict('l', 'F');
11063 if (edit_logmsg_only)
11064 option_conflict('l', 'm');
11065 if (fold_only)
11066 option_conflict('l', 'f');
11067 if (edit_only)
11068 option_conflict('l', 'e');
11069 if (delete_backups)
11070 option_conflict('l', 'X');
11071 if (argc != 0 && argc != 1)
11072 usage_histedit();
11073 } else if (delete_backups) {
11074 if (abort_edit)
11075 option_conflict('X', 'a');
11076 if (continue_edit)
11077 option_conflict('X', 'c');
11078 if (edit_script_path)
11079 option_conflict('X', 'F');
11080 if (edit_logmsg_only)
11081 option_conflict('X', 'm');
11082 if (fold_only)
11083 option_conflict('X', 'f');
11084 if (edit_only)
11085 option_conflict('X', 'e');
11086 if (list_backups)
11087 option_conflict('X', 'l');
11088 if (argc != 0 && argc != 1)
11089 usage_histedit();
11090 } else if (argc != 0)
11091 usage_histedit();
11094 * This command cannot apply unveil(2) in all cases because the
11095 * user may choose to run an editor to edit the histedit script
11096 * and to edit individual commit log messages.
11097 * unveil(2) traverses exec(2); if an editor is used we have to
11098 * apply unveil after edit script and log messages have been written.
11099 * XXX TODO: Make use of unveil(2) where possible.
11102 cwd = getcwd(NULL, 0);
11103 if (cwd == NULL) {
11104 error = got_error_from_errno("getcwd");
11105 goto done;
11108 error = got_repo_pack_fds_open(&pack_fds);
11109 if (error != NULL)
11110 goto done;
11112 error = got_worktree_open(&worktree, cwd);
11113 if (error) {
11114 if (list_backups || delete_backups) {
11115 if (error->code != GOT_ERR_NOT_WORKTREE)
11116 goto done;
11117 } else {
11118 if (error->code == GOT_ERR_NOT_WORKTREE)
11119 error = wrap_not_worktree_error(error,
11120 "histedit", cwd);
11121 goto done;
11125 if (list_backups || delete_backups) {
11126 error = got_repo_open(&repo,
11127 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11128 NULL, pack_fds);
11129 if (error != NULL)
11130 goto done;
11131 error = apply_unveil(got_repo_get_path(repo), 0,
11132 worktree ? got_worktree_get_root_path(worktree) : NULL);
11133 if (error)
11134 goto done;
11135 error = process_backup_refs(
11136 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11137 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11138 goto done; /* nothing else to do */
11141 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11142 NULL, pack_fds);
11143 if (error != NULL)
11144 goto done;
11146 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11147 if (error)
11148 goto done;
11149 if (rebase_in_progress) {
11150 error = got_error(GOT_ERR_REBASING);
11151 goto done;
11154 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11155 repo);
11156 if (error)
11157 goto done;
11158 if (merge_in_progress) {
11159 error = got_error(GOT_ERR_MERGE_BUSY);
11160 goto done;
11163 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11164 if (error)
11165 goto done;
11167 if (edit_in_progress && edit_logmsg_only) {
11168 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11169 "histedit operation is in progress in this "
11170 "work tree and must be continued or aborted "
11171 "before the -m option can be used");
11172 goto done;
11174 if (edit_in_progress && fold_only) {
11175 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11176 "histedit operation is in progress in this "
11177 "work tree and must be continued or aborted "
11178 "before the -f option can be used");
11179 goto done;
11181 if (edit_in_progress && edit_only) {
11182 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11183 "histedit operation is in progress in this "
11184 "work tree and must be continued or aborted "
11185 "before the -e option can be used");
11186 goto done;
11189 if (edit_in_progress && abort_edit) {
11190 error = got_worktree_histedit_continue(&resume_commit_id,
11191 &tmp_branch, &branch, &base_commit_id, &fileindex,
11192 worktree, repo);
11193 if (error)
11194 goto done;
11195 printf("Switching work tree to %s\n",
11196 got_ref_get_symref_target(branch));
11197 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11198 branch, base_commit_id, abort_progress, &upa);
11199 if (error)
11200 goto done;
11201 printf("Histedit of %s aborted\n",
11202 got_ref_get_symref_target(branch));
11203 print_merge_progress_stats(&upa);
11204 goto done; /* nothing else to do */
11205 } else if (abort_edit) {
11206 error = got_error(GOT_ERR_NOT_HISTEDIT);
11207 goto done;
11210 if (continue_edit) {
11211 char *path;
11213 if (!edit_in_progress) {
11214 error = got_error(GOT_ERR_NOT_HISTEDIT);
11215 goto done;
11218 error = got_worktree_get_histedit_script_path(&path, worktree);
11219 if (error)
11220 goto done;
11222 error = histedit_load_list(&histedit_cmds, path, repo);
11223 free(path);
11224 if (error)
11225 goto done;
11227 error = got_worktree_histedit_continue(&resume_commit_id,
11228 &tmp_branch, &branch, &base_commit_id, &fileindex,
11229 worktree, repo);
11230 if (error)
11231 goto done;
11233 error = got_ref_resolve(&head_commit_id, repo, branch);
11234 if (error)
11235 goto done;
11237 error = got_object_open_as_commit(&commit, repo,
11238 head_commit_id);
11239 if (error)
11240 goto done;
11241 parent_ids = got_object_commit_get_parent_ids(commit);
11242 pid = STAILQ_FIRST(parent_ids);
11243 if (pid == NULL) {
11244 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11245 goto done;
11247 error = collect_commits(&commits, head_commit_id, &pid->id,
11248 base_commit_id, got_worktree_get_path_prefix(worktree),
11249 GOT_ERR_HISTEDIT_PATH, repo);
11250 got_object_commit_close(commit);
11251 commit = NULL;
11252 if (error)
11253 goto done;
11254 } else {
11255 if (edit_in_progress) {
11256 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11257 goto done;
11260 error = got_ref_open(&branch, repo,
11261 got_worktree_get_head_ref_name(worktree), 0);
11262 if (error != NULL)
11263 goto done;
11265 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11266 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11267 "will not edit commit history of a branch outside "
11268 "the \"refs/heads/\" reference namespace");
11269 goto done;
11272 error = got_ref_resolve(&head_commit_id, repo, branch);
11273 got_ref_close(branch);
11274 branch = NULL;
11275 if (error)
11276 goto done;
11278 error = got_object_open_as_commit(&commit, repo,
11279 head_commit_id);
11280 if (error)
11281 goto done;
11282 parent_ids = got_object_commit_get_parent_ids(commit);
11283 pid = STAILQ_FIRST(parent_ids);
11284 if (pid == NULL) {
11285 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11286 goto done;
11288 error = collect_commits(&commits, head_commit_id, &pid->id,
11289 got_worktree_get_base_commit_id(worktree),
11290 got_worktree_get_path_prefix(worktree),
11291 GOT_ERR_HISTEDIT_PATH, repo);
11292 got_object_commit_close(commit);
11293 commit = NULL;
11294 if (error)
11295 goto done;
11297 if (STAILQ_EMPTY(&commits)) {
11298 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11299 goto done;
11302 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11303 &base_commit_id, &fileindex, worktree, repo);
11304 if (error)
11305 goto done;
11307 if (edit_script_path) {
11308 error = histedit_load_list(&histedit_cmds,
11309 edit_script_path, repo);
11310 if (error) {
11311 got_worktree_histedit_abort(worktree, fileindex,
11312 repo, branch, base_commit_id,
11313 abort_progress, &upa);
11314 print_merge_progress_stats(&upa);
11315 goto done;
11317 } else {
11318 const char *branch_name;
11319 branch_name = got_ref_get_symref_target(branch);
11320 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11321 branch_name += 11;
11322 error = histedit_edit_script(&histedit_cmds, &commits,
11323 branch_name, edit_logmsg_only, fold_only,
11324 edit_only, repo);
11325 if (error) {
11326 got_worktree_histedit_abort(worktree, fileindex,
11327 repo, branch, base_commit_id,
11328 abort_progress, &upa);
11329 print_merge_progress_stats(&upa);
11330 goto done;
11335 error = histedit_save_list(&histedit_cmds, worktree,
11336 repo);
11337 if (error) {
11338 got_worktree_histedit_abort(worktree, fileindex,
11339 repo, branch, base_commit_id,
11340 abort_progress, &upa);
11341 print_merge_progress_stats(&upa);
11342 goto done;
11347 error = histedit_check_script(&histedit_cmds, &commits, repo);
11348 if (error)
11349 goto done;
11351 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11352 if (resume_commit_id) {
11353 if (got_object_id_cmp(hle->commit_id,
11354 resume_commit_id) != 0)
11355 continue;
11357 resume_commit_id = NULL;
11358 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11359 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11360 error = histedit_skip_commit(hle, worktree,
11361 repo);
11362 if (error)
11363 goto done;
11364 } else {
11365 struct got_pathlist_head paths;
11366 int have_changes = 0;
11368 TAILQ_INIT(&paths);
11369 error = got_pathlist_append(&paths, "", NULL);
11370 if (error)
11371 goto done;
11372 error = got_worktree_status(worktree, &paths,
11373 repo, 0, check_local_changes, &have_changes,
11374 check_cancelled, NULL);
11375 got_pathlist_free(&paths);
11376 if (error) {
11377 if (error->code != GOT_ERR_CANCELLED)
11378 goto done;
11379 if (sigint_received || sigpipe_received)
11380 goto done;
11382 if (have_changes) {
11383 error = histedit_commit(NULL, worktree,
11384 fileindex, tmp_branch, hle, repo);
11385 if (error)
11386 goto done;
11387 } else {
11388 error = got_object_open_as_commit(
11389 &commit, repo, hle->commit_id);
11390 if (error)
11391 goto done;
11392 error = show_histedit_progress(commit,
11393 hle, NULL);
11394 got_object_commit_close(commit);
11395 commit = NULL;
11396 if (error)
11397 goto done;
11400 continue;
11403 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11404 error = histedit_skip_commit(hle, worktree, repo);
11405 if (error)
11406 goto done;
11407 continue;
11410 error = got_object_open_as_commit(&commit, repo,
11411 hle->commit_id);
11412 if (error)
11413 goto done;
11414 parent_ids = got_object_commit_get_parent_ids(commit);
11415 pid = STAILQ_FIRST(parent_ids);
11417 error = got_worktree_histedit_merge_files(&merged_paths,
11418 worktree, fileindex, &pid->id, hle->commit_id, repo,
11419 update_progress, &upa, check_cancelled, NULL);
11420 if (error)
11421 goto done;
11422 got_object_commit_close(commit);
11423 commit = NULL;
11425 print_merge_progress_stats(&upa);
11426 if (upa.conflicts > 0 || upa.missing > 0 ||
11427 upa.not_deleted > 0 || upa.unversioned > 0) {
11428 if (upa.conflicts > 0) {
11429 error = show_rebase_merge_conflict(
11430 hle->commit_id, repo);
11431 if (error)
11432 goto done;
11434 got_worktree_rebase_pathlist_free(&merged_paths);
11435 break;
11438 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11439 char *id_str;
11440 error = got_object_id_str(&id_str, hle->commit_id);
11441 if (error)
11442 goto done;
11443 printf("Stopping histedit for amending commit %s\n",
11444 id_str);
11445 free(id_str);
11446 got_worktree_rebase_pathlist_free(&merged_paths);
11447 error = got_worktree_histedit_postpone(worktree,
11448 fileindex);
11449 goto done;
11452 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11453 error = histedit_skip_commit(hle, worktree, repo);
11454 if (error)
11455 goto done;
11456 continue;
11459 error = histedit_commit(&merged_paths, worktree, fileindex,
11460 tmp_branch, hle, repo);
11461 got_worktree_rebase_pathlist_free(&merged_paths);
11462 if (error)
11463 goto done;
11466 if (upa.conflicts > 0 || upa.missing > 0 ||
11467 upa.not_deleted > 0 || upa.unversioned > 0) {
11468 error = got_worktree_histedit_postpone(worktree, fileindex);
11469 if (error)
11470 goto done;
11471 if (upa.conflicts > 0 && upa.missing == 0 &&
11472 upa.not_deleted == 0 && upa.unversioned == 0) {
11473 error = got_error_msg(GOT_ERR_CONFLICTS,
11474 "conflicts must be resolved before histedit "
11475 "can continue");
11476 } else if (upa.conflicts > 0) {
11477 error = got_error_msg(GOT_ERR_CONFLICTS,
11478 "conflicts must be resolved before histedit "
11479 "can continue; changes destined for some "
11480 "files were not yet merged and should be "
11481 "merged manually if required before the "
11482 "histedit operation is continued");
11483 } else {
11484 error = got_error_msg(GOT_ERR_CONFLICTS,
11485 "changes destined for some files were not "
11486 "yet merged and should be merged manually "
11487 "if required before the histedit operation "
11488 "is continued");
11490 } else
11491 error = histedit_complete(worktree, fileindex, tmp_branch,
11492 branch, repo);
11493 done:
11494 got_object_id_queue_free(&commits);
11495 histedit_free_list(&histedit_cmds);
11496 free(head_commit_id);
11497 free(base_commit_id);
11498 free(resume_commit_id);
11499 if (commit)
11500 got_object_commit_close(commit);
11501 if (branch)
11502 got_ref_close(branch);
11503 if (tmp_branch)
11504 got_ref_close(tmp_branch);
11505 if (worktree)
11506 got_worktree_close(worktree);
11507 if (repo) {
11508 const struct got_error *close_err = got_repo_close(repo);
11509 if (error == NULL)
11510 error = close_err;
11512 if (pack_fds) {
11513 const struct got_error *pack_err =
11514 got_repo_pack_fds_close(pack_fds);
11515 if (error == NULL)
11516 error = pack_err;
11517 pack_fds = NULL;
11519 return error;
11522 __dead static void
11523 usage_integrate(void)
11525 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11526 exit(1);
11529 static const struct got_error *
11530 cmd_integrate(int argc, char *argv[])
11532 const struct got_error *error = NULL;
11533 struct got_repository *repo = NULL;
11534 struct got_worktree *worktree = NULL;
11535 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11536 const char *branch_arg = NULL;
11537 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11538 struct got_fileindex *fileindex = NULL;
11539 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11540 int ch;
11541 struct got_update_progress_arg upa;
11542 int *pack_fds = NULL;
11544 while ((ch = getopt(argc, argv, "")) != -1) {
11545 switch (ch) {
11546 default:
11547 usage_integrate();
11548 /* NOTREACHED */
11552 argc -= optind;
11553 argv += optind;
11555 if (argc != 1)
11556 usage_integrate();
11557 branch_arg = argv[0];
11558 #ifndef PROFILE
11559 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11560 "unveil", NULL) == -1)
11561 err(1, "pledge");
11562 #endif
11563 cwd = getcwd(NULL, 0);
11564 if (cwd == NULL) {
11565 error = got_error_from_errno("getcwd");
11566 goto done;
11569 error = got_repo_pack_fds_open(&pack_fds);
11570 if (error != NULL)
11571 goto done;
11573 error = got_worktree_open(&worktree, cwd);
11574 if (error) {
11575 if (error->code == GOT_ERR_NOT_WORKTREE)
11576 error = wrap_not_worktree_error(error, "integrate",
11577 cwd);
11578 goto done;
11581 error = check_rebase_or_histedit_in_progress(worktree);
11582 if (error)
11583 goto done;
11585 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11586 NULL, pack_fds);
11587 if (error != NULL)
11588 goto done;
11590 error = apply_unveil(got_repo_get_path(repo), 0,
11591 got_worktree_get_root_path(worktree));
11592 if (error)
11593 goto done;
11595 error = check_merge_in_progress(worktree, repo);
11596 if (error)
11597 goto done;
11599 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11600 error = got_error_from_errno("asprintf");
11601 goto done;
11604 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11605 &base_branch_ref, worktree, refname, repo);
11606 if (error)
11607 goto done;
11609 refname = strdup(got_ref_get_name(branch_ref));
11610 if (refname == NULL) {
11611 error = got_error_from_errno("strdup");
11612 got_worktree_integrate_abort(worktree, fileindex, repo,
11613 branch_ref, base_branch_ref);
11614 goto done;
11616 base_refname = strdup(got_ref_get_name(base_branch_ref));
11617 if (base_refname == NULL) {
11618 error = got_error_from_errno("strdup");
11619 got_worktree_integrate_abort(worktree, fileindex, repo,
11620 branch_ref, base_branch_ref);
11621 goto done;
11624 error = got_ref_resolve(&commit_id, repo, branch_ref);
11625 if (error)
11626 goto done;
11628 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11629 if (error)
11630 goto done;
11632 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11633 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11634 "specified branch has already been integrated");
11635 got_worktree_integrate_abort(worktree, fileindex, repo,
11636 branch_ref, base_branch_ref);
11637 goto done;
11640 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11641 if (error) {
11642 if (error->code == GOT_ERR_ANCESTRY)
11643 error = got_error(GOT_ERR_REBASE_REQUIRED);
11644 got_worktree_integrate_abort(worktree, fileindex, repo,
11645 branch_ref, base_branch_ref);
11646 goto done;
11649 memset(&upa, 0, sizeof(upa));
11650 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11651 branch_ref, base_branch_ref, update_progress, &upa,
11652 check_cancelled, NULL);
11653 if (error)
11654 goto done;
11656 printf("Integrated %s into %s\n", refname, base_refname);
11657 print_update_progress_stats(&upa);
11658 done:
11659 if (repo) {
11660 const struct got_error *close_err = got_repo_close(repo);
11661 if (error == NULL)
11662 error = close_err;
11664 if (worktree)
11665 got_worktree_close(worktree);
11666 if (pack_fds) {
11667 const struct got_error *pack_err =
11668 got_repo_pack_fds_close(pack_fds);
11669 if (error == NULL)
11670 error = pack_err;
11671 pack_fds = NULL;
11673 free(cwd);
11674 free(base_commit_id);
11675 free(commit_id);
11676 free(refname);
11677 free(base_refname);
11678 return error;
11681 __dead static void
11682 usage_merge(void)
11684 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11685 getprogname());
11686 exit(1);
11689 static const struct got_error *
11690 cmd_merge(int argc, char *argv[])
11692 const struct got_error *error = NULL;
11693 struct got_worktree *worktree = NULL;
11694 struct got_repository *repo = NULL;
11695 struct got_fileindex *fileindex = NULL;
11696 char *cwd = NULL, *id_str = NULL, *author = NULL;
11697 struct got_reference *branch = NULL, *wt_branch = NULL;
11698 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11699 struct got_object_id *wt_branch_tip = NULL;
11700 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11701 int interrupt_merge = 0;
11702 struct got_update_progress_arg upa;
11703 struct got_object_id *merge_commit_id = NULL;
11704 char *branch_name = NULL;
11705 int *pack_fds = NULL;
11707 memset(&upa, 0, sizeof(upa));
11709 while ((ch = getopt(argc, argv, "acn")) != -1) {
11710 switch (ch) {
11711 case 'a':
11712 abort_merge = 1;
11713 break;
11714 case 'c':
11715 continue_merge = 1;
11716 break;
11717 case 'n':
11718 interrupt_merge = 1;
11719 break;
11720 default:
11721 usage_rebase();
11722 /* NOTREACHED */
11726 argc -= optind;
11727 argv += optind;
11729 #ifndef PROFILE
11730 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11731 "unveil", NULL) == -1)
11732 err(1, "pledge");
11733 #endif
11735 if (abort_merge && continue_merge)
11736 option_conflict('a', 'c');
11737 if (abort_merge || continue_merge) {
11738 if (argc != 0)
11739 usage_merge();
11740 } else if (argc != 1)
11741 usage_merge();
11743 cwd = getcwd(NULL, 0);
11744 if (cwd == NULL) {
11745 error = got_error_from_errno("getcwd");
11746 goto done;
11749 error = got_repo_pack_fds_open(&pack_fds);
11750 if (error != NULL)
11751 goto done;
11753 error = got_worktree_open(&worktree, cwd);
11754 if (error) {
11755 if (error->code == GOT_ERR_NOT_WORKTREE)
11756 error = wrap_not_worktree_error(error,
11757 "merge", cwd);
11758 goto done;
11761 error = got_repo_open(&repo,
11762 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11763 pack_fds);
11764 if (error != NULL)
11765 goto done;
11767 error = apply_unveil(got_repo_get_path(repo), 0,
11768 worktree ? got_worktree_get_root_path(worktree) : NULL);
11769 if (error)
11770 goto done;
11772 error = check_rebase_or_histedit_in_progress(worktree);
11773 if (error)
11774 goto done;
11776 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11777 repo);
11778 if (error)
11779 goto done;
11781 if (abort_merge) {
11782 if (!merge_in_progress) {
11783 error = got_error(GOT_ERR_NOT_MERGING);
11784 goto done;
11786 error = got_worktree_merge_continue(&branch_name,
11787 &branch_tip, &fileindex, worktree, repo);
11788 if (error)
11789 goto done;
11790 error = got_worktree_merge_abort(worktree, fileindex, repo,
11791 abort_progress, &upa);
11792 if (error)
11793 goto done;
11794 printf("Merge of %s aborted\n", branch_name);
11795 goto done; /* nothing else to do */
11798 error = get_author(&author, repo, worktree);
11799 if (error)
11800 goto done;
11802 if (continue_merge) {
11803 if (!merge_in_progress) {
11804 error = got_error(GOT_ERR_NOT_MERGING);
11805 goto done;
11807 error = got_worktree_merge_continue(&branch_name,
11808 &branch_tip, &fileindex, worktree, repo);
11809 if (error)
11810 goto done;
11811 } else {
11812 error = got_ref_open(&branch, repo, argv[0], 0);
11813 if (error != NULL)
11814 goto done;
11815 branch_name = strdup(got_ref_get_name(branch));
11816 if (branch_name == NULL) {
11817 error = got_error_from_errno("strdup");
11818 goto done;
11820 error = got_ref_resolve(&branch_tip, repo, branch);
11821 if (error)
11822 goto done;
11825 error = got_ref_open(&wt_branch, repo,
11826 got_worktree_get_head_ref_name(worktree), 0);
11827 if (error)
11828 goto done;
11829 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11830 if (error)
11831 goto done;
11832 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11833 wt_branch_tip, branch_tip, 0, repo,
11834 check_cancelled, NULL);
11835 if (error && error->code != GOT_ERR_ANCESTRY)
11836 goto done;
11838 if (!continue_merge) {
11839 error = check_path_prefix(wt_branch_tip, branch_tip,
11840 got_worktree_get_path_prefix(worktree),
11841 GOT_ERR_MERGE_PATH, repo);
11842 if (error)
11843 goto done;
11844 if (yca_id) {
11845 error = check_same_branch(wt_branch_tip, branch,
11846 yca_id, repo);
11847 if (error) {
11848 if (error->code != GOT_ERR_ANCESTRY)
11849 goto done;
11850 error = NULL;
11851 } else {
11852 static char msg[512];
11853 snprintf(msg, sizeof(msg),
11854 "cannot create a merge commit because "
11855 "%s is based on %s; %s can be integrated "
11856 "with 'got integrate' instead", branch_name,
11857 got_worktree_get_head_ref_name(worktree),
11858 branch_name);
11859 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11860 goto done;
11863 error = got_worktree_merge_prepare(&fileindex, worktree,
11864 branch, repo);
11865 if (error)
11866 goto done;
11868 error = got_worktree_merge_branch(worktree, fileindex,
11869 yca_id, branch_tip, repo, update_progress, &upa,
11870 check_cancelled, NULL);
11871 if (error)
11872 goto done;
11873 print_merge_progress_stats(&upa);
11874 if (!upa.did_something) {
11875 error = got_worktree_merge_abort(worktree, fileindex,
11876 repo, abort_progress, &upa);
11877 if (error)
11878 goto done;
11879 printf("Already up-to-date\n");
11880 goto done;
11884 if (interrupt_merge) {
11885 error = got_worktree_merge_postpone(worktree, fileindex);
11886 if (error)
11887 goto done;
11888 printf("Merge of %s interrupted on request\n", branch_name);
11889 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11890 upa.not_deleted > 0 || upa.unversioned > 0) {
11891 error = got_worktree_merge_postpone(worktree, fileindex);
11892 if (error)
11893 goto done;
11894 if (upa.conflicts > 0 && upa.missing == 0 &&
11895 upa.not_deleted == 0 && upa.unversioned == 0) {
11896 error = got_error_msg(GOT_ERR_CONFLICTS,
11897 "conflicts must be resolved before merging "
11898 "can continue");
11899 } else if (upa.conflicts > 0) {
11900 error = got_error_msg(GOT_ERR_CONFLICTS,
11901 "conflicts must be resolved before merging "
11902 "can continue; changes destined for some "
11903 "files were not yet merged and "
11904 "should be merged manually if required before the "
11905 "merge operation is continued");
11906 } else {
11907 error = got_error_msg(GOT_ERR_CONFLICTS,
11908 "changes destined for some "
11909 "files were not yet merged and should be "
11910 "merged manually if required before the "
11911 "merge operation is continued");
11913 goto done;
11914 } else {
11915 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11916 fileindex, author, NULL, 1, branch_tip, branch_name,
11917 repo, continue_merge ? print_status : NULL, NULL);
11918 if (error)
11919 goto done;
11920 error = got_worktree_merge_complete(worktree, fileindex, repo);
11921 if (error)
11922 goto done;
11923 error = got_object_id_str(&id_str, merge_commit_id);
11924 if (error)
11925 goto done;
11926 printf("Merged %s into %s: %s\n", branch_name,
11927 got_worktree_get_head_ref_name(worktree),
11928 id_str);
11931 done:
11932 free(id_str);
11933 free(merge_commit_id);
11934 free(author);
11935 free(branch_tip);
11936 free(branch_name);
11937 free(yca_id);
11938 if (branch)
11939 got_ref_close(branch);
11940 if (wt_branch)
11941 got_ref_close(wt_branch);
11942 if (worktree)
11943 got_worktree_close(worktree);
11944 if (repo) {
11945 const struct got_error *close_err = got_repo_close(repo);
11946 if (error == NULL)
11947 error = close_err;
11949 if (pack_fds) {
11950 const struct got_error *pack_err =
11951 got_repo_pack_fds_close(pack_fds);
11952 if (error == NULL)
11953 error = pack_err;
11954 pack_fds = NULL;
11956 return error;
11959 __dead static void
11960 usage_stage(void)
11962 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11963 "[-S] [file-path ...]\n",
11964 getprogname());
11965 exit(1);
11968 static const struct got_error *
11969 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11970 const char *path, struct got_object_id *blob_id,
11971 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11972 int dirfd, const char *de_name)
11974 const struct got_error *err = NULL;
11975 char *id_str = NULL;
11977 if (staged_status != GOT_STATUS_ADD &&
11978 staged_status != GOT_STATUS_MODIFY &&
11979 staged_status != GOT_STATUS_DELETE)
11980 return NULL;
11982 if (staged_status == GOT_STATUS_ADD ||
11983 staged_status == GOT_STATUS_MODIFY)
11984 err = got_object_id_str(&id_str, staged_blob_id);
11985 else
11986 err = got_object_id_str(&id_str, blob_id);
11987 if (err)
11988 return err;
11990 printf("%s %c %s\n", id_str, staged_status, path);
11991 free(id_str);
11992 return NULL;
11995 static const struct got_error *
11996 cmd_stage(int argc, char *argv[])
11998 const struct got_error *error = NULL;
11999 struct got_repository *repo = NULL;
12000 struct got_worktree *worktree = NULL;
12001 char *cwd = NULL;
12002 struct got_pathlist_head paths;
12003 struct got_pathlist_entry *pe;
12004 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12005 FILE *patch_script_file = NULL;
12006 const char *patch_script_path = NULL;
12007 struct choose_patch_arg cpa;
12008 int *pack_fds = NULL;
12010 TAILQ_INIT(&paths);
12012 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12013 switch (ch) {
12014 case 'l':
12015 list_stage = 1;
12016 break;
12017 case 'p':
12018 pflag = 1;
12019 break;
12020 case 'F':
12021 patch_script_path = optarg;
12022 break;
12023 case 'S':
12024 allow_bad_symlinks = 1;
12025 break;
12026 default:
12027 usage_stage();
12028 /* NOTREACHED */
12032 argc -= optind;
12033 argv += optind;
12035 #ifndef PROFILE
12036 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12037 "unveil", NULL) == -1)
12038 err(1, "pledge");
12039 #endif
12040 if (list_stage && (pflag || patch_script_path))
12041 errx(1, "-l option cannot be used with other options");
12042 if (patch_script_path && !pflag)
12043 errx(1, "-F option can only be used together with -p option");
12045 cwd = getcwd(NULL, 0);
12046 if (cwd == NULL) {
12047 error = got_error_from_errno("getcwd");
12048 goto done;
12051 error = got_repo_pack_fds_open(&pack_fds);
12052 if (error != NULL)
12053 goto done;
12055 error = got_worktree_open(&worktree, cwd);
12056 if (error) {
12057 if (error->code == GOT_ERR_NOT_WORKTREE)
12058 error = wrap_not_worktree_error(error, "stage", cwd);
12059 goto done;
12062 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12063 NULL, pack_fds);
12064 if (error != NULL)
12065 goto done;
12067 if (patch_script_path) {
12068 patch_script_file = fopen(patch_script_path, "re");
12069 if (patch_script_file == NULL) {
12070 error = got_error_from_errno2("fopen",
12071 patch_script_path);
12072 goto done;
12075 error = apply_unveil(got_repo_get_path(repo), 0,
12076 got_worktree_get_root_path(worktree));
12077 if (error)
12078 goto done;
12080 error = check_merge_in_progress(worktree, repo);
12081 if (error)
12082 goto done;
12084 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12085 if (error)
12086 goto done;
12088 if (list_stage)
12089 error = got_worktree_status(worktree, &paths, repo, 0,
12090 print_stage, NULL, check_cancelled, NULL);
12091 else {
12092 cpa.patch_script_file = patch_script_file;
12093 cpa.action = "stage";
12094 error = got_worktree_stage(worktree, &paths,
12095 pflag ? NULL : print_status, NULL,
12096 pflag ? choose_patch : NULL, &cpa,
12097 allow_bad_symlinks, repo);
12099 done:
12100 if (patch_script_file && fclose(patch_script_file) == EOF &&
12101 error == NULL)
12102 error = got_error_from_errno2("fclose", patch_script_path);
12103 if (repo) {
12104 const struct got_error *close_err = got_repo_close(repo);
12105 if (error == NULL)
12106 error = close_err;
12108 if (worktree)
12109 got_worktree_close(worktree);
12110 if (pack_fds) {
12111 const struct got_error *pack_err =
12112 got_repo_pack_fds_close(pack_fds);
12113 if (error == NULL)
12114 error = pack_err;
12115 pack_fds = NULL;
12117 TAILQ_FOREACH(pe, &paths, entry)
12118 free((char *)pe->path);
12119 got_pathlist_free(&paths);
12120 free(cwd);
12121 return error;
12124 __dead static void
12125 usage_unstage(void)
12127 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12128 "[file-path ...]\n",
12129 getprogname());
12130 exit(1);
12134 static const struct got_error *
12135 cmd_unstage(int argc, char *argv[])
12137 const struct got_error *error = NULL;
12138 struct got_repository *repo = NULL;
12139 struct got_worktree *worktree = NULL;
12140 char *cwd = NULL;
12141 struct got_pathlist_head paths;
12142 struct got_pathlist_entry *pe;
12143 int ch, pflag = 0;
12144 struct got_update_progress_arg upa;
12145 FILE *patch_script_file = NULL;
12146 const char *patch_script_path = NULL;
12147 struct choose_patch_arg cpa;
12148 int *pack_fds = NULL;
12150 TAILQ_INIT(&paths);
12152 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12153 switch (ch) {
12154 case 'p':
12155 pflag = 1;
12156 break;
12157 case 'F':
12158 patch_script_path = optarg;
12159 break;
12160 default:
12161 usage_unstage();
12162 /* NOTREACHED */
12166 argc -= optind;
12167 argv += optind;
12169 #ifndef PROFILE
12170 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12171 "unveil", NULL) == -1)
12172 err(1, "pledge");
12173 #endif
12174 if (patch_script_path && !pflag)
12175 errx(1, "-F option can only be used together with -p option");
12177 cwd = getcwd(NULL, 0);
12178 if (cwd == NULL) {
12179 error = got_error_from_errno("getcwd");
12180 goto done;
12183 error = got_repo_pack_fds_open(&pack_fds);
12184 if (error != NULL)
12185 goto done;
12187 error = got_worktree_open(&worktree, cwd);
12188 if (error) {
12189 if (error->code == GOT_ERR_NOT_WORKTREE)
12190 error = wrap_not_worktree_error(error, "unstage", cwd);
12191 goto done;
12194 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12195 NULL, pack_fds);
12196 if (error != NULL)
12197 goto done;
12199 if (patch_script_path) {
12200 patch_script_file = fopen(patch_script_path, "re");
12201 if (patch_script_file == NULL) {
12202 error = got_error_from_errno2("fopen",
12203 patch_script_path);
12204 goto done;
12208 error = apply_unveil(got_repo_get_path(repo), 0,
12209 got_worktree_get_root_path(worktree));
12210 if (error)
12211 goto done;
12213 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12214 if (error)
12215 goto done;
12217 cpa.patch_script_file = patch_script_file;
12218 cpa.action = "unstage";
12219 memset(&upa, 0, sizeof(upa));
12220 error = got_worktree_unstage(worktree, &paths, update_progress,
12221 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12222 if (!error)
12223 print_merge_progress_stats(&upa);
12224 done:
12225 if (patch_script_file && fclose(patch_script_file) == EOF &&
12226 error == NULL)
12227 error = got_error_from_errno2("fclose", patch_script_path);
12228 if (repo) {
12229 const struct got_error *close_err = got_repo_close(repo);
12230 if (error == NULL)
12231 error = close_err;
12233 if (worktree)
12234 got_worktree_close(worktree);
12235 if (pack_fds) {
12236 const struct got_error *pack_err =
12237 got_repo_pack_fds_close(pack_fds);
12238 if (error == NULL)
12239 error = pack_err;
12240 pack_fds = NULL;
12242 TAILQ_FOREACH(pe, &paths, entry)
12243 free((char *)pe->path);
12244 got_pathlist_free(&paths);
12245 free(cwd);
12246 return error;
12249 __dead static void
12250 usage_cat(void)
12252 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12253 "arg1 [arg2 ...]\n", getprogname());
12254 exit(1);
12257 static const struct got_error *
12258 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12260 const struct got_error *err;
12261 struct got_blob_object *blob;
12263 err = got_object_open_as_blob(&blob, repo, id, 8192);
12264 if (err)
12265 return err;
12267 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12268 got_object_blob_close(blob);
12269 return err;
12272 static const struct got_error *
12273 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12275 const struct got_error *err;
12276 struct got_tree_object *tree;
12277 int nentries, i;
12279 err = got_object_open_as_tree(&tree, repo, id);
12280 if (err)
12281 return err;
12283 nentries = got_object_tree_get_nentries(tree);
12284 for (i = 0; i < nentries; i++) {
12285 struct got_tree_entry *te;
12286 char *id_str;
12287 if (sigint_received || sigpipe_received)
12288 break;
12289 te = got_object_tree_get_entry(tree, i);
12290 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12291 if (err)
12292 break;
12293 fprintf(outfile, "%s %.7o %s\n", id_str,
12294 got_tree_entry_get_mode(te),
12295 got_tree_entry_get_name(te));
12296 free(id_str);
12299 got_object_tree_close(tree);
12300 return err;
12303 static void
12304 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12306 long long h, m;
12307 char sign = '+';
12309 if (gmtoff < 0) {
12310 sign = '-';
12311 gmtoff = -gmtoff;
12314 h = (long long)gmtoff / 3600;
12315 m = ((long long)gmtoff - h*3600) / 60;
12316 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12319 static const struct got_error *
12320 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12322 const struct got_error *err;
12323 struct got_commit_object *commit;
12324 const struct got_object_id_queue *parent_ids;
12325 struct got_object_qid *pid;
12326 char *id_str = NULL;
12327 const char *logmsg = NULL;
12328 char gmtoff[6];
12330 err = got_object_open_as_commit(&commit, repo, id);
12331 if (err)
12332 return err;
12334 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12335 if (err)
12336 goto done;
12338 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12339 parent_ids = got_object_commit_get_parent_ids(commit);
12340 fprintf(outfile, "numparents %d\n",
12341 got_object_commit_get_nparents(commit));
12342 STAILQ_FOREACH(pid, parent_ids, entry) {
12343 char *pid_str;
12344 err = got_object_id_str(&pid_str, &pid->id);
12345 if (err)
12346 goto done;
12347 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12348 free(pid_str);
12350 format_gmtoff(gmtoff, sizeof(gmtoff),
12351 got_object_commit_get_author_gmtoff(commit));
12352 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12353 got_object_commit_get_author(commit),
12354 (long long)got_object_commit_get_author_time(commit),
12355 gmtoff);
12357 format_gmtoff(gmtoff, sizeof(gmtoff),
12358 got_object_commit_get_committer_gmtoff(commit));
12359 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12360 got_object_commit_get_author(commit),
12361 (long long)got_object_commit_get_committer_time(commit),
12362 gmtoff);
12364 logmsg = got_object_commit_get_logmsg_raw(commit);
12365 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12366 fprintf(outfile, "%s", logmsg);
12367 done:
12368 free(id_str);
12369 got_object_commit_close(commit);
12370 return err;
12373 static const struct got_error *
12374 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12376 const struct got_error *err;
12377 struct got_tag_object *tag;
12378 char *id_str = NULL;
12379 const char *tagmsg = NULL;
12380 char gmtoff[6];
12382 err = got_object_open_as_tag(&tag, repo, id);
12383 if (err)
12384 return err;
12386 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12387 if (err)
12388 goto done;
12390 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12392 switch (got_object_tag_get_object_type(tag)) {
12393 case GOT_OBJ_TYPE_BLOB:
12394 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12395 GOT_OBJ_LABEL_BLOB);
12396 break;
12397 case GOT_OBJ_TYPE_TREE:
12398 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12399 GOT_OBJ_LABEL_TREE);
12400 break;
12401 case GOT_OBJ_TYPE_COMMIT:
12402 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12403 GOT_OBJ_LABEL_COMMIT);
12404 break;
12405 case GOT_OBJ_TYPE_TAG:
12406 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12407 GOT_OBJ_LABEL_TAG);
12408 break;
12409 default:
12410 break;
12413 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12414 got_object_tag_get_name(tag));
12416 format_gmtoff(gmtoff, sizeof(gmtoff),
12417 got_object_tag_get_tagger_gmtoff(tag));
12418 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12419 got_object_tag_get_tagger(tag),
12420 (long long)got_object_tag_get_tagger_time(tag),
12421 gmtoff);
12423 tagmsg = got_object_tag_get_message(tag);
12424 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12425 fprintf(outfile, "%s", tagmsg);
12426 done:
12427 free(id_str);
12428 got_object_tag_close(tag);
12429 return err;
12432 static const struct got_error *
12433 cmd_cat(int argc, char *argv[])
12435 const struct got_error *error;
12436 struct got_repository *repo = NULL;
12437 struct got_worktree *worktree = NULL;
12438 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12439 const char *commit_id_str = NULL;
12440 struct got_object_id *id = NULL, *commit_id = NULL;
12441 struct got_commit_object *commit = NULL;
12442 int ch, obj_type, i, force_path = 0;
12443 struct got_reflist_head refs;
12444 int *pack_fds = NULL;
12446 TAILQ_INIT(&refs);
12448 #ifndef PROFILE
12449 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12450 NULL) == -1)
12451 err(1, "pledge");
12452 #endif
12454 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12455 switch (ch) {
12456 case 'c':
12457 commit_id_str = optarg;
12458 break;
12459 case 'r':
12460 repo_path = realpath(optarg, NULL);
12461 if (repo_path == NULL)
12462 return got_error_from_errno2("realpath",
12463 optarg);
12464 got_path_strip_trailing_slashes(repo_path);
12465 break;
12466 case 'P':
12467 force_path = 1;
12468 break;
12469 default:
12470 usage_cat();
12471 /* NOTREACHED */
12475 argc -= optind;
12476 argv += optind;
12478 cwd = getcwd(NULL, 0);
12479 if (cwd == NULL) {
12480 error = got_error_from_errno("getcwd");
12481 goto done;
12484 error = got_repo_pack_fds_open(&pack_fds);
12485 if (error != NULL)
12486 goto done;
12488 if (repo_path == NULL) {
12489 error = got_worktree_open(&worktree, cwd);
12490 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12491 goto done;
12492 if (worktree) {
12493 repo_path = strdup(
12494 got_worktree_get_repo_path(worktree));
12495 if (repo_path == NULL) {
12496 error = got_error_from_errno("strdup");
12497 goto done;
12500 /* Release work tree lock. */
12501 got_worktree_close(worktree);
12502 worktree = NULL;
12506 if (repo_path == NULL) {
12507 repo_path = strdup(cwd);
12508 if (repo_path == NULL)
12509 return got_error_from_errno("strdup");
12512 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12513 free(repo_path);
12514 if (error != NULL)
12515 goto done;
12517 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12518 if (error)
12519 goto done;
12521 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12522 if (error)
12523 goto done;
12525 if (commit_id_str == NULL)
12526 commit_id_str = GOT_REF_HEAD;
12527 error = got_repo_match_object_id(&commit_id, NULL,
12528 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12529 if (error)
12530 goto done;
12532 error = got_object_open_as_commit(&commit, repo, commit_id);
12533 if (error)
12534 goto done;
12536 for (i = 0; i < argc; i++) {
12537 if (force_path) {
12538 error = got_object_id_by_path(&id, repo, commit,
12539 argv[i]);
12540 if (error)
12541 break;
12542 } else {
12543 error = got_repo_match_object_id(&id, &label, argv[i],
12544 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12545 repo);
12546 if (error) {
12547 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12548 error->code != GOT_ERR_NOT_REF)
12549 break;
12550 error = got_object_id_by_path(&id, repo,
12551 commit, argv[i]);
12552 if (error)
12553 break;
12557 error = got_object_get_type(&obj_type, repo, id);
12558 if (error)
12559 break;
12561 switch (obj_type) {
12562 case GOT_OBJ_TYPE_BLOB:
12563 error = cat_blob(id, repo, stdout);
12564 break;
12565 case GOT_OBJ_TYPE_TREE:
12566 error = cat_tree(id, repo, stdout);
12567 break;
12568 case GOT_OBJ_TYPE_COMMIT:
12569 error = cat_commit(id, repo, stdout);
12570 break;
12571 case GOT_OBJ_TYPE_TAG:
12572 error = cat_tag(id, repo, stdout);
12573 break;
12574 default:
12575 error = got_error(GOT_ERR_OBJ_TYPE);
12576 break;
12578 if (error)
12579 break;
12580 free(label);
12581 label = NULL;
12582 free(id);
12583 id = NULL;
12585 done:
12586 free(label);
12587 free(id);
12588 free(commit_id);
12589 if (commit)
12590 got_object_commit_close(commit);
12591 if (worktree)
12592 got_worktree_close(worktree);
12593 if (repo) {
12594 const struct got_error *close_err = got_repo_close(repo);
12595 if (error == NULL)
12596 error = close_err;
12598 if (pack_fds) {
12599 const struct got_error *pack_err =
12600 got_repo_pack_fds_close(pack_fds);
12601 if (error == NULL)
12602 error = pack_err;
12603 pack_fds = NULL;
12606 got_ref_list_free(&refs);
12607 return error;
12610 __dead static void
12611 usage_info(void)
12613 fprintf(stderr, "usage: %s info [path ...]\n",
12614 getprogname());
12615 exit(1);
12618 static const struct got_error *
12619 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12620 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12621 struct got_object_id *commit_id)
12623 const struct got_error *err = NULL;
12624 char *id_str = NULL;
12625 char datebuf[128];
12626 struct tm mytm, *tm;
12627 struct got_pathlist_head *paths = arg;
12628 struct got_pathlist_entry *pe;
12631 * Clear error indication from any of the path arguments which
12632 * would cause this file index entry to be displayed.
12634 TAILQ_FOREACH(pe, paths, entry) {
12635 if (got_path_cmp(path, pe->path, strlen(path),
12636 pe->path_len) == 0 ||
12637 got_path_is_child(path, pe->path, pe->path_len))
12638 pe->data = NULL; /* no error */
12641 printf(GOT_COMMIT_SEP_STR);
12642 if (S_ISLNK(mode))
12643 printf("symlink: %s\n", path);
12644 else if (S_ISREG(mode)) {
12645 printf("file: %s\n", path);
12646 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12647 } else if (S_ISDIR(mode))
12648 printf("directory: %s\n", path);
12649 else
12650 printf("something: %s\n", path);
12652 tm = localtime_r(&mtime, &mytm);
12653 if (tm == NULL)
12654 return NULL;
12655 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12656 return got_error(GOT_ERR_NO_SPACE);
12657 printf("timestamp: %s\n", datebuf);
12659 if (blob_id) {
12660 err = got_object_id_str(&id_str, blob_id);
12661 if (err)
12662 return err;
12663 printf("based on blob: %s\n", id_str);
12664 free(id_str);
12667 if (staged_blob_id) {
12668 err = got_object_id_str(&id_str, staged_blob_id);
12669 if (err)
12670 return err;
12671 printf("based on staged blob: %s\n", id_str);
12672 free(id_str);
12675 if (commit_id) {
12676 err = got_object_id_str(&id_str, commit_id);
12677 if (err)
12678 return err;
12679 printf("based on commit: %s\n", id_str);
12680 free(id_str);
12683 return NULL;
12686 static const struct got_error *
12687 cmd_info(int argc, char *argv[])
12689 const struct got_error *error = NULL;
12690 struct got_worktree *worktree = NULL;
12691 char *cwd = NULL, *id_str = NULL;
12692 struct got_pathlist_head paths;
12693 struct got_pathlist_entry *pe;
12694 char *uuidstr = NULL;
12695 int ch, show_files = 0;
12696 int *pack_fds = NULL;
12698 TAILQ_INIT(&paths);
12700 while ((ch = getopt(argc, argv, "")) != -1) {
12701 switch (ch) {
12702 default:
12703 usage_info();
12704 /* NOTREACHED */
12708 argc -= optind;
12709 argv += optind;
12711 #ifndef PROFILE
12712 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12713 NULL) == -1)
12714 err(1, "pledge");
12715 #endif
12716 cwd = getcwd(NULL, 0);
12717 if (cwd == NULL) {
12718 error = got_error_from_errno("getcwd");
12719 goto done;
12722 error = got_repo_pack_fds_open(&pack_fds);
12723 if (error != NULL)
12724 goto done;
12726 error = got_worktree_open(&worktree, cwd);
12727 if (error) {
12728 if (error->code == GOT_ERR_NOT_WORKTREE)
12729 error = wrap_not_worktree_error(error, "info", cwd);
12730 goto done;
12733 #ifndef PROFILE
12734 /* Remove "cpath" promise. */
12735 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12736 NULL) == -1)
12737 err(1, "pledge");
12738 #endif
12739 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12740 if (error)
12741 goto done;
12743 if (argc >= 1) {
12744 error = get_worktree_paths_from_argv(&paths, argc, argv,
12745 worktree);
12746 if (error)
12747 goto done;
12748 show_files = 1;
12751 error = got_object_id_str(&id_str,
12752 got_worktree_get_base_commit_id(worktree));
12753 if (error)
12754 goto done;
12756 error = got_worktree_get_uuid(&uuidstr, worktree);
12757 if (error)
12758 goto done;
12760 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12761 printf("work tree base commit: %s\n", id_str);
12762 printf("work tree path prefix: %s\n",
12763 got_worktree_get_path_prefix(worktree));
12764 printf("work tree branch reference: %s\n",
12765 got_worktree_get_head_ref_name(worktree));
12766 printf("work tree UUID: %s\n", uuidstr);
12767 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12769 if (show_files) {
12770 struct got_pathlist_entry *pe;
12771 TAILQ_FOREACH(pe, &paths, entry) {
12772 if (pe->path_len == 0)
12773 continue;
12775 * Assume this path will fail. This will be corrected
12776 * in print_path_info() in case the path does suceeed.
12778 pe->data = (void *)got_error_path(pe->path,
12779 GOT_ERR_BAD_PATH);
12781 error = got_worktree_path_info(worktree, &paths,
12782 print_path_info, &paths, check_cancelled, NULL);
12783 if (error)
12784 goto done;
12785 TAILQ_FOREACH(pe, &paths, entry) {
12786 if (pe->data != NULL) {
12787 error = pe->data; /* bad path */
12788 break;
12792 done:
12793 if (pack_fds) {
12794 const struct got_error *pack_err =
12795 got_repo_pack_fds_close(pack_fds);
12796 if (error == NULL)
12797 error = pack_err;
12798 pack_fds = NULL;
12800 TAILQ_FOREACH(pe, &paths, entry)
12801 free((char *)pe->path);
12802 got_pathlist_free(&paths);
12803 free(cwd);
12804 free(id_str);
12805 free(uuidstr);
12806 return error;