Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static volatile sig_atomic_t sigint_received;
67 static volatile sig_atomic_t sigpipe_received;
69 static void
70 catch_sigint(int signo)
71 {
72 sigint_received = 1;
73 }
75 static void
76 catch_sigpipe(int signo)
77 {
78 sigpipe_received = 1;
79 }
82 struct got_cmd {
83 const char *cmd_name;
84 const struct got_error *(*cmd_main)(int, char *[]);
85 void (*cmd_usage)(void);
86 const char *cmd_alias;
87 };
89 __dead static void usage(int, int);
90 __dead static void usage_init(void);
91 __dead static void usage_import(void);
92 __dead static void usage_clone(void);
93 __dead static void usage_fetch(void);
94 __dead static void usage_checkout(void);
95 __dead static void usage_update(void);
96 __dead static void usage_log(void);
97 __dead static void usage_diff(void);
98 __dead static void usage_blame(void);
99 __dead static void usage_tree(void);
100 __dead static void usage_status(void);
101 __dead static void usage_ref(void);
102 __dead static void usage_branch(void);
103 __dead static void usage_tag(void);
104 __dead static void usage_add(void);
105 __dead static void usage_remove(void);
106 __dead static void usage_patch(void);
107 __dead static void usage_revert(void);
108 __dead static void usage_commit(void);
109 __dead static void usage_send(void);
110 __dead static void usage_cherrypick(void);
111 __dead static void usage_backout(void);
112 __dead static void usage_rebase(void);
113 __dead static void usage_histedit(void);
114 __dead static void usage_integrate(void);
115 __dead static void usage_merge(void);
116 __dead static void usage_stage(void);
117 __dead static void usage_unstage(void);
118 __dead static void usage_cat(void);
119 __dead static void usage_info(void);
121 static const struct got_error* cmd_init(int, char *[]);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "init", cmd_init, usage_init, "" },
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_init(void)
350 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
351 exit(1);
354 static const struct got_error *
355 cmd_init(int argc, char *argv[])
357 const struct got_error *error = NULL;
358 char *repo_path = NULL;
359 int ch;
361 while ((ch = getopt(argc, argv, "")) != -1) {
362 switch (ch) {
363 default:
364 usage_init();
365 /* NOTREACHED */
369 argc -= optind;
370 argv += optind;
372 #ifndef PROFILE
373 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
374 err(1, "pledge");
375 #endif
376 if (argc != 1)
377 usage_init();
379 repo_path = strdup(argv[0]);
380 if (repo_path == NULL)
381 return got_error_from_errno("strdup");
383 got_path_strip_trailing_slashes(repo_path);
385 error = got_path_mkdir(repo_path);
386 if (error &&
387 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
388 goto done;
390 error = apply_unveil(repo_path, 0, NULL);
391 if (error)
392 goto done;
394 error = got_repo_init(repo_path);
395 done:
396 free(repo_path);
397 return error;
400 __dead static void
401 usage_import(void)
403 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
404 "[-r repository-path] [-I pattern] path\n", getprogname());
405 exit(1);
408 static int
409 spawn_editor(const char *editor, const char *file)
411 pid_t pid;
412 sig_t sighup, sigint, sigquit;
413 int st = -1;
415 sighup = signal(SIGHUP, SIG_IGN);
416 sigint = signal(SIGINT, SIG_IGN);
417 sigquit = signal(SIGQUIT, SIG_IGN);
419 switch (pid = fork()) {
420 case -1:
421 goto doneediting;
422 case 0:
423 execl(editor, editor, file, (char *)NULL);
424 _exit(127);
427 while (waitpid(pid, &st, 0) == -1)
428 if (errno != EINTR)
429 break;
431 doneediting:
432 (void)signal(SIGHUP, sighup);
433 (void)signal(SIGINT, sigint);
434 (void)signal(SIGQUIT, sigquit);
436 if (!WIFEXITED(st)) {
437 errno = EINTR;
438 return -1;
441 return WEXITSTATUS(st);
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 char *line = NULL;
451 size_t linesize = 0;
452 ssize_t linelen;
453 struct stat st, st2;
454 FILE *fp = NULL;
455 size_t len, logmsg_len;
456 char *initial_content_stripped = NULL, *buf = NULL, *s;
458 *logmsg = NULL;
460 if (stat(logmsg_path, &st) == -1)
461 return got_error_from_errno2("stat", logmsg_path);
463 if (spawn_editor(editor, logmsg_path) == -1)
464 return got_error_from_errno("failed spawning editor");
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno("stat");
469 if (require_modification &&
470 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 /*
475 * Set up a stripped version of the initial content without comments
476 * and blank lines. We need this in order to check if the message
477 * has in fact been edited.
478 */
479 initial_content_stripped = malloc(initial_content_len + 1);
480 if (initial_content_stripped == NULL)
481 return got_error_from_errno("malloc");
482 initial_content_stripped[0] = '\0';
484 buf = strdup(initial_content);
485 if (buf == NULL) {
486 err = got_error_from_errno("strdup");
487 goto done;
489 s = buf;
490 len = 0;
491 while ((line = strsep(&s, "\n")) != NULL) {
492 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
493 continue; /* remove comments and leading empty lines */
494 len = strlcat(initial_content_stripped, line,
495 initial_content_len + 1);
496 if (len >= initial_content_len + 1) {
497 err = got_error(GOT_ERR_NO_SPACE);
498 goto done;
501 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
502 initial_content_stripped[len - 1] = '\0';
503 len--;
506 logmsg_len = st2.st_size;
507 *logmsg = malloc(logmsg_len + 1);
508 if (*logmsg == NULL)
509 return got_error_from_errno("malloc");
510 (*logmsg)[0] = '\0';
512 fp = fopen(logmsg_path, "re");
513 if (fp == NULL) {
514 err = got_error_from_errno("fopen");
515 goto done;
518 len = 0;
519 while ((linelen = getline(&line, &linesize, fp)) != -1) {
520 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
521 continue; /* remove comments and leading empty lines */
522 len = strlcat(*logmsg, line, logmsg_len + 1);
523 if (len >= logmsg_len + 1) {
524 err = got_error(GOT_ERR_NO_SPACE);
525 goto done;
528 free(line);
529 if (ferror(fp)) {
530 err = got_ferror(fp, GOT_ERR_IO);
531 goto done;
533 while (len > 0 && (*logmsg)[len - 1] == '\n') {
534 (*logmsg)[len - 1] = '\0';
535 len--;
538 if (len == 0) {
539 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
540 "commit message cannot be empty, aborting");
541 goto done;
543 if (require_modification &&
544 strcmp(*logmsg, initial_content_stripped) == 0)
545 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
546 "no changes made to commit message, aborting");
547 done:
548 free(initial_content_stripped);
549 free(buf);
550 if (fp && fclose(fp) == EOF && err == NULL)
551 err = got_error_from_errno("fclose");
552 if (err) {
553 free(*logmsg);
554 *logmsg = NULL;
556 return err;
559 static const struct got_error *
560 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
561 const char *path_dir, const char *branch_name)
563 char *initial_content = NULL;
564 const struct got_error *err = NULL;
565 int initial_content_len;
566 int fd = -1;
568 initial_content_len = asprintf(&initial_content,
569 "\n# %s to be imported to branch %s\n", path_dir,
570 branch_name);
571 if (initial_content_len == -1)
572 return got_error_from_errno("asprintf");
574 err = got_opentemp_named_fd(logmsg_path, &fd,
575 GOT_TMPDIR_STR "/got-importmsg");
576 if (err)
577 goto done;
579 if (write(fd, initial_content, initial_content_len) == -1) {
580 err = got_error_from_errno2("write", *logmsg_path);
581 goto done;
584 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
585 initial_content_len, 1);
586 done:
587 if (fd != -1 && close(fd) == -1 && err == NULL)
588 err = got_error_from_errno2("close", *logmsg_path);
589 free(initial_content);
590 if (err) {
591 free(*logmsg_path);
592 *logmsg_path = NULL;
594 return err;
597 static const struct got_error *
598 import_progress(void *arg, const char *path)
600 printf("A %s\n", path);
601 return NULL;
604 static int
605 valid_author(const char *author)
607 /*
608 * Really dumb email address check; we're only doing this to
609 * avoid git's object parser breaking on commits we create.
610 */
611 while (*author && *author != '<')
612 author++;
613 if (*author != '<')
614 return 0;
615 while (*author && *author != '@')
616 author++;
617 if (*author != '@')
618 return 0;
619 while (*author && *author != '>')
620 author++;
621 return *author == '>';
624 static const struct got_error *
625 get_author(char **author, struct got_repository *repo,
626 struct got_worktree *worktree)
628 const struct got_error *err = NULL;
629 const char *got_author = NULL, *name, *email;
630 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
632 *author = NULL;
634 if (worktree)
635 worktree_conf = got_worktree_get_gotconfig(worktree);
636 repo_conf = got_repo_get_gotconfig(repo);
638 /*
639 * Priority of potential author information sources, from most
640 * significant to least significant:
641 * 1) work tree's .got/got.conf file
642 * 2) repository's got.conf file
643 * 3) repository's git config file
644 * 4) environment variables
645 * 5) global git config files (in user's home directory or /etc)
646 */
648 if (worktree_conf)
649 got_author = got_gotconfig_get_author(worktree_conf);
650 if (got_author == NULL)
651 got_author = got_gotconfig_get_author(repo_conf);
652 if (got_author == NULL) {
653 name = got_repo_get_gitconfig_author_name(repo);
654 email = got_repo_get_gitconfig_author_email(repo);
655 if (name && email) {
656 if (asprintf(author, "%s <%s>", name, email) == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
661 got_author = getenv("GOT_AUTHOR");
662 if (got_author == NULL) {
663 name = got_repo_get_global_gitconfig_author_name(repo);
664 email = got_repo_get_global_gitconfig_author_email(
665 repo);
666 if (name && email) {
667 if (asprintf(author, "%s <%s>", name, email)
668 == -1)
669 return got_error_from_errno("asprintf");
670 return NULL;
672 /* TODO: Look up user in password database? */
673 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
677 *author = strdup(got_author);
678 if (*author == NULL)
679 return got_error_from_errno("strdup");
681 if (!valid_author(*author)) {
682 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
683 free(*author);
684 *author = NULL;
686 return err;
689 static const struct got_error *
690 get_gitconfig_path(char **gitconfig_path)
692 const char *homedir = getenv("HOME");
694 *gitconfig_path = NULL;
695 if (homedir) {
696 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
697 return got_error_from_errno("asprintf");
700 return NULL;
703 static const struct got_error *
704 cmd_import(int argc, char *argv[])
706 const struct got_error *error = NULL;
707 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
708 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
709 const char *branch_name = "main";
710 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
711 struct got_repository *repo = NULL;
712 struct got_reference *branch_ref = NULL, *head_ref = NULL;
713 struct got_object_id *new_commit_id = NULL;
714 int ch;
715 struct got_pathlist_head ignores;
716 struct got_pathlist_entry *pe;
717 int preserve_logmsg = 0;
718 int *pack_fds = NULL;
720 TAILQ_INIT(&ignores);
722 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
723 switch (ch) {
724 case 'b':
725 branch_name = optarg;
726 break;
727 case 'm':
728 logmsg = strdup(optarg);
729 if (logmsg == NULL) {
730 error = got_error_from_errno("strdup");
731 goto done;
733 break;
734 case 'r':
735 repo_path = realpath(optarg, NULL);
736 if (repo_path == NULL) {
737 error = got_error_from_errno2("realpath",
738 optarg);
739 goto done;
741 break;
742 case 'I':
743 if (optarg[0] == '\0')
744 break;
745 error = got_pathlist_insert(&pe, &ignores, optarg,
746 NULL);
747 if (error)
748 goto done;
749 break;
750 default:
751 usage_import();
752 /* NOTREACHED */
756 argc -= optind;
757 argv += optind;
759 #ifndef PROFILE
760 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
761 "unveil",
762 NULL) == -1)
763 err(1, "pledge");
764 #endif
765 if (argc != 1)
766 usage_import();
768 if (repo_path == NULL) {
769 repo_path = getcwd(NULL, 0);
770 if (repo_path == NULL)
771 return got_error_from_errno("getcwd");
773 got_path_strip_trailing_slashes(repo_path);
774 error = get_gitconfig_path(&gitconfig_path);
775 if (error)
776 goto done;
777 error = got_repo_pack_fds_open(&pack_fds);
778 if (error != NULL)
779 goto done;
780 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
781 if (error)
782 goto done;
784 error = get_author(&author, repo, NULL);
785 if (error)
786 return error;
788 /*
789 * Don't let the user create a branch name with a leading '-'.
790 * While technically a valid reference name, this case is usually
791 * an unintended typo.
792 */
793 if (branch_name[0] == '-')
794 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
796 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
797 error = got_error_from_errno("asprintf");
798 goto done;
801 error = got_ref_open(&branch_ref, repo, refname, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF)
804 goto done;
805 } else {
806 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
807 "import target branch already exists");
808 goto done;
811 path_dir = realpath(argv[0], NULL);
812 if (path_dir == NULL) {
813 error = got_error_from_errno2("realpath", argv[0]);
814 goto done;
816 got_path_strip_trailing_slashes(path_dir);
818 /*
819 * unveil(2) traverses exec(2); if an editor is used we have
820 * to apply unveil after the log message has been written.
821 */
822 if (logmsg == NULL || strlen(logmsg) == 0) {
823 error = get_editor(&editor);
824 if (error)
825 goto done;
826 free(logmsg);
827 error = collect_import_msg(&logmsg, &logmsg_path, editor,
828 path_dir, refname);
829 if (error) {
830 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
831 logmsg_path != NULL)
832 preserve_logmsg = 1;
833 goto done;
837 if (unveil(path_dir, "r") != 0) {
838 error = got_error_from_errno2("unveil", path_dir);
839 if (logmsg_path)
840 preserve_logmsg = 1;
841 goto done;
844 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
845 if (error) {
846 if (logmsg_path)
847 preserve_logmsg = 1;
848 goto done;
851 error = got_repo_import(&new_commit_id, path_dir, logmsg,
852 author, &ignores, repo, import_progress, NULL);
853 if (error) {
854 if (logmsg_path)
855 preserve_logmsg = 1;
856 goto done;
859 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
860 if (error) {
861 if (logmsg_path)
862 preserve_logmsg = 1;
863 goto done;
866 error = got_ref_write(branch_ref, repo);
867 if (error) {
868 if (logmsg_path)
869 preserve_logmsg = 1;
870 goto done;
873 error = got_object_id_str(&id_str, new_commit_id);
874 if (error) {
875 if (logmsg_path)
876 preserve_logmsg = 1;
877 goto done;
880 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
881 if (error) {
882 if (error->code != GOT_ERR_NOT_REF) {
883 if (logmsg_path)
884 preserve_logmsg = 1;
885 goto done;
888 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
889 branch_ref);
890 if (error) {
891 if (logmsg_path)
892 preserve_logmsg = 1;
893 goto done;
896 error = got_ref_write(head_ref, repo);
897 if (error) {
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
904 printf("Created branch %s with commit %s\n",
905 got_ref_get_name(branch_ref), id_str);
906 done:
907 if (pack_fds) {
908 const struct got_error *pack_err =
909 got_repo_pack_fds_close(pack_fds);
910 if (error == NULL)
911 error = pack_err;
913 if (preserve_logmsg) {
914 fprintf(stderr, "%s: log message preserved in %s\n",
915 getprogname(), logmsg_path);
916 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
917 error = got_error_from_errno2("unlink", logmsg_path);
918 free(logmsg);
919 free(logmsg_path);
920 free(repo_path);
921 free(editor);
922 free(refname);
923 free(new_commit_id);
924 free(id_str);
925 free(author);
926 free(gitconfig_path);
927 if (branch_ref)
928 got_ref_close(branch_ref);
929 if (head_ref)
930 got_ref_close(head_ref);
931 return error;
934 __dead static void
935 usage_clone(void)
937 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
938 "[-R reference] repository-url [directory]\n", getprogname());
939 exit(1);
942 struct got_fetch_progress_arg {
943 char last_scaled_size[FMT_SCALED_STRSIZE];
944 int last_p_indexed;
945 int last_p_resolved;
946 int verbosity;
948 struct got_repository *repo;
950 int create_configs;
951 int configs_created;
952 struct {
953 struct got_pathlist_head *symrefs;
954 struct got_pathlist_head *wanted_branches;
955 struct got_pathlist_head *wanted_refs;
956 const char *proto;
957 const char *host;
958 const char *port;
959 const char *remote_repo_path;
960 const char *git_url;
961 int fetch_all_branches;
962 int mirror_references;
963 } config_info;
964 };
966 /* XXX forward declaration */
967 static const struct got_error *
968 create_config_files(const char *proto, const char *host, const char *port,
969 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
970 int mirror_references, struct got_pathlist_head *symrefs,
971 struct got_pathlist_head *wanted_branches,
972 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
974 static const struct got_error *
975 fetch_progress(void *arg, const char *message, off_t packfile_size,
976 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
978 const struct got_error *err = NULL;
979 struct got_fetch_progress_arg *a = arg;
980 char scaled_size[FMT_SCALED_STRSIZE];
981 int p_indexed, p_resolved;
982 int print_size = 0, print_indexed = 0, print_resolved = 0;
984 /*
985 * In order to allow a failed clone to be resumed with 'got fetch'
986 * we try to create configuration files as soon as possible.
987 * Once the server has sent information about its default branch
988 * we have all required information.
989 */
990 if (a->create_configs && !a->configs_created &&
991 !TAILQ_EMPTY(a->config_info.symrefs)) {
992 err = create_config_files(a->config_info.proto,
993 a->config_info.host, a->config_info.port,
994 a->config_info.remote_repo_path,
995 a->config_info.git_url,
996 a->config_info.fetch_all_branches,
997 a->config_info.mirror_references,
998 a->config_info.symrefs,
999 a->config_info.wanted_branches,
1000 a->config_info.wanted_refs, a->repo);
1001 if (err)
1002 return err;
1003 a->configs_created = 1;
1006 if (a->verbosity < 0)
1007 return NULL;
1009 if (message && message[0] != '\0') {
1010 printf("\rserver: %s", message);
1011 fflush(stdout);
1012 return NULL;
1015 if (packfile_size > 0 || nobj_indexed > 0) {
1016 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1017 (a->last_scaled_size[0] == '\0' ||
1018 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1019 print_size = 1;
1020 if (strlcpy(a->last_scaled_size, scaled_size,
1021 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1022 return got_error(GOT_ERR_NO_SPACE);
1024 if (nobj_indexed > 0) {
1025 p_indexed = (nobj_indexed * 100) / nobj_total;
1026 if (p_indexed != a->last_p_indexed) {
1027 a->last_p_indexed = p_indexed;
1028 print_indexed = 1;
1029 print_size = 1;
1032 if (nobj_resolved > 0) {
1033 p_resolved = (nobj_resolved * 100) /
1034 (nobj_total - nobj_loose);
1035 if (p_resolved != a->last_p_resolved) {
1036 a->last_p_resolved = p_resolved;
1037 print_resolved = 1;
1038 print_indexed = 1;
1039 print_size = 1;
1044 if (print_size || print_indexed || print_resolved)
1045 printf("\r");
1046 if (print_size)
1047 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1048 if (print_indexed)
1049 printf("; indexing %d%%", p_indexed);
1050 if (print_resolved)
1051 printf("; resolving deltas %d%%", p_resolved);
1052 if (print_size || print_indexed || print_resolved)
1053 fflush(stdout);
1055 return NULL;
1058 static const struct got_error *
1059 create_symref(const char *refname, struct got_reference *target_ref,
1060 int verbosity, struct got_repository *repo)
1062 const struct got_error *err;
1063 struct got_reference *head_symref;
1065 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1066 if (err)
1067 return err;
1069 err = got_ref_write(head_symref, repo);
1070 if (err == NULL && verbosity > 0) {
1071 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1072 got_ref_get_name(target_ref));
1074 got_ref_close(head_symref);
1075 return err;
1078 static const struct got_error *
1079 list_remote_refs(struct got_pathlist_head *symrefs,
1080 struct got_pathlist_head *refs)
1082 const struct got_error *err;
1083 struct got_pathlist_entry *pe;
1085 TAILQ_FOREACH(pe, symrefs, entry) {
1086 const char *refname = pe->path;
1087 const char *targetref = pe->data;
1089 printf("%s: %s\n", refname, targetref);
1092 TAILQ_FOREACH(pe, refs, entry) {
1093 const char *refname = pe->path;
1094 struct got_object_id *id = pe->data;
1095 char *id_str;
1097 err = got_object_id_str(&id_str, id);
1098 if (err)
1099 return err;
1100 printf("%s: %s\n", refname, id_str);
1101 free(id_str);
1104 return NULL;
1107 static const struct got_error *
1108 create_ref(const char *refname, struct got_object_id *id,
1109 int verbosity, struct got_repository *repo)
1111 const struct got_error *err = NULL;
1112 struct got_reference *ref;
1113 char *id_str;
1115 err = got_object_id_str(&id_str, id);
1116 if (err)
1117 return err;
1119 err = got_ref_alloc(&ref, refname, id);
1120 if (err)
1121 goto done;
1123 err = got_ref_write(ref, repo);
1124 got_ref_close(ref);
1126 if (err == NULL && verbosity >= 0)
1127 printf("Created reference %s: %s\n", refname, id_str);
1128 done:
1129 free(id_str);
1130 return err;
1133 static int
1134 match_wanted_ref(const char *refname, const char *wanted_ref)
1136 if (strncmp(refname, "refs/", 5) != 0)
1137 return 0;
1138 refname += 5;
1141 * Prevent fetching of references that won't make any
1142 * sense outside of the remote repository's context.
1144 if (strncmp(refname, "got/", 4) == 0)
1145 return 0;
1146 if (strncmp(refname, "remotes/", 8) == 0)
1147 return 0;
1149 if (strncmp(wanted_ref, "refs/", 5) == 0)
1150 wanted_ref += 5;
1152 /* Allow prefix match. */
1153 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1154 return 1;
1156 /* Allow exact match. */
1157 return (strcmp(refname, wanted_ref) == 0);
1160 static int
1161 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1163 struct got_pathlist_entry *pe;
1165 TAILQ_FOREACH(pe, wanted_refs, entry) {
1166 if (match_wanted_ref(refname, pe->path))
1167 return 1;
1170 return 0;
1173 static const struct got_error *
1174 create_wanted_ref(const char *refname, struct got_object_id *id,
1175 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1177 const struct got_error *err;
1178 char *remote_refname;
1180 if (strncmp("refs/", refname, 5) == 0)
1181 refname += 5;
1183 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1184 remote_repo_name, refname) == -1)
1185 return got_error_from_errno("asprintf");
1187 err = create_ref(remote_refname, id, verbosity, repo);
1188 free(remote_refname);
1189 return err;
1192 static const struct got_error *
1193 create_gotconfig(const char *proto, const char *host, const char *port,
1194 const char *remote_repo_path, const char *default_branch,
1195 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1196 struct got_pathlist_head *wanted_refs, int mirror_references,
1197 struct got_repository *repo)
1199 const struct got_error *err = NULL;
1200 char *gotconfig_path = NULL;
1201 char *gotconfig = NULL;
1202 FILE *gotconfig_file = NULL;
1203 const char *branchname = NULL;
1204 char *branches = NULL, *refs = NULL;
1205 ssize_t n;
1207 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1208 struct got_pathlist_entry *pe;
1209 TAILQ_FOREACH(pe, wanted_branches, entry) {
1210 char *s;
1211 branchname = pe->path;
1212 if (strncmp(branchname, "refs/heads/", 11) == 0)
1213 branchname += 11;
1214 if (asprintf(&s, "%s\"%s\" ",
1215 branches ? branches : "", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1219 free(branches);
1220 branches = s;
1222 } else if (!fetch_all_branches && default_branch) {
1223 branchname = default_branch;
1224 if (strncmp(branchname, "refs/heads/", 11) == 0)
1225 branchname += 11;
1226 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1227 err = got_error_from_errno("asprintf");
1228 goto done;
1231 if (!TAILQ_EMPTY(wanted_refs)) {
1232 struct got_pathlist_entry *pe;
1233 TAILQ_FOREACH(pe, wanted_refs, entry) {
1234 char *s;
1235 const char *refname = pe->path;
1236 if (strncmp(refname, "refs/", 5) == 0)
1237 branchname += 5;
1238 if (asprintf(&s, "%s\"%s\" ",
1239 refs ? refs : "", refname) == -1) {
1240 err = got_error_from_errno("asprintf");
1241 goto done;
1243 free(refs);
1244 refs = s;
1248 /* Create got.conf(5). */
1249 gotconfig_path = got_repo_get_path_gotconfig(repo);
1250 if (gotconfig_path == NULL) {
1251 err = got_error_from_errno("got_repo_get_path_gotconfig");
1252 goto done;
1254 gotconfig_file = fopen(gotconfig_path, "ae");
1255 if (gotconfig_file == NULL) {
1256 err = got_error_from_errno2("fopen", gotconfig_path);
1257 goto done;
1259 if (asprintf(&gotconfig,
1260 "remote \"%s\" {\n"
1261 "\tserver %s\n"
1262 "\tprotocol %s\n"
1263 "%s%s%s"
1264 "\trepository \"%s\"\n"
1265 "%s%s%s"
1266 "%s%s%s"
1267 "%s"
1268 "%s"
1269 "}\n",
1270 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1271 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1272 remote_repo_path, branches ? "\tbranch { " : "",
1273 branches ? branches : "", branches ? "}\n" : "",
1274 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1275 mirror_references ? "\tmirror-references yes\n" : "",
1276 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1277 err = got_error_from_errno("asprintf");
1278 goto done;
1280 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1281 if (n != strlen(gotconfig)) {
1282 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1283 goto done;
1286 done:
1287 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1288 err = got_error_from_errno2("fclose", gotconfig_path);
1289 free(gotconfig_path);
1290 free(branches);
1291 return err;
1294 static const struct got_error *
1295 create_gitconfig(const char *git_url, const char *default_branch,
1296 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1297 struct got_pathlist_head *wanted_refs, int mirror_references,
1298 struct got_repository *repo)
1300 const struct got_error *err = NULL;
1301 char *gitconfig_path = NULL;
1302 char *gitconfig = NULL;
1303 FILE *gitconfig_file = NULL;
1304 char *branches = NULL, *refs = NULL;
1305 const char *branchname;
1306 ssize_t n;
1308 /* Create a config file Git can understand. */
1309 gitconfig_path = got_repo_get_path_gitconfig(repo);
1310 if (gitconfig_path == NULL) {
1311 err = got_error_from_errno("got_repo_get_path_gitconfig");
1312 goto done;
1314 gitconfig_file = fopen(gitconfig_path, "ae");
1315 if (gitconfig_file == NULL) {
1316 err = got_error_from_errno2("fopen", gitconfig_path);
1317 goto done;
1319 if (fetch_all_branches) {
1320 if (mirror_references) {
1321 if (asprintf(&branches,
1322 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1323 err = got_error_from_errno("asprintf");
1324 goto done;
1326 } else if (asprintf(&branches,
1327 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1328 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 } else if (!TAILQ_EMPTY(wanted_branches)) {
1333 struct got_pathlist_entry *pe;
1334 TAILQ_FOREACH(pe, wanted_branches, entry) {
1335 char *s;
1336 branchname = pe->path;
1337 if (strncmp(branchname, "refs/heads/", 11) == 0)
1338 branchname += 11;
1339 if (mirror_references) {
1340 if (asprintf(&s,
1341 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1342 branches ? branches : "",
1343 branchname, branchname) == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 } else if (asprintf(&s,
1348 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1349 branches ? branches : "",
1350 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1351 branchname) == -1) {
1352 err = got_error_from_errno("asprintf");
1353 goto done;
1355 free(branches);
1356 branches = s;
1358 } else {
1360 * If the server specified a default branch, use just that one.
1361 * Otherwise fall back to fetching all branches on next fetch.
1363 if (default_branch) {
1364 branchname = default_branch;
1365 if (strncmp(branchname, "refs/heads/", 11) == 0)
1366 branchname += 11;
1367 } else
1368 branchname = "*"; /* fall back to all branches */
1369 if (mirror_references) {
1370 if (asprintf(&branches,
1371 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1372 branchname, branchname) == -1) {
1373 err = got_error_from_errno("asprintf");
1374 goto done;
1376 } else if (asprintf(&branches,
1377 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1378 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1379 branchname) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1384 if (!TAILQ_EMPTY(wanted_refs)) {
1385 struct got_pathlist_entry *pe;
1386 TAILQ_FOREACH(pe, wanted_refs, entry) {
1387 char *s;
1388 const char *refname = pe->path;
1389 if (strncmp(refname, "refs/", 5) == 0)
1390 refname += 5;
1391 if (mirror_references) {
1392 if (asprintf(&s,
1393 "%s\tfetch = refs/%s:refs/%s\n",
1394 refs ? refs : "", refname, refname) == -1) {
1395 err = got_error_from_errno("asprintf");
1396 goto done;
1398 } else if (asprintf(&s,
1399 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1400 refs ? refs : "",
1401 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1402 refname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 free(refs);
1407 refs = s;
1411 if (asprintf(&gitconfig,
1412 "[remote \"%s\"]\n"
1413 "\turl = %s\n"
1414 "%s"
1415 "%s"
1416 "\tfetch = refs/tags/*:refs/tags/*\n",
1417 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1418 refs ? refs : "") == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1423 if (n != strlen(gitconfig)) {
1424 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1425 goto done;
1427 done:
1428 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1429 err = got_error_from_errno2("fclose", gitconfig_path);
1430 free(gitconfig_path);
1431 free(branches);
1432 return err;
1435 static const struct got_error *
1436 create_config_files(const char *proto, const char *host, const char *port,
1437 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1438 int mirror_references, struct got_pathlist_head *symrefs,
1439 struct got_pathlist_head *wanted_branches,
1440 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1442 const struct got_error *err = NULL;
1443 const char *default_branch = NULL;
1444 struct got_pathlist_entry *pe;
1447 * If we asked for a set of wanted branches then use the first
1448 * one of those.
1450 if (!TAILQ_EMPTY(wanted_branches)) {
1451 pe = TAILQ_FIRST(wanted_branches);
1452 default_branch = pe->path;
1453 } else {
1454 /* First HEAD ref listed by server is the default branch. */
1455 TAILQ_FOREACH(pe, symrefs, entry) {
1456 const char *refname = pe->path;
1457 const char *target = pe->data;
1459 if (strcmp(refname, GOT_REF_HEAD) != 0)
1460 continue;
1462 default_branch = target;
1463 break;
1467 /* Create got.conf(5). */
1468 err = create_gotconfig(proto, host, port, remote_repo_path,
1469 default_branch, fetch_all_branches, wanted_branches,
1470 wanted_refs, mirror_references, repo);
1471 if (err)
1472 return err;
1474 /* Create a config file Git can understand. */
1475 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1476 wanted_branches, wanted_refs, mirror_references, repo);
1479 static const struct got_error *
1480 cmd_clone(int argc, char *argv[])
1482 const struct got_error *error = NULL;
1483 const char *uri, *dirname;
1484 char *proto, *host, *port, *repo_name, *server_path;
1485 char *default_destdir = NULL, *id_str = NULL;
1486 const char *repo_path;
1487 struct got_repository *repo = NULL;
1488 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1489 struct got_pathlist_entry *pe;
1490 struct got_object_id *pack_hash = NULL;
1491 int ch, fetchfd = -1, fetchstatus;
1492 pid_t fetchpid = -1;
1493 struct got_fetch_progress_arg fpa;
1494 char *git_url = NULL;
1495 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1496 int list_refs_only = 0;
1497 int *pack_fds = NULL;
1499 TAILQ_INIT(&refs);
1500 TAILQ_INIT(&symrefs);
1501 TAILQ_INIT(&wanted_branches);
1502 TAILQ_INIT(&wanted_refs);
1504 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1505 switch (ch) {
1506 case 'a':
1507 fetch_all_branches = 1;
1508 break;
1509 case 'b':
1510 error = got_pathlist_append(&wanted_branches,
1511 optarg, NULL);
1512 if (error)
1513 return error;
1514 break;
1515 case 'l':
1516 list_refs_only = 1;
1517 break;
1518 case 'm':
1519 mirror_references = 1;
1520 break;
1521 case 'v':
1522 if (verbosity < 0)
1523 verbosity = 0;
1524 else if (verbosity < 3)
1525 verbosity++;
1526 break;
1527 case 'q':
1528 verbosity = -1;
1529 break;
1530 case 'R':
1531 error = got_pathlist_append(&wanted_refs,
1532 optarg, NULL);
1533 if (error)
1534 return error;
1535 break;
1536 default:
1537 usage_clone();
1538 break;
1541 argc -= optind;
1542 argv += optind;
1544 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1545 option_conflict('a', 'b');
1546 if (list_refs_only) {
1547 if (!TAILQ_EMPTY(&wanted_branches))
1548 option_conflict('l', 'b');
1549 if (fetch_all_branches)
1550 option_conflict('l', 'a');
1551 if (mirror_references)
1552 option_conflict('l', 'm');
1553 if (!TAILQ_EMPTY(&wanted_refs))
1554 option_conflict('l', 'R');
1557 uri = argv[0];
1559 if (argc == 1)
1560 dirname = NULL;
1561 else if (argc == 2)
1562 dirname = argv[1];
1563 else
1564 usage_clone();
1566 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1567 &repo_name, uri);
1568 if (error)
1569 goto done;
1571 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1572 host, port ? ":" : "", port ? port : "",
1573 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1574 error = got_error_from_errno("asprintf");
1575 goto done;
1578 if (strcmp(proto, "git") == 0) {
1579 #ifndef PROFILE
1580 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1581 "sendfd dns inet unveil", NULL) == -1)
1582 err(1, "pledge");
1583 #endif
1584 } else if (strcmp(proto, "git+ssh") == 0 ||
1585 strcmp(proto, "ssh") == 0) {
1586 #ifndef PROFILE
1587 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1588 "sendfd unveil", NULL) == -1)
1589 err(1, "pledge");
1590 #endif
1591 } else if (strcmp(proto, "http") == 0 ||
1592 strcmp(proto, "git+http") == 0) {
1593 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1594 goto done;
1595 } else {
1596 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1597 goto done;
1599 if (dirname == NULL) {
1600 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1601 error = got_error_from_errno("asprintf");
1602 goto done;
1604 repo_path = default_destdir;
1605 } else
1606 repo_path = dirname;
1608 if (!list_refs_only) {
1609 error = got_path_mkdir(repo_path);
1610 if (error &&
1611 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1612 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1613 goto done;
1614 if (!got_path_dir_is_empty(repo_path)) {
1615 error = got_error_path(repo_path,
1616 GOT_ERR_DIR_NOT_EMPTY);
1617 goto done;
1621 error = got_dial_apply_unveil(proto);
1622 if (error)
1623 goto done;
1625 error = apply_unveil(repo_path, 0, NULL);
1626 if (error)
1627 goto done;
1629 if (verbosity >= 0)
1630 printf("Connecting to %s%s%s\n", host,
1631 port ? ":" : "", port ? port : "");
1633 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1634 server_path, verbosity);
1635 if (error)
1636 goto done;
1638 if (!list_refs_only) {
1639 error = got_repo_init(repo_path);
1640 if (error)
1641 goto done;
1642 error = got_repo_pack_fds_open(&pack_fds);
1643 if (error != NULL)
1644 goto done;
1645 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1646 if (error)
1647 goto done;
1650 fpa.last_scaled_size[0] = '\0';
1651 fpa.last_p_indexed = -1;
1652 fpa.last_p_resolved = -1;
1653 fpa.verbosity = verbosity;
1654 fpa.create_configs = 1;
1655 fpa.configs_created = 0;
1656 fpa.repo = repo;
1657 fpa.config_info.symrefs = &symrefs;
1658 fpa.config_info.wanted_branches = &wanted_branches;
1659 fpa.config_info.wanted_refs = &wanted_refs;
1660 fpa.config_info.proto = proto;
1661 fpa.config_info.host = host;
1662 fpa.config_info.port = port;
1663 fpa.config_info.remote_repo_path = server_path;
1664 fpa.config_info.git_url = git_url;
1665 fpa.config_info.fetch_all_branches = fetch_all_branches;
1666 fpa.config_info.mirror_references = mirror_references;
1667 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1668 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1669 fetch_all_branches, &wanted_branches, &wanted_refs,
1670 list_refs_only, verbosity, fetchfd, repo,
1671 fetch_progress, &fpa);
1672 if (error)
1673 goto done;
1675 if (list_refs_only) {
1676 error = list_remote_refs(&symrefs, &refs);
1677 goto done;
1680 if (pack_hash == NULL) {
1681 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1682 "server sent an empty pack file");
1683 goto done;
1685 error = got_object_id_str(&id_str, pack_hash);
1686 if (error)
1687 goto done;
1688 if (verbosity >= 0)
1689 printf("\nFetched %s.pack\n", id_str);
1690 free(id_str);
1692 /* Set up references provided with the pack file. */
1693 TAILQ_FOREACH(pe, &refs, entry) {
1694 const char *refname = pe->path;
1695 struct got_object_id *id = pe->data;
1696 char *remote_refname;
1698 if (is_wanted_ref(&wanted_refs, refname) &&
1699 !mirror_references) {
1700 error = create_wanted_ref(refname, id,
1701 GOT_FETCH_DEFAULT_REMOTE_NAME,
1702 verbosity - 1, repo);
1703 if (error)
1704 goto done;
1705 continue;
1708 error = create_ref(refname, id, verbosity - 1, repo);
1709 if (error)
1710 goto done;
1712 if (mirror_references)
1713 continue;
1715 if (strncmp("refs/heads/", refname, 11) != 0)
1716 continue;
1718 if (asprintf(&remote_refname,
1719 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1720 refname + 11) == -1) {
1721 error = got_error_from_errno("asprintf");
1722 goto done;
1724 error = create_ref(remote_refname, id, verbosity - 1, repo);
1725 free(remote_refname);
1726 if (error)
1727 goto done;
1730 /* Set the HEAD reference if the server provided one. */
1731 TAILQ_FOREACH(pe, &symrefs, entry) {
1732 struct got_reference *target_ref;
1733 const char *refname = pe->path;
1734 const char *target = pe->data;
1735 char *remote_refname = NULL, *remote_target = NULL;
1737 if (strcmp(refname, GOT_REF_HEAD) != 0)
1738 continue;
1740 error = got_ref_open(&target_ref, repo, target, 0);
1741 if (error) {
1742 if (error->code == GOT_ERR_NOT_REF) {
1743 error = NULL;
1744 continue;
1746 goto done;
1749 error = create_symref(refname, target_ref, verbosity, repo);
1750 got_ref_close(target_ref);
1751 if (error)
1752 goto done;
1754 if (mirror_references)
1755 continue;
1757 if (strncmp("refs/heads/", target, 11) != 0)
1758 continue;
1760 if (asprintf(&remote_refname,
1761 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1762 refname) == -1) {
1763 error = got_error_from_errno("asprintf");
1764 goto done;
1766 if (asprintf(&remote_target,
1767 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 target + 11) == -1) {
1769 error = got_error_from_errno("asprintf");
1770 free(remote_refname);
1771 goto done;
1773 error = got_ref_open(&target_ref, repo, remote_target, 0);
1774 if (error) {
1775 free(remote_refname);
1776 free(remote_target);
1777 if (error->code == GOT_ERR_NOT_REF) {
1778 error = NULL;
1779 continue;
1781 goto done;
1783 error = create_symref(remote_refname, target_ref,
1784 verbosity - 1, repo);
1785 free(remote_refname);
1786 free(remote_target);
1787 got_ref_close(target_ref);
1788 if (error)
1789 goto done;
1791 if (pe == NULL) {
1793 * We failed to set the HEAD reference. If we asked for
1794 * a set of wanted branches use the first of one of those
1795 * which could be fetched instead.
1797 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1798 const char *target = pe->path;
1799 struct got_reference *target_ref;
1801 error = got_ref_open(&target_ref, repo, target, 0);
1802 if (error) {
1803 if (error->code == GOT_ERR_NOT_REF) {
1804 error = NULL;
1805 continue;
1807 goto done;
1810 error = create_symref(GOT_REF_HEAD, target_ref,
1811 verbosity, repo);
1812 got_ref_close(target_ref);
1813 if (error)
1814 goto done;
1815 break;
1819 if (verbosity >= 0)
1820 printf("Created %s repository '%s'\n",
1821 mirror_references ? "mirrored" : "cloned", repo_path);
1822 done:
1823 if (pack_fds) {
1824 const struct got_error *pack_err =
1825 got_repo_pack_fds_close(pack_fds);
1826 if (error == NULL)
1827 error = pack_err;
1829 if (fetchpid > 0) {
1830 if (kill(fetchpid, SIGTERM) == -1)
1831 error = got_error_from_errno("kill");
1832 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1833 error = got_error_from_errno("waitpid");
1835 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1836 error = got_error_from_errno("close");
1837 if (repo) {
1838 const struct got_error *close_err = got_repo_close(repo);
1839 if (error == NULL)
1840 error = close_err;
1842 TAILQ_FOREACH(pe, &refs, entry) {
1843 free((void *)pe->path);
1844 free(pe->data);
1846 got_pathlist_free(&refs);
1847 TAILQ_FOREACH(pe, &symrefs, entry) {
1848 free((void *)pe->path);
1849 free(pe->data);
1851 got_pathlist_free(&symrefs);
1852 got_pathlist_free(&wanted_branches);
1853 got_pathlist_free(&wanted_refs);
1854 free(pack_hash);
1855 free(proto);
1856 free(host);
1857 free(port);
1858 free(server_path);
1859 free(repo_name);
1860 free(default_destdir);
1861 free(git_url);
1862 return error;
1865 static const struct got_error *
1866 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1867 int replace_tags, int verbosity, struct got_repository *repo)
1869 const struct got_error *err = NULL;
1870 char *new_id_str = NULL;
1871 struct got_object_id *old_id = NULL;
1873 err = got_object_id_str(&new_id_str, new_id);
1874 if (err)
1875 goto done;
1877 if (!replace_tags &&
1878 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1879 err = got_ref_resolve(&old_id, repo, ref);
1880 if (err)
1881 goto done;
1882 if (got_object_id_cmp(old_id, new_id) == 0)
1883 goto done;
1884 if (verbosity >= 0) {
1885 printf("Rejecting update of existing tag %s: %s\n",
1886 got_ref_get_name(ref), new_id_str);
1888 goto done;
1891 if (got_ref_is_symbolic(ref)) {
1892 if (verbosity >= 0) {
1893 printf("Replacing reference %s: %s\n",
1894 got_ref_get_name(ref),
1895 got_ref_get_symref_target(ref));
1897 err = got_ref_change_symref_to_ref(ref, new_id);
1898 if (err)
1899 goto done;
1900 err = got_ref_write(ref, repo);
1901 if (err)
1902 goto done;
1903 } else {
1904 err = got_ref_resolve(&old_id, repo, ref);
1905 if (err)
1906 goto done;
1907 if (got_object_id_cmp(old_id, new_id) == 0)
1908 goto done;
1910 err = got_ref_change_ref(ref, new_id);
1911 if (err)
1912 goto done;
1913 err = got_ref_write(ref, repo);
1914 if (err)
1915 goto done;
1918 if (verbosity >= 0)
1919 printf("Updated %s: %s\n", got_ref_get_name(ref),
1920 new_id_str);
1921 done:
1922 free(old_id);
1923 free(new_id_str);
1924 return err;
1927 static const struct got_error *
1928 update_symref(const char *refname, struct got_reference *target_ref,
1929 int verbosity, struct got_repository *repo)
1931 const struct got_error *err = NULL, *unlock_err;
1932 struct got_reference *symref;
1933 int symref_is_locked = 0;
1935 err = got_ref_open(&symref, repo, refname, 1);
1936 if (err) {
1937 if (err->code != GOT_ERR_NOT_REF)
1938 return err;
1939 err = got_ref_alloc_symref(&symref, refname, target_ref);
1940 if (err)
1941 goto done;
1943 err = got_ref_write(symref, repo);
1944 if (err)
1945 goto done;
1947 if (verbosity >= 0)
1948 printf("Created reference %s: %s\n",
1949 got_ref_get_name(symref),
1950 got_ref_get_symref_target(symref));
1951 } else {
1952 symref_is_locked = 1;
1954 if (strcmp(got_ref_get_symref_target(symref),
1955 got_ref_get_name(target_ref)) == 0)
1956 goto done;
1958 err = got_ref_change_symref(symref,
1959 got_ref_get_name(target_ref));
1960 if (err)
1961 goto done;
1963 err = got_ref_write(symref, repo);
1964 if (err)
1965 goto done;
1967 if (verbosity >= 0)
1968 printf("Updated %s: %s\n", got_ref_get_name(symref),
1969 got_ref_get_symref_target(symref));
1972 done:
1973 if (symref_is_locked) {
1974 unlock_err = got_ref_unlock(symref);
1975 if (unlock_err && err == NULL)
1976 err = unlock_err;
1978 got_ref_close(symref);
1979 return err;
1982 __dead static void
1983 usage_fetch(void)
1985 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1986 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1987 "[remote-repository-name]\n",
1988 getprogname());
1989 exit(1);
1992 static const struct got_error *
1993 delete_missing_ref(struct got_reference *ref,
1994 int verbosity, struct got_repository *repo)
1996 const struct got_error *err = NULL;
1997 struct got_object_id *id = NULL;
1998 char *id_str = NULL;
2000 if (got_ref_is_symbolic(ref)) {
2001 err = got_ref_delete(ref, repo);
2002 if (err)
2003 return err;
2004 if (verbosity >= 0) {
2005 printf("Deleted %s: %s\n",
2006 got_ref_get_name(ref),
2007 got_ref_get_symref_target(ref));
2009 } else {
2010 err = got_ref_resolve(&id, repo, ref);
2011 if (err)
2012 return err;
2013 err = got_object_id_str(&id_str, id);
2014 if (err)
2015 goto done;
2017 err = got_ref_delete(ref, repo);
2018 if (err)
2019 goto done;
2020 if (verbosity >= 0) {
2021 printf("Deleted %s: %s\n",
2022 got_ref_get_name(ref), id_str);
2025 done:
2026 free(id);
2027 free(id_str);
2028 return NULL;
2031 static const struct got_error *
2032 delete_missing_refs(struct got_pathlist_head *their_refs,
2033 struct got_pathlist_head *their_symrefs,
2034 const struct got_remote_repo *remote,
2035 int verbosity, struct got_repository *repo)
2037 const struct got_error *err = NULL, *unlock_err;
2038 struct got_reflist_head my_refs;
2039 struct got_reflist_entry *re;
2040 struct got_pathlist_entry *pe;
2041 char *remote_namespace = NULL;
2042 char *local_refname = NULL;
2044 TAILQ_INIT(&my_refs);
2046 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2047 == -1)
2048 return got_error_from_errno("asprintf");
2050 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2051 if (err)
2052 goto done;
2054 TAILQ_FOREACH(re, &my_refs, entry) {
2055 const char *refname = got_ref_get_name(re->ref);
2056 const char *their_refname;
2058 if (remote->mirror_references) {
2059 their_refname = refname;
2060 } else {
2061 if (strncmp(refname, remote_namespace,
2062 strlen(remote_namespace)) == 0) {
2063 if (strcmp(refname + strlen(remote_namespace),
2064 GOT_REF_HEAD) == 0)
2065 continue;
2066 if (asprintf(&local_refname, "refs/heads/%s",
2067 refname + strlen(remote_namespace)) == -1) {
2068 err = got_error_from_errno("asprintf");
2069 goto done;
2071 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2072 continue;
2074 their_refname = local_refname;
2077 TAILQ_FOREACH(pe, their_refs, entry) {
2078 if (strcmp(their_refname, pe->path) == 0)
2079 break;
2081 if (pe != NULL)
2082 continue;
2084 TAILQ_FOREACH(pe, their_symrefs, entry) {
2085 if (strcmp(their_refname, pe->path) == 0)
2086 break;
2088 if (pe != NULL)
2089 continue;
2091 err = delete_missing_ref(re->ref, verbosity, repo);
2092 if (err)
2093 break;
2095 if (local_refname) {
2096 struct got_reference *ref;
2097 err = got_ref_open(&ref, repo, local_refname, 1);
2098 if (err) {
2099 if (err->code != GOT_ERR_NOT_REF)
2100 break;
2101 free(local_refname);
2102 local_refname = NULL;
2103 continue;
2105 err = delete_missing_ref(ref, verbosity, repo);
2106 if (err)
2107 break;
2108 unlock_err = got_ref_unlock(ref);
2109 got_ref_close(ref);
2110 if (unlock_err && err == NULL) {
2111 err = unlock_err;
2112 break;
2115 free(local_refname);
2116 local_refname = NULL;
2119 done:
2120 free(remote_namespace);
2121 free(local_refname);
2122 return err;
2125 static const struct got_error *
2126 update_wanted_ref(const char *refname, struct got_object_id *id,
2127 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2129 const struct got_error *err, *unlock_err;
2130 char *remote_refname;
2131 struct got_reference *ref;
2133 if (strncmp("refs/", refname, 5) == 0)
2134 refname += 5;
2136 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2137 remote_repo_name, refname) == -1)
2138 return got_error_from_errno("asprintf");
2140 err = got_ref_open(&ref, repo, remote_refname, 1);
2141 if (err) {
2142 if (err->code != GOT_ERR_NOT_REF)
2143 goto done;
2144 err = create_ref(remote_refname, id, verbosity, repo);
2145 } else {
2146 err = update_ref(ref, id, 0, verbosity, repo);
2147 unlock_err = got_ref_unlock(ref);
2148 if (unlock_err && err == NULL)
2149 err = unlock_err;
2150 got_ref_close(ref);
2152 done:
2153 free(remote_refname);
2154 return err;
2157 static const struct got_error *
2158 delete_ref(struct got_repository *repo, struct got_reference *ref)
2160 const struct got_error *err = NULL;
2161 struct got_object_id *id = NULL;
2162 char *id_str = NULL;
2163 const char *target;
2165 if (got_ref_is_symbolic(ref)) {
2166 target = got_ref_get_symref_target(ref);
2167 } else {
2168 err = got_ref_resolve(&id, repo, ref);
2169 if (err)
2170 goto done;
2171 err = got_object_id_str(&id_str, id);
2172 if (err)
2173 goto done;
2174 target = id_str;
2177 err = got_ref_delete(ref, repo);
2178 if (err)
2179 goto done;
2181 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2182 done:
2183 free(id);
2184 free(id_str);
2185 return err;
2188 static const struct got_error *
2189 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2191 const struct got_error *err = NULL;
2192 struct got_reflist_head refs;
2193 struct got_reflist_entry *re;
2194 char *prefix;
2196 TAILQ_INIT(&refs);
2198 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2199 err = got_error_from_errno("asprintf");
2200 goto done;
2202 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2203 if (err)
2204 goto done;
2206 TAILQ_FOREACH(re, &refs, entry)
2207 delete_ref(repo, re->ref);
2208 done:
2209 got_ref_list_free(&refs);
2210 return err;
2213 static const struct got_error *
2214 cmd_fetch(int argc, char *argv[])
2216 const struct got_error *error = NULL, *unlock_err;
2217 char *cwd = NULL, *repo_path = NULL;
2218 const char *remote_name;
2219 char *proto = NULL, *host = NULL, *port = NULL;
2220 char *repo_name = NULL, *server_path = NULL;
2221 const struct got_remote_repo *remotes, *remote = NULL;
2222 int nremotes;
2223 char *id_str = NULL;
2224 struct got_repository *repo = NULL;
2225 struct got_worktree *worktree = NULL;
2226 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2227 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2228 struct got_pathlist_entry *pe;
2229 struct got_object_id *pack_hash = NULL;
2230 int i, ch, fetchfd = -1, fetchstatus;
2231 pid_t fetchpid = -1;
2232 struct got_fetch_progress_arg fpa;
2233 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2234 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2235 int *pack_fds = NULL;
2237 TAILQ_INIT(&refs);
2238 TAILQ_INIT(&symrefs);
2239 TAILQ_INIT(&wanted_branches);
2240 TAILQ_INIT(&wanted_refs);
2242 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2243 switch (ch) {
2244 case 'a':
2245 fetch_all_branches = 1;
2246 break;
2247 case 'b':
2248 error = got_pathlist_append(&wanted_branches,
2249 optarg, NULL);
2250 if (error)
2251 return error;
2252 break;
2253 case 'd':
2254 delete_refs = 1;
2255 break;
2256 case 'l':
2257 list_refs_only = 1;
2258 break;
2259 case 'r':
2260 repo_path = realpath(optarg, NULL);
2261 if (repo_path == NULL)
2262 return got_error_from_errno2("realpath",
2263 optarg);
2264 got_path_strip_trailing_slashes(repo_path);
2265 break;
2266 case 't':
2267 replace_tags = 1;
2268 break;
2269 case 'v':
2270 if (verbosity < 0)
2271 verbosity = 0;
2272 else if (verbosity < 3)
2273 verbosity++;
2274 break;
2275 case 'q':
2276 verbosity = -1;
2277 break;
2278 case 'R':
2279 error = got_pathlist_append(&wanted_refs,
2280 optarg, NULL);
2281 if (error)
2282 return error;
2283 break;
2284 case 'X':
2285 delete_remote = 1;
2286 break;
2287 default:
2288 usage_fetch();
2289 break;
2292 argc -= optind;
2293 argv += optind;
2295 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2296 option_conflict('a', 'b');
2297 if (list_refs_only) {
2298 if (!TAILQ_EMPTY(&wanted_branches))
2299 option_conflict('l', 'b');
2300 if (fetch_all_branches)
2301 option_conflict('l', 'a');
2302 if (delete_refs)
2303 option_conflict('l', 'd');
2304 if (delete_remote)
2305 option_conflict('l', 'X');
2307 if (delete_remote) {
2308 if (fetch_all_branches)
2309 option_conflict('X', 'a');
2310 if (!TAILQ_EMPTY(&wanted_branches))
2311 option_conflict('X', 'b');
2312 if (delete_refs)
2313 option_conflict('X', 'd');
2314 if (replace_tags)
2315 option_conflict('X', 't');
2316 if (!TAILQ_EMPTY(&wanted_refs))
2317 option_conflict('X', 'R');
2320 if (argc == 0) {
2321 if (delete_remote)
2322 errx(1, "-X option requires a remote name");
2323 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2324 } else if (argc == 1)
2325 remote_name = argv[0];
2326 else
2327 usage_fetch();
2329 cwd = getcwd(NULL, 0);
2330 if (cwd == NULL) {
2331 error = got_error_from_errno("getcwd");
2332 goto done;
2335 error = got_repo_pack_fds_open(&pack_fds);
2336 if (error != NULL)
2337 goto done;
2339 if (repo_path == NULL) {
2340 error = got_worktree_open(&worktree, cwd);
2341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2342 goto done;
2343 else
2344 error = NULL;
2345 if (worktree) {
2346 repo_path =
2347 strdup(got_worktree_get_repo_path(worktree));
2348 if (repo_path == NULL)
2349 error = got_error_from_errno("strdup");
2350 if (error)
2351 goto done;
2352 } else {
2353 repo_path = strdup(cwd);
2354 if (repo_path == NULL) {
2355 error = got_error_from_errno("strdup");
2356 goto done;
2361 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2362 if (error)
2363 goto done;
2365 if (delete_remote) {
2366 error = delete_refs_for_remote(repo, remote_name);
2367 goto done; /* nothing else to do */
2370 if (worktree) {
2371 worktree_conf = got_worktree_get_gotconfig(worktree);
2372 if (worktree_conf) {
2373 got_gotconfig_get_remotes(&nremotes, &remotes,
2374 worktree_conf);
2375 for (i = 0; i < nremotes; i++) {
2376 if (strcmp(remotes[i].name, remote_name) == 0) {
2377 remote = &remotes[i];
2378 break;
2383 if (remote == NULL) {
2384 repo_conf = got_repo_get_gotconfig(repo);
2385 if (repo_conf) {
2386 got_gotconfig_get_remotes(&nremotes, &remotes,
2387 repo_conf);
2388 for (i = 0; i < nremotes; i++) {
2389 if (strcmp(remotes[i].name, remote_name) == 0) {
2390 remote = &remotes[i];
2391 break;
2396 if (remote == NULL) {
2397 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2398 for (i = 0; i < nremotes; i++) {
2399 if (strcmp(remotes[i].name, remote_name) == 0) {
2400 remote = &remotes[i];
2401 break;
2405 if (remote == NULL) {
2406 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2407 goto done;
2410 if (TAILQ_EMPTY(&wanted_branches)) {
2411 if (!fetch_all_branches)
2412 fetch_all_branches = remote->fetch_all_branches;
2413 for (i = 0; i < remote->nfetch_branches; i++) {
2414 got_pathlist_append(&wanted_branches,
2415 remote->fetch_branches[i], NULL);
2418 if (TAILQ_EMPTY(&wanted_refs)) {
2419 for (i = 0; i < remote->nfetch_refs; i++) {
2420 got_pathlist_append(&wanted_refs,
2421 remote->fetch_refs[i], NULL);
2425 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2426 &repo_name, remote->fetch_url);
2427 if (error)
2428 goto done;
2430 if (strcmp(proto, "git") == 0) {
2431 #ifndef PROFILE
2432 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2433 "sendfd dns inet unveil", NULL) == -1)
2434 err(1, "pledge");
2435 #endif
2436 } else if (strcmp(proto, "git+ssh") == 0 ||
2437 strcmp(proto, "ssh") == 0) {
2438 #ifndef PROFILE
2439 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2440 "sendfd unveil", NULL) == -1)
2441 err(1, "pledge");
2442 #endif
2443 } else if (strcmp(proto, "http") == 0 ||
2444 strcmp(proto, "git+http") == 0) {
2445 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2446 goto done;
2447 } else {
2448 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2449 goto done;
2452 error = got_dial_apply_unveil(proto);
2453 if (error)
2454 goto done;
2456 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2457 if (error)
2458 goto done;
2460 if (verbosity >= 0)
2461 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2462 port ? ":" : "", port ? port : "");
2464 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2465 server_path, verbosity);
2466 if (error)
2467 goto done;
2469 fpa.last_scaled_size[0] = '\0';
2470 fpa.last_p_indexed = -1;
2471 fpa.last_p_resolved = -1;
2472 fpa.verbosity = verbosity;
2473 fpa.repo = repo;
2474 fpa.create_configs = 0;
2475 fpa.configs_created = 0;
2476 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2477 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2478 remote->mirror_references, fetch_all_branches, &wanted_branches,
2479 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2480 fetch_progress, &fpa);
2481 if (error)
2482 goto done;
2484 if (list_refs_only) {
2485 error = list_remote_refs(&symrefs, &refs);
2486 goto done;
2489 if (pack_hash == NULL) {
2490 if (verbosity >= 0)
2491 printf("Already up-to-date\n");
2492 } else if (verbosity >= 0) {
2493 error = got_object_id_str(&id_str, pack_hash);
2494 if (error)
2495 goto done;
2496 printf("\nFetched %s.pack\n", id_str);
2497 free(id_str);
2498 id_str = NULL;
2501 /* Update references provided with the pack file. */
2502 TAILQ_FOREACH(pe, &refs, entry) {
2503 const char *refname = pe->path;
2504 struct got_object_id *id = pe->data;
2505 struct got_reference *ref;
2506 char *remote_refname;
2508 if (is_wanted_ref(&wanted_refs, refname) &&
2509 !remote->mirror_references) {
2510 error = update_wanted_ref(refname, id,
2511 remote->name, verbosity, repo);
2512 if (error)
2513 goto done;
2514 continue;
2517 if (remote->mirror_references ||
2518 strncmp("refs/tags/", refname, 10) == 0) {
2519 error = got_ref_open(&ref, repo, refname, 1);
2520 if (error) {
2521 if (error->code != GOT_ERR_NOT_REF)
2522 goto done;
2523 error = create_ref(refname, id, verbosity,
2524 repo);
2525 if (error)
2526 goto done;
2527 } else {
2528 error = update_ref(ref, id, replace_tags,
2529 verbosity, repo);
2530 unlock_err = got_ref_unlock(ref);
2531 if (unlock_err && error == NULL)
2532 error = unlock_err;
2533 got_ref_close(ref);
2534 if (error)
2535 goto done;
2537 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2538 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2539 remote_name, refname + 11) == -1) {
2540 error = got_error_from_errno("asprintf");
2541 goto done;
2544 error = got_ref_open(&ref, repo, remote_refname, 1);
2545 if (error) {
2546 if (error->code != GOT_ERR_NOT_REF)
2547 goto done;
2548 error = create_ref(remote_refname, id,
2549 verbosity, repo);
2550 if (error)
2551 goto done;
2552 } else {
2553 error = update_ref(ref, id, replace_tags,
2554 verbosity, repo);
2555 unlock_err = got_ref_unlock(ref);
2556 if (unlock_err && error == NULL)
2557 error = unlock_err;
2558 got_ref_close(ref);
2559 if (error)
2560 goto done;
2563 /* Also create a local branch if none exists yet. */
2564 error = got_ref_open(&ref, repo, refname, 1);
2565 if (error) {
2566 if (error->code != GOT_ERR_NOT_REF)
2567 goto done;
2568 error = create_ref(refname, id, verbosity,
2569 repo);
2570 if (error)
2571 goto done;
2572 } else {
2573 unlock_err = got_ref_unlock(ref);
2574 if (unlock_err && error == NULL)
2575 error = unlock_err;
2576 got_ref_close(ref);
2580 if (delete_refs) {
2581 error = delete_missing_refs(&refs, &symrefs, remote,
2582 verbosity, repo);
2583 if (error)
2584 goto done;
2587 if (!remote->mirror_references) {
2588 /* Update remote HEAD reference if the server provided one. */
2589 TAILQ_FOREACH(pe, &symrefs, entry) {
2590 struct got_reference *target_ref;
2591 const char *refname = pe->path;
2592 const char *target = pe->data;
2593 char *remote_refname = NULL, *remote_target = NULL;
2595 if (strcmp(refname, GOT_REF_HEAD) != 0)
2596 continue;
2598 if (strncmp("refs/heads/", target, 11) != 0)
2599 continue;
2601 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2602 remote->name, refname) == -1) {
2603 error = got_error_from_errno("asprintf");
2604 goto done;
2606 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2607 remote->name, target + 11) == -1) {
2608 error = got_error_from_errno("asprintf");
2609 free(remote_refname);
2610 goto done;
2613 error = got_ref_open(&target_ref, repo, remote_target,
2614 0);
2615 if (error) {
2616 free(remote_refname);
2617 free(remote_target);
2618 if (error->code == GOT_ERR_NOT_REF) {
2619 error = NULL;
2620 continue;
2622 goto done;
2624 error = update_symref(remote_refname, target_ref,
2625 verbosity, repo);
2626 free(remote_refname);
2627 free(remote_target);
2628 got_ref_close(target_ref);
2629 if (error)
2630 goto done;
2633 done:
2634 if (fetchpid > 0) {
2635 if (kill(fetchpid, SIGTERM) == -1)
2636 error = got_error_from_errno("kill");
2637 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2638 error = got_error_from_errno("waitpid");
2640 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2641 error = got_error_from_errno("close");
2642 if (repo) {
2643 const struct got_error *close_err = got_repo_close(repo);
2644 if (error == NULL)
2645 error = close_err;
2647 if (worktree)
2648 got_worktree_close(worktree);
2649 if (pack_fds) {
2650 const struct got_error *pack_err =
2651 got_repo_pack_fds_close(pack_fds);
2652 if (error == NULL)
2653 error = pack_err;
2655 TAILQ_FOREACH(pe, &refs, entry) {
2656 free((void *)pe->path);
2657 free(pe->data);
2659 got_pathlist_free(&refs);
2660 TAILQ_FOREACH(pe, &symrefs, entry) {
2661 free((void *)pe->path);
2662 free(pe->data);
2664 got_pathlist_free(&symrefs);
2665 got_pathlist_free(&wanted_branches);
2666 got_pathlist_free(&wanted_refs);
2667 free(id_str);
2668 free(cwd);
2669 free(repo_path);
2670 free(pack_hash);
2671 free(proto);
2672 free(host);
2673 free(port);
2674 free(server_path);
2675 free(repo_name);
2676 return error;
2680 __dead static void
2681 usage_checkout(void)
2683 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2684 "[-p prefix] [-q] repository-path [worktree-path]\n",
2685 getprogname());
2686 exit(1);
2689 static void
2690 show_worktree_base_ref_warning(void)
2692 fprintf(stderr, "%s: warning: could not create a reference "
2693 "to the work tree's base commit; the commit could be "
2694 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2695 "repository writable and running 'got update' will prevent this\n",
2696 getprogname());
2699 struct got_checkout_progress_arg {
2700 const char *worktree_path;
2701 int had_base_commit_ref_error;
2702 int verbosity;
2705 static const struct got_error *
2706 checkout_progress(void *arg, unsigned char status, const char *path)
2708 struct got_checkout_progress_arg *a = arg;
2710 /* Base commit bump happens silently. */
2711 if (status == GOT_STATUS_BUMP_BASE)
2712 return NULL;
2714 if (status == GOT_STATUS_BASE_REF_ERR) {
2715 a->had_base_commit_ref_error = 1;
2716 return NULL;
2719 while (path[0] == '/')
2720 path++;
2722 if (a->verbosity >= 0)
2723 printf("%c %s/%s\n", status, a->worktree_path, path);
2725 return NULL;
2728 static const struct got_error *
2729 check_cancelled(void *arg)
2731 if (sigint_received || sigpipe_received)
2732 return got_error(GOT_ERR_CANCELLED);
2733 return NULL;
2736 static const struct got_error *
2737 check_linear_ancestry(struct got_object_id *commit_id,
2738 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2739 struct got_repository *repo)
2741 const struct got_error *err = NULL;
2742 struct got_object_id *yca_id;
2744 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2745 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2746 if (err)
2747 return err;
2749 if (yca_id == NULL)
2750 return got_error(GOT_ERR_ANCESTRY);
2753 * Require a straight line of history between the target commit
2754 * and the work tree's base commit.
2756 * Non-linear situations such as this require a rebase:
2758 * (commit) D F (base_commit)
2759 * \ /
2760 * C E
2761 * \ /
2762 * B (yca)
2763 * |
2764 * A
2766 * 'got update' only handles linear cases:
2767 * Update forwards in time: A (base/yca) - B - C - D (commit)
2768 * Update backwards in time: D (base) - C - B - A (commit/yca)
2770 if (allow_forwards_in_time_only) {
2771 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2772 return got_error(GOT_ERR_ANCESTRY);
2773 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2774 got_object_id_cmp(base_commit_id, yca_id) != 0)
2775 return got_error(GOT_ERR_ANCESTRY);
2777 free(yca_id);
2778 return NULL;
2781 static const struct got_error *
2782 check_same_branch(struct got_object_id *commit_id,
2783 struct got_reference *head_ref, struct got_object_id *yca_id,
2784 struct got_repository *repo)
2786 const struct got_error *err = NULL;
2787 struct got_commit_graph *graph = NULL;
2788 struct got_object_id *head_commit_id = NULL;
2789 int is_same_branch = 0;
2791 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2792 if (err)
2793 goto done;
2795 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2796 is_same_branch = 1;
2797 goto done;
2799 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2800 is_same_branch = 1;
2801 goto done;
2804 err = got_commit_graph_open(&graph, "/", 1);
2805 if (err)
2806 goto done;
2808 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2809 check_cancelled, NULL);
2810 if (err)
2811 goto done;
2813 for (;;) {
2814 struct got_object_id *id;
2815 err = got_commit_graph_iter_next(&id, graph, repo,
2816 check_cancelled, NULL);
2817 if (err) {
2818 if (err->code == GOT_ERR_ITER_COMPLETED)
2819 err = NULL;
2820 break;
2823 if (id) {
2824 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2825 break;
2826 if (got_object_id_cmp(id, commit_id) == 0) {
2827 is_same_branch = 1;
2828 break;
2832 done:
2833 if (graph)
2834 got_commit_graph_close(graph);
2835 free(head_commit_id);
2836 if (!err && !is_same_branch)
2837 err = got_error(GOT_ERR_ANCESTRY);
2838 return err;
2841 static const struct got_error *
2842 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2844 static char msg[512];
2845 const char *branch_name;
2847 if (got_ref_is_symbolic(ref))
2848 branch_name = got_ref_get_symref_target(ref);
2849 else
2850 branch_name = got_ref_get_name(ref);
2852 if (strncmp("refs/heads/", branch_name, 11) == 0)
2853 branch_name += 11;
2855 snprintf(msg, sizeof(msg),
2856 "target commit is not contained in branch '%s'; "
2857 "the branch to use must be specified with -b; "
2858 "if necessary a new branch can be created for "
2859 "this commit with 'got branch -c %s BRANCH_NAME'",
2860 branch_name, commit_id_str);
2862 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2865 static const struct got_error *
2866 cmd_checkout(int argc, char *argv[])
2868 const struct got_error *error = NULL;
2869 struct got_repository *repo = NULL;
2870 struct got_reference *head_ref = NULL, *ref = NULL;
2871 struct got_worktree *worktree = NULL;
2872 char *repo_path = NULL;
2873 char *worktree_path = NULL;
2874 const char *path_prefix = "";
2875 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2876 char *commit_id_str = NULL;
2877 struct got_object_id *commit_id = NULL;
2878 char *cwd = NULL;
2879 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2880 struct got_pathlist_head paths;
2881 struct got_checkout_progress_arg cpa;
2882 int *pack_fds = NULL;
2884 TAILQ_INIT(&paths);
2886 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2887 switch (ch) {
2888 case 'b':
2889 branch_name = optarg;
2890 break;
2891 case 'c':
2892 commit_id_str = strdup(optarg);
2893 if (commit_id_str == NULL)
2894 return got_error_from_errno("strdup");
2895 break;
2896 case 'E':
2897 allow_nonempty = 1;
2898 break;
2899 case 'p':
2900 path_prefix = optarg;
2901 break;
2902 case 'q':
2903 verbosity = -1;
2904 break;
2905 default:
2906 usage_checkout();
2907 /* NOTREACHED */
2911 argc -= optind;
2912 argv += optind;
2914 #ifndef PROFILE
2915 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2916 "unveil", NULL) == -1)
2917 err(1, "pledge");
2918 #endif
2919 if (argc == 1) {
2920 char *base, *dotgit;
2921 const char *path;
2922 repo_path = realpath(argv[0], NULL);
2923 if (repo_path == NULL)
2924 return got_error_from_errno2("realpath", argv[0]);
2925 cwd = getcwd(NULL, 0);
2926 if (cwd == NULL) {
2927 error = got_error_from_errno("getcwd");
2928 goto done;
2930 if (path_prefix[0])
2931 path = path_prefix;
2932 else
2933 path = repo_path;
2934 error = got_path_basename(&base, path);
2935 if (error)
2936 goto done;
2937 dotgit = strstr(base, ".git");
2938 if (dotgit)
2939 *dotgit = '\0';
2940 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2941 error = got_error_from_errno("asprintf");
2942 free(base);
2943 goto done;
2945 free(base);
2946 } else if (argc == 2) {
2947 repo_path = realpath(argv[0], NULL);
2948 if (repo_path == NULL) {
2949 error = got_error_from_errno2("realpath", argv[0]);
2950 goto done;
2952 worktree_path = realpath(argv[1], NULL);
2953 if (worktree_path == NULL) {
2954 if (errno != ENOENT) {
2955 error = got_error_from_errno2("realpath",
2956 argv[1]);
2957 goto done;
2959 worktree_path = strdup(argv[1]);
2960 if (worktree_path == NULL) {
2961 error = got_error_from_errno("strdup");
2962 goto done;
2965 } else
2966 usage_checkout();
2968 got_path_strip_trailing_slashes(repo_path);
2969 got_path_strip_trailing_slashes(worktree_path);
2971 error = got_repo_pack_fds_open(&pack_fds);
2972 if (error != NULL)
2973 goto done;
2975 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2976 if (error != NULL)
2977 goto done;
2979 /* Pre-create work tree path for unveil(2) */
2980 error = got_path_mkdir(worktree_path);
2981 if (error) {
2982 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2983 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2984 goto done;
2985 if (!allow_nonempty &&
2986 !got_path_dir_is_empty(worktree_path)) {
2987 error = got_error_path(worktree_path,
2988 GOT_ERR_DIR_NOT_EMPTY);
2989 goto done;
2993 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2994 if (error)
2995 goto done;
2997 error = got_ref_open(&head_ref, repo, branch_name, 0);
2998 if (error != NULL)
2999 goto done;
3001 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3002 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3003 goto done;
3005 error = got_worktree_open(&worktree, worktree_path);
3006 if (error != NULL)
3007 goto done;
3009 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3010 path_prefix);
3011 if (error != NULL)
3012 goto done;
3013 if (!same_path_prefix) {
3014 error = got_error(GOT_ERR_PATH_PREFIX);
3015 goto done;
3018 if (commit_id_str) {
3019 struct got_reflist_head refs;
3020 TAILQ_INIT(&refs);
3021 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3022 NULL);
3023 if (error)
3024 goto done;
3025 error = got_repo_match_object_id(&commit_id, NULL,
3026 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3027 got_ref_list_free(&refs);
3028 if (error)
3029 goto done;
3030 error = check_linear_ancestry(commit_id,
3031 got_worktree_get_base_commit_id(worktree), 0, repo);
3032 if (error != NULL) {
3033 if (error->code == GOT_ERR_ANCESTRY) {
3034 error = checkout_ancestry_error(
3035 head_ref, commit_id_str);
3037 goto done;
3039 error = check_same_branch(commit_id, head_ref, NULL, repo);
3040 if (error) {
3041 if (error->code == GOT_ERR_ANCESTRY) {
3042 error = checkout_ancestry_error(
3043 head_ref, commit_id_str);
3045 goto done;
3047 error = got_worktree_set_base_commit_id(worktree, repo,
3048 commit_id);
3049 if (error)
3050 goto done;
3051 /* Expand potentially abbreviated commit ID string. */
3052 free(commit_id_str);
3053 error = got_object_id_str(&commit_id_str, commit_id);
3054 if (error)
3055 goto done;
3056 } else {
3057 commit_id = got_object_id_dup(
3058 got_worktree_get_base_commit_id(worktree));
3059 if (commit_id == NULL) {
3060 error = got_error_from_errno("got_object_id_dup");
3061 goto done;
3063 error = got_object_id_str(&commit_id_str, commit_id);
3064 if (error)
3065 goto done;
3068 error = got_pathlist_append(&paths, "", NULL);
3069 if (error)
3070 goto done;
3071 cpa.worktree_path = worktree_path;
3072 cpa.had_base_commit_ref_error = 0;
3073 cpa.verbosity = verbosity;
3074 error = got_worktree_checkout_files(worktree, &paths, repo,
3075 checkout_progress, &cpa, check_cancelled, NULL);
3076 if (error != NULL)
3077 goto done;
3079 if (got_ref_is_symbolic(head_ref)) {
3080 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3081 if (error)
3082 goto done;
3083 refname = got_ref_get_name(ref);
3084 } else
3085 refname = got_ref_get_name(head_ref);
3086 printf("Checked out %s: %s\n", refname, commit_id_str);
3087 printf("Now shut up and hack\n");
3088 if (cpa.had_base_commit_ref_error)
3089 show_worktree_base_ref_warning();
3090 done:
3091 if (pack_fds) {
3092 const struct got_error *pack_err =
3093 got_repo_pack_fds_close(pack_fds);
3094 if (error == NULL)
3095 error = pack_err;
3097 if (head_ref)
3098 got_ref_close(head_ref);
3099 if (ref)
3100 got_ref_close(ref);
3101 got_pathlist_free(&paths);
3102 free(commit_id_str);
3103 free(commit_id);
3104 free(repo_path);
3105 free(worktree_path);
3106 free(cwd);
3107 return error;
3110 struct got_update_progress_arg {
3111 int did_something;
3112 int conflicts;
3113 int obstructed;
3114 int not_updated;
3115 int missing;
3116 int not_deleted;
3117 int unversioned;
3118 int verbosity;
3121 static void
3122 print_update_progress_stats(struct got_update_progress_arg *upa)
3124 if (!upa->did_something)
3125 return;
3127 if (upa->conflicts > 0)
3128 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3129 if (upa->obstructed > 0)
3130 printf("File paths obstructed by a non-regular file: %d\n",
3131 upa->obstructed);
3132 if (upa->not_updated > 0)
3133 printf("Files not updated because of existing merge "
3134 "conflicts: %d\n", upa->not_updated);
3138 * The meaning of some status codes differs between merge-style operations and
3139 * update operations. For example, the ! status code means "file was missing"
3140 * if changes were merged into the work tree, and "missing file was restored"
3141 * if the work tree was updated. This function should be used by any operation
3142 * which merges changes into the work tree without updating the work tree.
3144 static void
3145 print_merge_progress_stats(struct got_update_progress_arg *upa)
3147 if (!upa->did_something)
3148 return;
3150 if (upa->conflicts > 0)
3151 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3152 if (upa->obstructed > 0)
3153 printf("File paths obstructed by a non-regular file: %d\n",
3154 upa->obstructed);
3155 if (upa->missing > 0)
3156 printf("Files which had incoming changes but could not be "
3157 "found in the work tree: %d\n", upa->missing);
3158 if (upa->not_deleted > 0)
3159 printf("Files not deleted due to differences in deleted "
3160 "content: %d\n", upa->not_deleted);
3161 if (upa->unversioned > 0)
3162 printf("Files not merged because an unversioned file was "
3163 "found in the work tree: %d\n", upa->unversioned);
3166 __dead static void
3167 usage_update(void)
3169 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3170 "[path ...]\n",
3171 getprogname());
3172 exit(1);
3175 static const struct got_error *
3176 update_progress(void *arg, unsigned char status, const char *path)
3178 struct got_update_progress_arg *upa = arg;
3180 if (status == GOT_STATUS_EXISTS ||
3181 status == GOT_STATUS_BASE_REF_ERR)
3182 return NULL;
3184 upa->did_something = 1;
3186 /* Base commit bump happens silently. */
3187 if (status == GOT_STATUS_BUMP_BASE)
3188 return NULL;
3190 if (status == GOT_STATUS_CONFLICT)
3191 upa->conflicts++;
3192 if (status == GOT_STATUS_OBSTRUCTED)
3193 upa->obstructed++;
3194 if (status == GOT_STATUS_CANNOT_UPDATE)
3195 upa->not_updated++;
3196 if (status == GOT_STATUS_MISSING)
3197 upa->missing++;
3198 if (status == GOT_STATUS_CANNOT_DELETE)
3199 upa->not_deleted++;
3200 if (status == GOT_STATUS_UNVERSIONED)
3201 upa->unversioned++;
3203 while (path[0] == '/')
3204 path++;
3205 if (upa->verbosity >= 0)
3206 printf("%c %s\n", status, path);
3208 return NULL;
3211 static const struct got_error *
3212 switch_head_ref(struct got_reference *head_ref,
3213 struct got_object_id *commit_id, struct got_worktree *worktree,
3214 struct got_repository *repo)
3216 const struct got_error *err = NULL;
3217 char *base_id_str;
3218 int ref_has_moved = 0;
3220 /* Trivial case: switching between two different references. */
3221 if (strcmp(got_ref_get_name(head_ref),
3222 got_worktree_get_head_ref_name(worktree)) != 0) {
3223 printf("Switching work tree from %s to %s\n",
3224 got_worktree_get_head_ref_name(worktree),
3225 got_ref_get_name(head_ref));
3226 return got_worktree_set_head_ref(worktree, head_ref);
3229 err = check_linear_ancestry(commit_id,
3230 got_worktree_get_base_commit_id(worktree), 0, repo);
3231 if (err) {
3232 if (err->code != GOT_ERR_ANCESTRY)
3233 return err;
3234 ref_has_moved = 1;
3236 if (!ref_has_moved)
3237 return NULL;
3239 /* Switching to a rebased branch with the same reference name. */
3240 err = got_object_id_str(&base_id_str,
3241 got_worktree_get_base_commit_id(worktree));
3242 if (err)
3243 return err;
3244 printf("Reference %s now points at a different branch\n",
3245 got_worktree_get_head_ref_name(worktree));
3246 printf("Switching work tree from %s to %s\n", base_id_str,
3247 got_worktree_get_head_ref_name(worktree));
3248 return NULL;
3251 static const struct got_error *
3252 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3254 const struct got_error *err;
3255 int in_progress;
3257 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3258 if (err)
3259 return err;
3260 if (in_progress)
3261 return got_error(GOT_ERR_REBASING);
3263 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3264 if (err)
3265 return err;
3266 if (in_progress)
3267 return got_error(GOT_ERR_HISTEDIT_BUSY);
3269 return NULL;
3272 static const struct got_error *
3273 check_merge_in_progress(struct got_worktree *worktree,
3274 struct got_repository *repo)
3276 const struct got_error *err;
3277 int in_progress;
3279 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3280 if (err)
3281 return err;
3282 if (in_progress)
3283 return got_error(GOT_ERR_MERGE_BUSY);
3285 return NULL;
3288 static const struct got_error *
3289 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3290 char *argv[], struct got_worktree *worktree)
3292 const struct got_error *err = NULL;
3293 char *path;
3294 struct got_pathlist_entry *new;
3295 int i;
3297 if (argc == 0) {
3298 path = strdup("");
3299 if (path == NULL)
3300 return got_error_from_errno("strdup");
3301 return got_pathlist_append(paths, path, NULL);
3304 for (i = 0; i < argc; i++) {
3305 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3306 if (err)
3307 break;
3308 err = got_pathlist_insert(&new, paths, path, NULL);
3309 if (err || new == NULL /* duplicate */) {
3310 free(path);
3311 if (err)
3312 break;
3316 return err;
3319 static const struct got_error *
3320 wrap_not_worktree_error(const struct got_error *orig_err,
3321 const char *cmdname, const char *path)
3323 const struct got_error *err;
3324 struct got_repository *repo;
3325 static char msg[512];
3326 int *pack_fds = NULL;
3328 err = got_repo_pack_fds_open(&pack_fds);
3329 if (err)
3330 return err;
3332 err = got_repo_open(&repo, path, NULL, pack_fds);
3333 if (err)
3334 return orig_err;
3336 snprintf(msg, sizeof(msg),
3337 "'got %s' needs a work tree in addition to a git repository\n"
3338 "Work trees can be checked out from this Git repository with "
3339 "'got checkout'.\n"
3340 "The got(1) manual page contains more information.", cmdname);
3341 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3342 got_repo_close(repo);
3343 if (pack_fds) {
3344 const struct got_error *pack_err =
3345 got_repo_pack_fds_close(pack_fds);
3346 if (err == NULL)
3347 err = pack_err;
3349 return err;
3352 static const struct got_error *
3353 cmd_update(int argc, char *argv[])
3355 const struct got_error *error = NULL;
3356 struct got_repository *repo = NULL;
3357 struct got_worktree *worktree = NULL;
3358 char *worktree_path = NULL;
3359 struct got_object_id *commit_id = NULL;
3360 char *commit_id_str = NULL;
3361 const char *branch_name = NULL;
3362 struct got_reference *head_ref = NULL;
3363 struct got_pathlist_head paths;
3364 struct got_pathlist_entry *pe;
3365 int ch, verbosity = 0;
3366 struct got_update_progress_arg upa;
3367 int *pack_fds = NULL;
3369 TAILQ_INIT(&paths);
3371 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3372 switch (ch) {
3373 case 'b':
3374 branch_name = optarg;
3375 break;
3376 case 'c':
3377 commit_id_str = strdup(optarg);
3378 if (commit_id_str == NULL)
3379 return got_error_from_errno("strdup");
3380 break;
3381 case 'q':
3382 verbosity = -1;
3383 break;
3384 default:
3385 usage_update();
3386 /* NOTREACHED */
3390 argc -= optind;
3391 argv += optind;
3393 #ifndef PROFILE
3394 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3395 "unveil", NULL) == -1)
3396 err(1, "pledge");
3397 #endif
3398 worktree_path = getcwd(NULL, 0);
3399 if (worktree_path == NULL) {
3400 error = got_error_from_errno("getcwd");
3401 goto done;
3404 error = got_repo_pack_fds_open(&pack_fds);
3405 if (error != NULL)
3406 goto done;
3408 error = got_worktree_open(&worktree, worktree_path);
3409 if (error) {
3410 if (error->code == GOT_ERR_NOT_WORKTREE)
3411 error = wrap_not_worktree_error(error, "update",
3412 worktree_path);
3413 goto done;
3416 error = check_rebase_or_histedit_in_progress(worktree);
3417 if (error)
3418 goto done;
3420 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3421 NULL, pack_fds);
3422 if (error != NULL)
3423 goto done;
3425 error = apply_unveil(got_repo_get_path(repo), 0,
3426 got_worktree_get_root_path(worktree));
3427 if (error)
3428 goto done;
3430 error = check_merge_in_progress(worktree, repo);
3431 if (error)
3432 goto done;
3434 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3435 if (error)
3436 goto done;
3438 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3439 got_worktree_get_head_ref_name(worktree), 0);
3440 if (error != NULL)
3441 goto done;
3442 if (commit_id_str == NULL) {
3443 error = got_ref_resolve(&commit_id, repo, head_ref);
3444 if (error != NULL)
3445 goto done;
3446 error = got_object_id_str(&commit_id_str, commit_id);
3447 if (error != NULL)
3448 goto done;
3449 } else {
3450 struct got_reflist_head refs;
3451 TAILQ_INIT(&refs);
3452 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3453 NULL);
3454 if (error)
3455 goto done;
3456 error = got_repo_match_object_id(&commit_id, NULL,
3457 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3458 got_ref_list_free(&refs);
3459 free(commit_id_str);
3460 commit_id_str = NULL;
3461 if (error)
3462 goto done;
3463 error = got_object_id_str(&commit_id_str, commit_id);
3464 if (error)
3465 goto done;
3468 if (branch_name) {
3469 struct got_object_id *head_commit_id;
3470 TAILQ_FOREACH(pe, &paths, entry) {
3471 if (pe->path_len == 0)
3472 continue;
3473 error = got_error_msg(GOT_ERR_BAD_PATH,
3474 "switching between branches requires that "
3475 "the entire work tree gets updated");
3476 goto done;
3478 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3479 if (error)
3480 goto done;
3481 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3482 repo);
3483 free(head_commit_id);
3484 if (error != NULL)
3485 goto done;
3486 error = check_same_branch(commit_id, head_ref, NULL, repo);
3487 if (error)
3488 goto done;
3489 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3490 if (error)
3491 goto done;
3492 } else {
3493 error = check_linear_ancestry(commit_id,
3494 got_worktree_get_base_commit_id(worktree), 0, repo);
3495 if (error != NULL) {
3496 if (error->code == GOT_ERR_ANCESTRY)
3497 error = got_error(GOT_ERR_BRANCH_MOVED);
3498 goto done;
3500 error = check_same_branch(commit_id, head_ref, NULL, repo);
3501 if (error)
3502 goto done;
3505 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3506 commit_id) != 0) {
3507 error = got_worktree_set_base_commit_id(worktree, repo,
3508 commit_id);
3509 if (error)
3510 goto done;
3513 memset(&upa, 0, sizeof(upa));
3514 upa.verbosity = verbosity;
3515 error = got_worktree_checkout_files(worktree, &paths, repo,
3516 update_progress, &upa, check_cancelled, NULL);
3517 if (error != NULL)
3518 goto done;
3520 if (upa.did_something) {
3521 printf("Updated to %s: %s\n",
3522 got_worktree_get_head_ref_name(worktree), commit_id_str);
3523 } else
3524 printf("Already up-to-date\n");
3526 print_update_progress_stats(&upa);
3527 done:
3528 if (pack_fds) {
3529 const struct got_error *pack_err =
3530 got_repo_pack_fds_close(pack_fds);
3531 if (error == NULL)
3532 error = pack_err;
3534 free(worktree_path);
3535 TAILQ_FOREACH(pe, &paths, entry)
3536 free((char *)pe->path);
3537 got_pathlist_free(&paths);
3538 free(commit_id);
3539 free(commit_id_str);
3540 return error;
3543 static const struct got_error *
3544 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3545 const char *path, int diff_context, int ignore_whitespace,
3546 int force_text_diff, struct got_repository *repo, FILE *outfile)
3548 const struct got_error *err = NULL;
3549 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3550 FILE *f1 = NULL, *f2 = NULL;
3551 int fd1 = -1, fd2 = -1;
3553 fd1 = got_opentempfd();
3554 if (fd1 == -1)
3555 return got_error_from_errno("got_opentempfd");
3556 fd2 = got_opentempfd();
3557 if (fd2 == -1) {
3558 err = got_error_from_errno("got_opentempfd");
3559 goto done;
3562 if (blob_id1) {
3563 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3564 fd1);
3565 if (err)
3566 goto done;
3569 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3570 if (err)
3571 goto done;
3573 f1 = got_opentemp();
3574 if (f1 == NULL) {
3575 err = got_error_from_errno("got_opentemp");
3576 goto done;
3578 f2 = got_opentemp();
3579 if (f2 == NULL) {
3580 err = got_error_from_errno("got_opentemp");
3581 goto done;
3584 while (path[0] == '/')
3585 path++;
3586 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3587 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3588 force_text_diff, outfile);
3589 done:
3590 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3591 err = got_error_from_errno("close");
3592 if (blob1)
3593 got_object_blob_close(blob1);
3594 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3595 err = got_error_from_errno("close");
3596 got_object_blob_close(blob2);
3597 if (f1 && fclose(f1) == EOF && err == NULL)
3598 err = got_error_from_errno("fclose");
3599 if (f2 && fclose(f2) == EOF && err == NULL)
3600 err = got_error_from_errno("fclose");
3601 return err;
3604 static const struct got_error *
3605 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3606 const char *path, int diff_context, int ignore_whitespace,
3607 int force_text_diff, struct got_repository *repo, FILE *outfile)
3609 const struct got_error *err = NULL;
3610 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3611 struct got_diff_blob_output_unidiff_arg arg;
3612 FILE *f1 = NULL, *f2 = NULL;
3613 int fd1 = -1, fd2 = -1;
3615 if (tree_id1) {
3616 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3617 if (err)
3618 goto done;
3619 fd1 = got_opentempfd();
3620 if (fd1 == -1) {
3621 err = got_error_from_errno("got_opentempfd");
3622 goto done;
3626 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3627 if (err)
3628 goto done;
3630 f1 = got_opentemp();
3631 if (f1 == NULL) {
3632 err = got_error_from_errno("got_opentemp");
3633 goto done;
3636 f2 = got_opentemp();
3637 if (f2 == NULL) {
3638 err = got_error_from_errno("got_opentemp");
3639 goto done;
3641 fd2 = got_opentempfd();
3642 if (fd2 == -1) {
3643 err = got_error_from_errno("got_opentempfd");
3644 goto done;
3646 arg.diff_context = diff_context;
3647 arg.ignore_whitespace = ignore_whitespace;
3648 arg.force_text_diff = force_text_diff;
3649 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3650 arg.outfile = outfile;
3651 arg.line_offsets = NULL;
3652 arg.nlines = 0;
3653 while (path[0] == '/')
3654 path++;
3655 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3656 got_diff_blob_output_unidiff, &arg, 1);
3657 done:
3658 if (tree1)
3659 got_object_tree_close(tree1);
3660 if (tree2)
3661 got_object_tree_close(tree2);
3662 if (f1 && fclose(f1) == EOF && err == NULL)
3663 err = got_error_from_errno("fclose");
3664 if (f2 && fclose(f2) == EOF && err == NULL)
3665 err = got_error_from_errno("fclose");
3666 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3667 err = got_error_from_errno("close");
3668 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3669 err = got_error_from_errno("close");
3670 return err;
3673 static const struct got_error *
3674 get_changed_paths(struct got_pathlist_head *paths,
3675 struct got_commit_object *commit, struct got_repository *repo)
3677 const struct got_error *err = NULL;
3678 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3679 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3680 struct got_object_qid *qid;
3682 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3683 if (qid != NULL) {
3684 struct got_commit_object *pcommit;
3685 err = got_object_open_as_commit(&pcommit, repo,
3686 &qid->id);
3687 if (err)
3688 return err;
3690 tree_id1 = got_object_id_dup(
3691 got_object_commit_get_tree_id(pcommit));
3692 if (tree_id1 == NULL) {
3693 got_object_commit_close(pcommit);
3694 return got_error_from_errno("got_object_id_dup");
3696 got_object_commit_close(pcommit);
3700 if (tree_id1) {
3701 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3702 if (err)
3703 goto done;
3706 tree_id2 = got_object_commit_get_tree_id(commit);
3707 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3708 if (err)
3709 goto done;
3711 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3712 got_diff_tree_collect_changed_paths, paths, 0);
3713 done:
3714 if (tree1)
3715 got_object_tree_close(tree1);
3716 if (tree2)
3717 got_object_tree_close(tree2);
3718 free(tree_id1);
3719 return err;
3722 static const struct got_error *
3723 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3724 const char *path, int diff_context, struct got_repository *repo,
3725 FILE *outfile)
3727 const struct got_error *err = NULL;
3728 struct got_commit_object *pcommit = NULL;
3729 char *id_str1 = NULL, *id_str2 = NULL;
3730 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3731 struct got_object_qid *qid;
3733 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3734 if (qid != NULL) {
3735 err = got_object_open_as_commit(&pcommit, repo,
3736 &qid->id);
3737 if (err)
3738 return err;
3739 err = got_object_id_str(&id_str1, &qid->id);
3740 if (err)
3741 goto done;
3744 err = got_object_id_str(&id_str2, id);
3745 if (err)
3746 goto done;
3748 if (path && path[0] != '\0') {
3749 int obj_type;
3750 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3751 if (err)
3752 goto done;
3753 if (pcommit) {
3754 err = got_object_id_by_path(&obj_id1, repo,
3755 pcommit, path);
3756 if (err) {
3757 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3758 free(obj_id2);
3759 goto done;
3763 err = got_object_get_type(&obj_type, repo, obj_id2);
3764 if (err) {
3765 free(obj_id2);
3766 goto done;
3768 fprintf(outfile,
3769 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3770 fprintf(outfile, "commit - %s\n",
3771 id_str1 ? id_str1 : "/dev/null");
3772 fprintf(outfile, "commit + %s\n", id_str2);
3773 switch (obj_type) {
3774 case GOT_OBJ_TYPE_BLOB:
3775 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3776 0, 0, repo, outfile);
3777 break;
3778 case GOT_OBJ_TYPE_TREE:
3779 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3780 0, 0, repo, outfile);
3781 break;
3782 default:
3783 err = got_error(GOT_ERR_OBJ_TYPE);
3784 break;
3786 free(obj_id1);
3787 free(obj_id2);
3788 } else {
3789 obj_id2 = got_object_commit_get_tree_id(commit);
3790 if (pcommit)
3791 obj_id1 = got_object_commit_get_tree_id(pcommit);
3792 fprintf(outfile,
3793 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3794 fprintf(outfile, "commit - %s\n",
3795 id_str1 ? id_str1 : "/dev/null");
3796 fprintf(outfile, "commit + %s\n", id_str2);
3797 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3798 repo, outfile);
3800 done:
3801 free(id_str1);
3802 free(id_str2);
3803 if (pcommit)
3804 got_object_commit_close(pcommit);
3805 return err;
3808 static char *
3809 get_datestr(time_t *time, char *datebuf)
3811 struct tm mytm, *tm;
3812 char *p, *s;
3814 tm = gmtime_r(time, &mytm);
3815 if (tm == NULL)
3816 return NULL;
3817 s = asctime_r(tm, datebuf);
3818 if (s == NULL)
3819 return NULL;
3820 p = strchr(s, '\n');
3821 if (p)
3822 *p = '\0';
3823 return s;
3826 static const struct got_error *
3827 match_commit(int *have_match, struct got_object_id *id,
3828 struct got_commit_object *commit, regex_t *regex)
3830 const struct got_error *err = NULL;
3831 regmatch_t regmatch;
3832 char *id_str = NULL, *logmsg = NULL;
3834 *have_match = 0;
3836 err = got_object_id_str(&id_str, id);
3837 if (err)
3838 return err;
3840 err = got_object_commit_get_logmsg(&logmsg, commit);
3841 if (err)
3842 goto done;
3844 if (regexec(regex, got_object_commit_get_author(commit), 1,
3845 &regmatch, 0) == 0 ||
3846 regexec(regex, got_object_commit_get_committer(commit), 1,
3847 &regmatch, 0) == 0 ||
3848 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3849 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3850 *have_match = 1;
3851 done:
3852 free(id_str);
3853 free(logmsg);
3854 return err;
3857 static void
3858 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3859 regex_t *regex)
3861 regmatch_t regmatch;
3862 struct got_pathlist_entry *pe;
3864 *have_match = 0;
3866 TAILQ_FOREACH(pe, changed_paths, entry) {
3867 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3868 *have_match = 1;
3869 break;
3874 static const struct got_error *
3875 match_patch(int *have_match, struct got_commit_object *commit,
3876 struct got_object_id *id, const char *path, int diff_context,
3877 struct got_repository *repo, regex_t *regex, FILE *f)
3879 const struct got_error *err = NULL;
3880 char *line = NULL;
3881 size_t linesize = 0;
3882 ssize_t linelen;
3883 regmatch_t regmatch;
3885 *have_match = 0;
3887 err = got_opentemp_truncate(f);
3888 if (err)
3889 return err;
3891 err = print_patch(commit, id, path, diff_context, repo, f);
3892 if (err)
3893 goto done;
3895 if (fseeko(f, 0L, SEEK_SET) == -1) {
3896 err = got_error_from_errno("fseeko");
3897 goto done;
3900 while ((linelen = getline(&line, &linesize, f)) != -1) {
3901 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3902 *have_match = 1;
3903 break;
3906 done:
3907 free(line);
3908 return err;
3911 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3913 static const struct got_error*
3914 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3915 struct got_object_id *id, struct got_repository *repo,
3916 int local_only)
3918 static const struct got_error *err = NULL;
3919 struct got_reflist_entry *re;
3920 char *s;
3921 const char *name;
3923 *refs_str = NULL;
3925 TAILQ_FOREACH(re, refs, entry) {
3926 struct got_tag_object *tag = NULL;
3927 struct got_object_id *ref_id;
3928 int cmp;
3930 name = got_ref_get_name(re->ref);
3931 if (strcmp(name, GOT_REF_HEAD) == 0)
3932 continue;
3933 if (strncmp(name, "refs/", 5) == 0)
3934 name += 5;
3935 if (strncmp(name, "got/", 4) == 0)
3936 continue;
3937 if (strncmp(name, "heads/", 6) == 0)
3938 name += 6;
3939 if (strncmp(name, "remotes/", 8) == 0) {
3940 if (local_only)
3941 continue;
3942 name += 8;
3943 s = strstr(name, "/" GOT_REF_HEAD);
3944 if (s != NULL && s[strlen(s)] == '\0')
3945 continue;
3947 err = got_ref_resolve(&ref_id, repo, re->ref);
3948 if (err)
3949 break;
3950 if (strncmp(name, "tags/", 5) == 0) {
3951 err = got_object_open_as_tag(&tag, repo, ref_id);
3952 if (err) {
3953 if (err->code != GOT_ERR_OBJ_TYPE) {
3954 free(ref_id);
3955 break;
3957 /* Ref points at something other than a tag. */
3958 err = NULL;
3959 tag = NULL;
3962 cmp = got_object_id_cmp(tag ?
3963 got_object_tag_get_object_id(tag) : ref_id, id);
3964 free(ref_id);
3965 if (tag)
3966 got_object_tag_close(tag);
3967 if (cmp != 0)
3968 continue;
3969 s = *refs_str;
3970 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3971 s ? ", " : "", name) == -1) {
3972 err = got_error_from_errno("asprintf");
3973 free(s);
3974 *refs_str = NULL;
3975 break;
3977 free(s);
3980 return err;
3983 static const struct got_error *
3984 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3985 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3987 const struct got_error *err = NULL;
3988 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3989 char *comma, *s, *nl;
3990 struct got_reflist_head *refs;
3991 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3992 struct tm tm;
3993 time_t committer_time;
3995 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3996 if (refs) {
3997 err = build_refs_str(&ref_str, refs, id, repo, 1);
3998 if (err)
3999 return err;
4001 /* Display the first matching ref only. */
4002 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4003 *comma = '\0';
4006 if (ref_str == NULL) {
4007 err = got_object_id_str(&id_str, id);
4008 if (err)
4009 return err;
4012 committer_time = got_object_commit_get_committer_time(commit);
4013 if (gmtime_r(&committer_time, &tm) == NULL) {
4014 err = got_error_from_errno("gmtime_r");
4015 goto done;
4017 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4018 err = got_error(GOT_ERR_NO_SPACE);
4019 goto done;
4022 err = got_object_commit_get_logmsg(&logmsg0, commit);
4023 if (err)
4024 goto done;
4026 s = logmsg0;
4027 while (isspace((unsigned char)s[0]))
4028 s++;
4030 nl = strchr(s, '\n');
4031 if (nl) {
4032 *nl = '\0';
4035 if (ref_str)
4036 printf("%s%-7s %s\n", datebuf, ref_str, s);
4037 else
4038 printf("%s%.7s %s\n", datebuf, id_str, s);
4040 if (fflush(stdout) != 0 && err == NULL)
4041 err = got_error_from_errno("fflush");
4042 done:
4043 free(id_str);
4044 free(ref_str);
4045 free(logmsg0);
4046 return err;
4049 static const struct got_error *
4050 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4051 struct got_repository *repo, const char *path,
4052 struct got_pathlist_head *changed_paths, int show_patch,
4053 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4054 const char *custom_refs_str)
4056 const struct got_error *err = NULL;
4057 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4058 char datebuf[26];
4059 time_t committer_time;
4060 const char *author, *committer;
4061 char *refs_str = NULL;
4063 err = got_object_id_str(&id_str, id);
4064 if (err)
4065 return err;
4067 if (custom_refs_str == NULL) {
4068 struct got_reflist_head *refs;
4069 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4070 if (refs) {
4071 err = build_refs_str(&refs_str, refs, id, repo, 0);
4072 if (err)
4073 goto done;
4077 printf(GOT_COMMIT_SEP_STR);
4078 if (custom_refs_str)
4079 printf("commit %s (%s)\n", id_str, custom_refs_str);
4080 else
4081 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4082 refs_str ? refs_str : "", refs_str ? ")" : "");
4083 free(id_str);
4084 id_str = NULL;
4085 free(refs_str);
4086 refs_str = NULL;
4087 printf("from: %s\n", got_object_commit_get_author(commit));
4088 committer_time = got_object_commit_get_committer_time(commit);
4089 datestr = get_datestr(&committer_time, datebuf);
4090 if (datestr)
4091 printf("date: %s UTC\n", datestr);
4092 author = got_object_commit_get_author(commit);
4093 committer = got_object_commit_get_committer(commit);
4094 if (strcmp(author, committer) != 0)
4095 printf("via: %s\n", committer);
4096 if (got_object_commit_get_nparents(commit) > 1) {
4097 const struct got_object_id_queue *parent_ids;
4098 struct got_object_qid *qid;
4099 int n = 1;
4100 parent_ids = got_object_commit_get_parent_ids(commit);
4101 STAILQ_FOREACH(qid, parent_ids, entry) {
4102 err = got_object_id_str(&id_str, &qid->id);
4103 if (err)
4104 goto done;
4105 printf("parent %d: %s\n", n++, id_str);
4106 free(id_str);
4107 id_str = NULL;
4111 err = got_object_commit_get_logmsg(&logmsg0, commit);
4112 if (err)
4113 goto done;
4115 logmsg = logmsg0;
4116 do {
4117 line = strsep(&logmsg, "\n");
4118 if (line)
4119 printf(" %s\n", line);
4120 } while (line);
4121 free(logmsg0);
4123 if (changed_paths) {
4124 struct got_pathlist_entry *pe;
4125 TAILQ_FOREACH(pe, changed_paths, entry) {
4126 struct got_diff_changed_path *cp = pe->data;
4127 printf(" %c %s\n", cp->status, pe->path);
4129 printf("\n");
4131 if (show_patch) {
4132 err = print_patch(commit, id, path, diff_context, repo, stdout);
4133 if (err == 0)
4134 printf("\n");
4137 if (fflush(stdout) != 0 && err == NULL)
4138 err = got_error_from_errno("fflush");
4139 done:
4140 free(id_str);
4141 free(refs_str);
4142 return err;
4145 static const struct got_error *
4146 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4147 struct got_repository *repo, const char *path, int show_changed_paths,
4148 int show_patch, const char *search_pattern, int diff_context, int limit,
4149 int log_branches, int reverse_display_order,
4150 struct got_reflist_object_id_map *refs_idmap, int one_line,
4151 FILE *tmpfile)
4153 const struct got_error *err;
4154 struct got_commit_graph *graph;
4155 regex_t regex;
4156 int have_match;
4157 struct got_object_id_queue reversed_commits;
4158 struct got_object_qid *qid;
4159 struct got_commit_object *commit;
4160 struct got_pathlist_head changed_paths;
4161 struct got_pathlist_entry *pe;
4163 STAILQ_INIT(&reversed_commits);
4164 TAILQ_INIT(&changed_paths);
4166 if (search_pattern && regcomp(&regex, search_pattern,
4167 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4168 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4170 err = got_commit_graph_open(&graph, path, !log_branches);
4171 if (err)
4172 return err;
4173 err = got_commit_graph_iter_start(graph, root_id, repo,
4174 check_cancelled, NULL);
4175 if (err)
4176 goto done;
4177 for (;;) {
4178 struct got_object_id *id;
4180 if (sigint_received || sigpipe_received)
4181 break;
4183 err = got_commit_graph_iter_next(&id, graph, repo,
4184 check_cancelled, NULL);
4185 if (err) {
4186 if (err->code == GOT_ERR_ITER_COMPLETED)
4187 err = NULL;
4188 break;
4190 if (id == NULL)
4191 break;
4193 err = got_object_open_as_commit(&commit, repo, id);
4194 if (err)
4195 break;
4197 if (show_changed_paths && !reverse_display_order) {
4198 err = get_changed_paths(&changed_paths, commit, repo);
4199 if (err)
4200 break;
4203 if (search_pattern) {
4204 err = match_commit(&have_match, id, commit, &regex);
4205 if (err) {
4206 got_object_commit_close(commit);
4207 break;
4209 if (have_match == 0 && show_changed_paths)
4210 match_changed_paths(&have_match,
4211 &changed_paths, &regex);
4212 if (have_match == 0 && show_patch) {
4213 err = match_patch(&have_match, commit, id,
4214 path, diff_context, repo, &regex,
4215 tmpfile);
4216 if (err)
4217 break;
4219 if (have_match == 0) {
4220 got_object_commit_close(commit);
4221 TAILQ_FOREACH(pe, &changed_paths, entry) {
4222 free((char *)pe->path);
4223 free(pe->data);
4225 got_pathlist_free(&changed_paths);
4226 continue;
4230 if (reverse_display_order) {
4231 err = got_object_qid_alloc(&qid, id);
4232 if (err)
4233 break;
4234 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4235 got_object_commit_close(commit);
4236 } else {
4237 if (one_line)
4238 err = print_commit_oneline(commit, id,
4239 repo, refs_idmap);
4240 else
4241 err = print_commit(commit, id, repo, path,
4242 show_changed_paths ? &changed_paths : NULL,
4243 show_patch, diff_context, refs_idmap, NULL);
4244 got_object_commit_close(commit);
4245 if (err)
4246 break;
4248 if ((limit && --limit == 0) ||
4249 (end_id && got_object_id_cmp(id, end_id) == 0))
4250 break;
4252 TAILQ_FOREACH(pe, &changed_paths, entry) {
4253 free((char *)pe->path);
4254 free(pe->data);
4256 got_pathlist_free(&changed_paths);
4258 if (reverse_display_order) {
4259 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4260 err = got_object_open_as_commit(&commit, repo,
4261 &qid->id);
4262 if (err)
4263 break;
4264 if (show_changed_paths) {
4265 err = get_changed_paths(&changed_paths,
4266 commit, repo);
4267 if (err)
4268 break;
4270 if (one_line)
4271 err = print_commit_oneline(commit, &qid->id,
4272 repo, refs_idmap);
4273 else
4274 err = print_commit(commit, &qid->id, repo, path,
4275 show_changed_paths ? &changed_paths : NULL,
4276 show_patch, diff_context, refs_idmap, NULL);
4277 got_object_commit_close(commit);
4278 if (err)
4279 break;
4280 TAILQ_FOREACH(pe, &changed_paths, entry) {
4281 free((char *)pe->path);
4282 free(pe->data);
4284 got_pathlist_free(&changed_paths);
4287 done:
4288 while (!STAILQ_EMPTY(&reversed_commits)) {
4289 qid = STAILQ_FIRST(&reversed_commits);
4290 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4291 got_object_qid_free(qid);
4293 TAILQ_FOREACH(pe, &changed_paths, entry) {
4294 free((char *)pe->path);
4295 free(pe->data);
4297 got_pathlist_free(&changed_paths);
4298 if (search_pattern)
4299 regfree(&regex);
4300 got_commit_graph_close(graph);
4301 return err;
4304 __dead static void
4305 usage_log(void)
4307 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4308 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4309 "[-r repository-path] [-R] [path]\n", getprogname());
4310 exit(1);
4313 static int
4314 get_default_log_limit(void)
4316 const char *got_default_log_limit;
4317 long long n;
4318 const char *errstr;
4320 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4321 if (got_default_log_limit == NULL)
4322 return 0;
4323 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4324 if (errstr != NULL)
4325 return 0;
4326 return n;
4329 static const struct got_error *
4330 cmd_log(int argc, char *argv[])
4332 const struct got_error *error;
4333 struct got_repository *repo = NULL;
4334 struct got_worktree *worktree = NULL;
4335 struct got_object_id *start_id = NULL, *end_id = NULL;
4336 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4337 const char *start_commit = NULL, *end_commit = NULL;
4338 const char *search_pattern = NULL;
4339 int diff_context = -1, ch;
4340 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4341 int reverse_display_order = 0, one_line = 0;
4342 const char *errstr;
4343 struct got_reflist_head refs;
4344 struct got_reflist_object_id_map *refs_idmap = NULL;
4345 FILE *tmpfile = NULL;
4346 int *pack_fds = NULL;
4348 TAILQ_INIT(&refs);
4350 #ifndef PROFILE
4351 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4352 NULL)
4353 == -1)
4354 err(1, "pledge");
4355 #endif
4357 limit = get_default_log_limit();
4359 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4360 switch (ch) {
4361 case 'p':
4362 show_patch = 1;
4363 break;
4364 case 'P':
4365 show_changed_paths = 1;
4366 break;
4367 case 'c':
4368 start_commit = optarg;
4369 break;
4370 case 'C':
4371 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4372 &errstr);
4373 if (errstr != NULL)
4374 errx(1, "number of context lines is %s: %s",
4375 errstr, optarg);
4376 break;
4377 case 'l':
4378 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4379 if (errstr != NULL)
4380 errx(1, "number of commits is %s: %s",
4381 errstr, optarg);
4382 break;
4383 case 'b':
4384 log_branches = 1;
4385 break;
4386 case 'r':
4387 repo_path = realpath(optarg, NULL);
4388 if (repo_path == NULL)
4389 return got_error_from_errno2("realpath",
4390 optarg);
4391 got_path_strip_trailing_slashes(repo_path);
4392 break;
4393 case 'R':
4394 reverse_display_order = 1;
4395 break;
4396 case 's':
4397 one_line = 1;
4398 break;
4399 case 'S':
4400 search_pattern = optarg;
4401 break;
4402 case 'x':
4403 end_commit = optarg;
4404 break;
4405 default:
4406 usage_log();
4407 /* NOTREACHED */
4411 argc -= optind;
4412 argv += optind;
4414 if (diff_context == -1)
4415 diff_context = 3;
4416 else if (!show_patch)
4417 errx(1, "-C requires -p");
4419 if (one_line && (show_patch || show_changed_paths))
4420 errx(1, "cannot use -s with -p or -P");
4422 cwd = getcwd(NULL, 0);
4423 if (cwd == NULL) {
4424 error = got_error_from_errno("getcwd");
4425 goto done;
4428 error = got_repo_pack_fds_open(&pack_fds);
4429 if (error != NULL)
4430 goto done;
4432 if (repo_path == NULL) {
4433 error = got_worktree_open(&worktree, cwd);
4434 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4435 goto done;
4436 error = NULL;
4439 if (argc == 1) {
4440 if (worktree) {
4441 error = got_worktree_resolve_path(&path, worktree,
4442 argv[0]);
4443 if (error)
4444 goto done;
4445 } else {
4446 path = strdup(argv[0]);
4447 if (path == NULL) {
4448 error = got_error_from_errno("strdup");
4449 goto done;
4452 } else if (argc != 0)
4453 usage_log();
4455 if (repo_path == NULL) {
4456 repo_path = worktree ?
4457 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4459 if (repo_path == NULL) {
4460 error = got_error_from_errno("strdup");
4461 goto done;
4464 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4465 if (error != NULL)
4466 goto done;
4468 error = apply_unveil(got_repo_get_path(repo), 1,
4469 worktree ? got_worktree_get_root_path(worktree) : NULL);
4470 if (error)
4471 goto done;
4473 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4474 if (error)
4475 goto done;
4477 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4478 if (error)
4479 goto done;
4481 if (start_commit == NULL) {
4482 struct got_reference *head_ref;
4483 struct got_commit_object *commit = NULL;
4484 error = got_ref_open(&head_ref, repo,
4485 worktree ? got_worktree_get_head_ref_name(worktree)
4486 : GOT_REF_HEAD, 0);
4487 if (error != NULL)
4488 goto done;
4489 error = got_ref_resolve(&start_id, repo, head_ref);
4490 got_ref_close(head_ref);
4491 if (error != NULL)
4492 goto done;
4493 error = got_object_open_as_commit(&commit, repo,
4494 start_id);
4495 if (error != NULL)
4496 goto done;
4497 got_object_commit_close(commit);
4498 } else {
4499 error = got_repo_match_object_id(&start_id, NULL,
4500 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4501 if (error != NULL)
4502 goto done;
4504 if (end_commit != NULL) {
4505 error = got_repo_match_object_id(&end_id, NULL,
4506 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4507 if (error != NULL)
4508 goto done;
4511 if (worktree) {
4513 * If a path was specified on the command line it was resolved
4514 * to a path in the work tree above. Prepend the work tree's
4515 * path prefix to obtain the corresponding in-repository path.
4517 if (path) {
4518 const char *prefix;
4519 prefix = got_worktree_get_path_prefix(worktree);
4520 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4521 (path[0] != '\0') ? "/" : "", path) == -1) {
4522 error = got_error_from_errno("asprintf");
4523 goto done;
4526 } else
4527 error = got_repo_map_path(&in_repo_path, repo,
4528 path ? path : "");
4529 if (error != NULL)
4530 goto done;
4531 if (in_repo_path) {
4532 free(path);
4533 path = in_repo_path;
4536 if (worktree) {
4537 /* Release work tree lock. */
4538 got_worktree_close(worktree);
4539 worktree = NULL;
4542 if (search_pattern && show_patch) {
4543 tmpfile = got_opentemp();
4544 if (tmpfile == NULL) {
4545 error = got_error_from_errno("got_opentemp");
4546 goto done;
4550 error = print_commits(start_id, end_id, repo, path ? path : "",
4551 show_changed_paths, show_patch, search_pattern, diff_context,
4552 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4553 tmpfile);
4554 done:
4555 free(path);
4556 free(repo_path);
4557 free(cwd);
4558 if (worktree)
4559 got_worktree_close(worktree);
4560 if (repo) {
4561 const struct got_error *close_err = got_repo_close(repo);
4562 if (error == NULL)
4563 error = close_err;
4565 if (pack_fds) {
4566 const struct got_error *pack_err =
4567 got_repo_pack_fds_close(pack_fds);
4568 if (error == NULL)
4569 error = pack_err;
4571 if (refs_idmap)
4572 got_reflist_object_id_map_free(refs_idmap);
4573 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4574 error = got_error_from_errno("fclose");
4575 got_ref_list_free(&refs);
4576 return error;
4579 __dead static void
4580 usage_diff(void)
4582 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4583 "[-r repository-path] [-s] [-w] [-P] "
4584 "[object1 object2 | path ...]\n", getprogname());
4585 exit(1);
4588 struct print_diff_arg {
4589 struct got_repository *repo;
4590 struct got_worktree *worktree;
4591 int diff_context;
4592 const char *id_str;
4593 int header_shown;
4594 int diff_staged;
4595 enum got_diff_algorithm diff_algo;
4596 int ignore_whitespace;
4597 int force_text_diff;
4598 FILE *f1;
4599 FILE *f2;
4603 * Create a file which contains the target path of a symlink so we can feed
4604 * it as content to the diff engine.
4606 static const struct got_error *
4607 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4608 const char *abspath)
4610 const struct got_error *err = NULL;
4611 char target_path[PATH_MAX];
4612 ssize_t target_len, outlen;
4614 *fd = -1;
4616 if (dirfd != -1) {
4617 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4618 if (target_len == -1)
4619 return got_error_from_errno2("readlinkat", abspath);
4620 } else {
4621 target_len = readlink(abspath, target_path, PATH_MAX);
4622 if (target_len == -1)
4623 return got_error_from_errno2("readlink", abspath);
4626 *fd = got_opentempfd();
4627 if (*fd == -1)
4628 return got_error_from_errno("got_opentempfd");
4630 outlen = write(*fd, target_path, target_len);
4631 if (outlen == -1) {
4632 err = got_error_from_errno("got_opentempfd");
4633 goto done;
4636 if (lseek(*fd, 0, SEEK_SET) == -1) {
4637 err = got_error_from_errno2("lseek", abspath);
4638 goto done;
4640 done:
4641 if (err) {
4642 close(*fd);
4643 *fd = -1;
4645 return err;
4648 static const struct got_error *
4649 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4650 const char *path, struct got_object_id *blob_id,
4651 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4652 int dirfd, const char *de_name)
4654 struct print_diff_arg *a = arg;
4655 const struct got_error *err = NULL;
4656 struct got_blob_object *blob1 = NULL;
4657 int fd = -1, fd1 = -1, fd2 = -1;
4658 FILE *f2 = NULL;
4659 char *abspath = NULL, *label1 = NULL;
4660 struct stat sb;
4661 off_t size1 = 0;
4662 int f2_exists = 1;
4664 if (a->diff_staged) {
4665 if (staged_status != GOT_STATUS_MODIFY &&
4666 staged_status != GOT_STATUS_ADD &&
4667 staged_status != GOT_STATUS_DELETE)
4668 return NULL;
4669 } else {
4670 if (staged_status == GOT_STATUS_DELETE)
4671 return NULL;
4672 if (status == GOT_STATUS_NONEXISTENT)
4673 return got_error_set_errno(ENOENT, path);
4674 if (status != GOT_STATUS_MODIFY &&
4675 status != GOT_STATUS_ADD &&
4676 status != GOT_STATUS_DELETE &&
4677 status != GOT_STATUS_CONFLICT)
4678 return NULL;
4681 err = got_opentemp_truncate(a->f1);
4682 if (err)
4683 return got_error_from_errno("got_opentemp_truncate");
4684 err = got_opentemp_truncate(a->f2);
4685 if (err)
4686 return got_error_from_errno("got_opentemp_truncate");
4688 if (!a->header_shown) {
4689 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4690 got_worktree_get_root_path(a->worktree));
4691 printf("commit - %s\n", a->id_str);
4692 printf("path + %s%s\n",
4693 got_worktree_get_root_path(a->worktree),
4694 a->diff_staged ? " (staged changes)" : "");
4695 a->header_shown = 1;
4698 if (a->diff_staged) {
4699 const char *label1 = NULL, *label2 = NULL;
4700 switch (staged_status) {
4701 case GOT_STATUS_MODIFY:
4702 label1 = path;
4703 label2 = path;
4704 break;
4705 case GOT_STATUS_ADD:
4706 label2 = path;
4707 break;
4708 case GOT_STATUS_DELETE:
4709 label1 = path;
4710 break;
4711 default:
4712 return got_error(GOT_ERR_FILE_STATUS);
4714 fd1 = got_opentempfd();
4715 if (fd1 == -1) {
4716 err = got_error_from_errno("got_opentempfd");
4717 goto done;
4719 fd2 = got_opentempfd();
4720 if (fd2 == -1) {
4721 err = got_error_from_errno("got_opentempfd");
4722 goto done;
4724 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4725 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4726 a->diff_algo, a->diff_context, a->ignore_whitespace,
4727 a->force_text_diff, a->repo, stdout);
4728 goto done;
4731 fd1 = got_opentempfd();
4732 if (fd1 == -1) {
4733 err = got_error_from_errno("got_opentempfd");
4734 goto done;
4737 if (staged_status == GOT_STATUS_ADD ||
4738 staged_status == GOT_STATUS_MODIFY) {
4739 char *id_str;
4740 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4741 8192, fd1);
4742 if (err)
4743 goto done;
4744 err = got_object_id_str(&id_str, staged_blob_id);
4745 if (err)
4746 goto done;
4747 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4748 err = got_error_from_errno("asprintf");
4749 free(id_str);
4750 goto done;
4752 free(id_str);
4753 } else if (status != GOT_STATUS_ADD) {
4754 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4755 fd1);
4756 if (err)
4757 goto done;
4760 if (status != GOT_STATUS_DELETE) {
4761 if (asprintf(&abspath, "%s/%s",
4762 got_worktree_get_root_path(a->worktree), path) == -1) {
4763 err = got_error_from_errno("asprintf");
4764 goto done;
4767 if (dirfd != -1) {
4768 fd = openat(dirfd, de_name,
4769 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4770 if (fd == -1) {
4771 if (!got_err_open_nofollow_on_symlink()) {
4772 err = got_error_from_errno2("openat",
4773 abspath);
4774 goto done;
4776 err = get_symlink_target_file(&fd, dirfd,
4777 de_name, abspath);
4778 if (err)
4779 goto done;
4781 } else {
4782 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4783 if (fd == -1) {
4784 if (!got_err_open_nofollow_on_symlink()) {
4785 err = got_error_from_errno2("open",
4786 abspath);
4787 goto done;
4789 err = get_symlink_target_file(&fd, dirfd,
4790 de_name, abspath);
4791 if (err)
4792 goto done;
4795 if (fstat(fd, &sb) == -1) {
4796 err = got_error_from_errno2("fstat", abspath);
4797 goto done;
4799 f2 = fdopen(fd, "r");
4800 if (f2 == NULL) {
4801 err = got_error_from_errno2("fdopen", abspath);
4802 goto done;
4804 fd = -1;
4805 } else {
4806 sb.st_size = 0;
4807 f2_exists = 0;
4810 if (blob1) {
4811 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4812 a->f1, blob1);
4813 if (err)
4814 goto done;
4817 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4818 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4819 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4820 done:
4821 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4822 err = got_error_from_errno("close");
4823 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4824 err = got_error_from_errno("close");
4825 if (blob1)
4826 got_object_blob_close(blob1);
4827 if (fd != -1 && close(fd) == -1 && err == NULL)
4828 err = got_error_from_errno("close");
4829 if (f2 && fclose(f2) == EOF && err == NULL)
4830 err = got_error_from_errno("fclose");
4831 free(abspath);
4832 return err;
4835 static const struct got_error *
4836 cmd_diff(int argc, char *argv[])
4838 const struct got_error *error;
4839 struct got_repository *repo = NULL;
4840 struct got_worktree *worktree = NULL;
4841 char *cwd = NULL, *repo_path = NULL;
4842 const char *commit_args[2] = { NULL, NULL };
4843 int ncommit_args = 0;
4844 struct got_object_id *ids[2] = { NULL, NULL };
4845 char *labels[2] = { NULL, NULL };
4846 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4847 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4848 int force_text_diff = 0, force_path = 0, rflag = 0;
4849 const char *errstr;
4850 struct got_reflist_head refs;
4851 struct got_pathlist_head paths;
4852 struct got_pathlist_entry *pe;
4853 FILE *f1 = NULL, *f2 = NULL;
4854 int fd1 = -1, fd2 = -1;
4855 int *pack_fds = NULL;
4857 TAILQ_INIT(&refs);
4858 TAILQ_INIT(&paths);
4860 #ifndef PROFILE
4861 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4862 NULL) == -1)
4863 err(1, "pledge");
4864 #endif
4866 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4867 switch (ch) {
4868 case 'a':
4869 force_text_diff = 1;
4870 break;
4871 case 'c':
4872 if (ncommit_args >= 2)
4873 errx(1, "too many -c options used");
4874 commit_args[ncommit_args++] = optarg;
4875 break;
4876 case 'C':
4877 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4878 &errstr);
4879 if (errstr != NULL)
4880 errx(1, "number of context lines is %s: %s",
4881 errstr, optarg);
4882 break;
4883 case 'r':
4884 repo_path = realpath(optarg, NULL);
4885 if (repo_path == NULL)
4886 return got_error_from_errno2("realpath",
4887 optarg);
4888 got_path_strip_trailing_slashes(repo_path);
4889 rflag = 1;
4890 break;
4891 case 's':
4892 diff_staged = 1;
4893 break;
4894 case 'w':
4895 ignore_whitespace = 1;
4896 break;
4897 case 'P':
4898 force_path = 1;
4899 break;
4900 default:
4901 usage_diff();
4902 /* NOTREACHED */
4906 argc -= optind;
4907 argv += optind;
4909 cwd = getcwd(NULL, 0);
4910 if (cwd == NULL) {
4911 error = got_error_from_errno("getcwd");
4912 goto done;
4915 error = got_repo_pack_fds_open(&pack_fds);
4916 if (error != NULL)
4917 goto done;
4919 if (repo_path == NULL) {
4920 error = got_worktree_open(&worktree, cwd);
4921 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4922 goto done;
4923 else
4924 error = NULL;
4925 if (worktree) {
4926 repo_path =
4927 strdup(got_worktree_get_repo_path(worktree));
4928 if (repo_path == NULL) {
4929 error = got_error_from_errno("strdup");
4930 goto done;
4932 } else {
4933 repo_path = strdup(cwd);
4934 if (repo_path == NULL) {
4935 error = got_error_from_errno("strdup");
4936 goto done;
4941 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4942 free(repo_path);
4943 if (error != NULL)
4944 goto done;
4946 if (rflag || worktree == NULL || ncommit_args > 0) {
4947 if (force_path) {
4948 error = got_error_msg(GOT_ERR_NOT_IMPL,
4949 "-P option can only be used when diffing "
4950 "a work tree");
4951 goto done;
4953 if (diff_staged) {
4954 error = got_error_msg(GOT_ERR_NOT_IMPL,
4955 "-s option can only be used when diffing "
4956 "a work tree");
4957 goto done;
4961 error = apply_unveil(got_repo_get_path(repo), 1,
4962 worktree ? got_worktree_get_root_path(worktree) : NULL);
4963 if (error)
4964 goto done;
4966 if ((!force_path && argc == 2) || ncommit_args > 0) {
4967 int obj_type = (ncommit_args > 0 ?
4968 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4969 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4970 NULL);
4971 if (error)
4972 goto done;
4973 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4974 const char *arg;
4975 if (ncommit_args > 0)
4976 arg = commit_args[i];
4977 else
4978 arg = argv[i];
4979 error = got_repo_match_object_id(&ids[i], &labels[i],
4980 arg, obj_type, &refs, repo);
4981 if (error) {
4982 if (error->code != GOT_ERR_NOT_REF &&
4983 error->code != GOT_ERR_NO_OBJ)
4984 goto done;
4985 if (ncommit_args > 0)
4986 goto done;
4987 error = NULL;
4988 break;
4993 f1 = got_opentemp();
4994 if (f1 == NULL) {
4995 error = got_error_from_errno("got_opentemp");
4996 goto done;
4999 f2 = got_opentemp();
5000 if (f2 == NULL) {
5001 error = got_error_from_errno("got_opentemp");
5002 goto done;
5005 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5006 struct print_diff_arg arg;
5007 char *id_str;
5009 if (worktree == NULL) {
5010 if (argc == 2 && ids[0] == NULL) {
5011 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5012 goto done;
5013 } else if (argc == 2 && ids[1] == NULL) {
5014 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5015 goto done;
5016 } else if (argc > 0) {
5017 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5018 "%s", "specified paths cannot be resolved");
5019 goto done;
5020 } else {
5021 error = got_error(GOT_ERR_NOT_WORKTREE);
5022 goto done;
5026 error = get_worktree_paths_from_argv(&paths, argc, argv,
5027 worktree);
5028 if (error)
5029 goto done;
5031 error = got_object_id_str(&id_str,
5032 got_worktree_get_base_commit_id(worktree));
5033 if (error)
5034 goto done;
5035 arg.repo = repo;
5036 arg.worktree = worktree;
5037 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5038 arg.diff_context = diff_context;
5039 arg.id_str = id_str;
5040 arg.header_shown = 0;
5041 arg.diff_staged = diff_staged;
5042 arg.ignore_whitespace = ignore_whitespace;
5043 arg.force_text_diff = force_text_diff;
5044 arg.f1 = f1;
5045 arg.f2 = f2;
5047 error = got_worktree_status(worktree, &paths, repo, 0,
5048 print_diff, &arg, check_cancelled, NULL);
5049 free(id_str);
5050 goto done;
5053 if (ncommit_args == 1) {
5054 struct got_commit_object *commit;
5055 error = got_object_open_as_commit(&commit, repo, ids[0]);
5056 if (error)
5057 goto done;
5059 labels[1] = labels[0];
5060 ids[1] = ids[0];
5061 if (got_object_commit_get_nparents(commit) > 0) {
5062 const struct got_object_id_queue *pids;
5063 struct got_object_qid *pid;
5064 pids = got_object_commit_get_parent_ids(commit);
5065 pid = STAILQ_FIRST(pids);
5066 ids[0] = got_object_id_dup(&pid->id);
5067 if (ids[0] == NULL) {
5068 error = got_error_from_errno(
5069 "got_object_id_dup");
5070 got_object_commit_close(commit);
5071 goto done;
5073 error = got_object_id_str(&labels[0], ids[0]);
5074 if (error) {
5075 got_object_commit_close(commit);
5076 goto done;
5078 } else {
5079 ids[0] = NULL;
5080 labels[0] = strdup("/dev/null");
5081 if (labels[0] == NULL) {
5082 error = got_error_from_errno("strdup");
5083 got_object_commit_close(commit);
5084 goto done;
5088 got_object_commit_close(commit);
5091 if (ncommit_args == 0 && argc > 2) {
5092 error = got_error_msg(GOT_ERR_BAD_PATH,
5093 "path arguments cannot be used when diffing two objects");
5094 goto done;
5097 if (ids[0]) {
5098 error = got_object_get_type(&type1, repo, ids[0]);
5099 if (error)
5100 goto done;
5103 error = got_object_get_type(&type2, repo, ids[1]);
5104 if (error)
5105 goto done;
5106 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5107 error = got_error(GOT_ERR_OBJ_TYPE);
5108 goto done;
5110 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5111 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5112 "path arguments cannot be used when diffing blobs");
5113 goto done;
5116 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5117 char *in_repo_path;
5118 struct got_pathlist_entry *new;
5119 if (worktree) {
5120 const char *prefix;
5121 char *p;
5122 error = got_worktree_resolve_path(&p, worktree,
5123 argv[i]);
5124 if (error)
5125 goto done;
5126 prefix = got_worktree_get_path_prefix(worktree);
5127 while (prefix[0] == '/')
5128 prefix++;
5129 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5130 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5131 p) == -1) {
5132 error = got_error_from_errno("asprintf");
5133 free(p);
5134 goto done;
5136 free(p);
5137 } else {
5138 char *mapped_path, *s;
5139 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5140 if (error)
5141 goto done;
5142 s = mapped_path;
5143 while (s[0] == '/')
5144 s++;
5145 in_repo_path = strdup(s);
5146 if (in_repo_path == NULL) {
5147 error = got_error_from_errno("asprintf");
5148 free(mapped_path);
5149 goto done;
5151 free(mapped_path);
5154 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5155 if (error || new == NULL /* duplicate */)
5156 free(in_repo_path);
5157 if (error)
5158 goto done;
5161 if (worktree) {
5162 /* Release work tree lock. */
5163 got_worktree_close(worktree);
5164 worktree = NULL;
5167 fd1 = got_opentempfd();
5168 if (fd1 == -1) {
5169 error = got_error_from_errno("got_opentempfd");
5170 goto done;
5173 fd2 = got_opentempfd();
5174 if (fd2 == -1) {
5175 error = got_error_from_errno("got_opentempfd");
5176 goto done;
5179 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5180 case GOT_OBJ_TYPE_BLOB:
5181 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5182 fd1, fd2, ids[0], ids[1], NULL, NULL,
5183 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5184 ignore_whitespace, force_text_diff, repo, stdout);
5185 break;
5186 case GOT_OBJ_TYPE_TREE:
5187 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5188 ids[0], ids[1], &paths, "", "",
5189 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5190 ignore_whitespace, force_text_diff, repo, stdout);
5191 break;
5192 case GOT_OBJ_TYPE_COMMIT:
5193 printf("diff %s %s\n", labels[0], labels[1]);
5194 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5195 fd1, fd2, ids[0], ids[1], &paths,
5196 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5197 ignore_whitespace, force_text_diff, repo, stdout);
5198 break;
5199 default:
5200 error = got_error(GOT_ERR_OBJ_TYPE);
5202 done:
5203 free(labels[0]);
5204 free(labels[1]);
5205 free(ids[0]);
5206 free(ids[1]);
5207 if (worktree)
5208 got_worktree_close(worktree);
5209 if (repo) {
5210 const struct got_error *close_err = got_repo_close(repo);
5211 if (error == NULL)
5212 error = close_err;
5214 if (pack_fds) {
5215 const struct got_error *pack_err =
5216 got_repo_pack_fds_close(pack_fds);
5217 if (error == NULL)
5218 error = pack_err;
5220 TAILQ_FOREACH(pe, &paths, entry)
5221 free((char *)pe->path);
5222 got_pathlist_free(&paths);
5223 got_ref_list_free(&refs);
5224 if (f1 && fclose(f1) == EOF && error == NULL)
5225 error = got_error_from_errno("fclose");
5226 if (f2 && fclose(f2) == EOF && error == NULL)
5227 error = got_error_from_errno("fclose");
5228 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5229 error = got_error_from_errno("close");
5230 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5231 error = got_error_from_errno("close");
5232 return error;
5235 __dead static void
5236 usage_blame(void)
5238 fprintf(stderr,
5239 "usage: %s blame [-c commit] [-r repository-path] path\n",
5240 getprogname());
5241 exit(1);
5244 struct blame_line {
5245 int annotated;
5246 char *id_str;
5247 char *committer;
5248 char datebuf[11]; /* YYYY-MM-DD + NUL */
5251 struct blame_cb_args {
5252 struct blame_line *lines;
5253 int nlines;
5254 int nlines_prec;
5255 int lineno_cur;
5256 off_t *line_offsets;
5257 FILE *f;
5258 struct got_repository *repo;
5261 static const struct got_error *
5262 blame_cb(void *arg, int nlines, int lineno,
5263 struct got_commit_object *commit, struct got_object_id *id)
5265 const struct got_error *err = NULL;
5266 struct blame_cb_args *a = arg;
5267 struct blame_line *bline;
5268 char *line = NULL;
5269 size_t linesize = 0;
5270 off_t offset;
5271 struct tm tm;
5272 time_t committer_time;
5274 if (nlines != a->nlines ||
5275 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5276 return got_error(GOT_ERR_RANGE);
5278 if (sigint_received)
5279 return got_error(GOT_ERR_ITER_COMPLETED);
5281 if (lineno == -1)
5282 return NULL; /* no change in this commit */
5284 /* Annotate this line. */
5285 bline = &a->lines[lineno - 1];
5286 if (bline->annotated)
5287 return NULL;
5288 err = got_object_id_str(&bline->id_str, id);
5289 if (err)
5290 return err;
5292 bline->committer = strdup(got_object_commit_get_committer(commit));
5293 if (bline->committer == NULL) {
5294 err = got_error_from_errno("strdup");
5295 goto done;
5298 committer_time = got_object_commit_get_committer_time(commit);
5299 if (gmtime_r(&committer_time, &tm) == NULL)
5300 return got_error_from_errno("gmtime_r");
5301 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5302 &tm) == 0) {
5303 err = got_error(GOT_ERR_NO_SPACE);
5304 goto done;
5306 bline->annotated = 1;
5308 /* Print lines annotated so far. */
5309 bline = &a->lines[a->lineno_cur - 1];
5310 if (!bline->annotated)
5311 goto done;
5313 offset = a->line_offsets[a->lineno_cur - 1];
5314 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5315 err = got_error_from_errno("fseeko");
5316 goto done;
5319 while (bline->annotated) {
5320 char *smallerthan, *at, *nl, *committer;
5321 size_t len;
5323 if (getline(&line, &linesize, a->f) == -1) {
5324 if (ferror(a->f))
5325 err = got_error_from_errno("getline");
5326 break;
5329 committer = bline->committer;
5330 smallerthan = strchr(committer, '<');
5331 if (smallerthan && smallerthan[1] != '\0')
5332 committer = smallerthan + 1;
5333 at = strchr(committer, '@');
5334 if (at)
5335 *at = '\0';
5336 len = strlen(committer);
5337 if (len >= 9)
5338 committer[8] = '\0';
5340 nl = strchr(line, '\n');
5341 if (nl)
5342 *nl = '\0';
5343 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5344 bline->id_str, bline->datebuf, committer, line);
5346 a->lineno_cur++;
5347 bline = &a->lines[a->lineno_cur - 1];
5349 done:
5350 free(line);
5351 return err;
5354 static const struct got_error *
5355 cmd_blame(int argc, char *argv[])
5357 const struct got_error *error;
5358 struct got_repository *repo = NULL;
5359 struct got_worktree *worktree = NULL;
5360 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5361 char *link_target = NULL;
5362 struct got_object_id *obj_id = NULL;
5363 struct got_object_id *commit_id = NULL;
5364 struct got_commit_object *commit = NULL;
5365 struct got_blob_object *blob = NULL;
5366 char *commit_id_str = NULL;
5367 struct blame_cb_args bca;
5368 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5369 off_t filesize;
5370 int *pack_fds = NULL;
5371 FILE *f1 = NULL, *f2 = NULL;
5373 fd1 = got_opentempfd();
5374 if (fd1 == -1)
5375 return got_error_from_errno("got_opentempfd");
5377 memset(&bca, 0, sizeof(bca));
5379 #ifndef PROFILE
5380 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5381 NULL) == -1)
5382 err(1, "pledge");
5383 #endif
5385 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5386 switch (ch) {
5387 case 'c':
5388 commit_id_str = optarg;
5389 break;
5390 case 'r':
5391 repo_path = realpath(optarg, NULL);
5392 if (repo_path == NULL)
5393 return got_error_from_errno2("realpath",
5394 optarg);
5395 got_path_strip_trailing_slashes(repo_path);
5396 break;
5397 default:
5398 usage_blame();
5399 /* NOTREACHED */
5403 argc -= optind;
5404 argv += optind;
5406 if (argc == 1)
5407 path = argv[0];
5408 else
5409 usage_blame();
5411 cwd = getcwd(NULL, 0);
5412 if (cwd == NULL) {
5413 error = got_error_from_errno("getcwd");
5414 goto done;
5417 error = got_repo_pack_fds_open(&pack_fds);
5418 if (error != NULL)
5419 goto done;
5421 if (repo_path == NULL) {
5422 error = got_worktree_open(&worktree, cwd);
5423 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5424 goto done;
5425 else
5426 error = NULL;
5427 if (worktree) {
5428 repo_path =
5429 strdup(got_worktree_get_repo_path(worktree));
5430 if (repo_path == NULL) {
5431 error = got_error_from_errno("strdup");
5432 if (error)
5433 goto done;
5435 } else {
5436 repo_path = strdup(cwd);
5437 if (repo_path == NULL) {
5438 error = got_error_from_errno("strdup");
5439 goto done;
5444 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5445 if (error != NULL)
5446 goto done;
5448 if (worktree) {
5449 const char *prefix = got_worktree_get_path_prefix(worktree);
5450 char *p;
5452 error = got_worktree_resolve_path(&p, worktree, path);
5453 if (error)
5454 goto done;
5455 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5456 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5457 p) == -1) {
5458 error = got_error_from_errno("asprintf");
5459 free(p);
5460 goto done;
5462 free(p);
5463 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5464 } else {
5465 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5466 if (error)
5467 goto done;
5468 error = got_repo_map_path(&in_repo_path, repo, path);
5470 if (error)
5471 goto done;
5473 if (commit_id_str == NULL) {
5474 struct got_reference *head_ref;
5475 error = got_ref_open(&head_ref, repo, worktree ?
5476 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5477 if (error != NULL)
5478 goto done;
5479 error = got_ref_resolve(&commit_id, repo, head_ref);
5480 got_ref_close(head_ref);
5481 if (error != NULL)
5482 goto done;
5483 } else {
5484 struct got_reflist_head refs;
5485 TAILQ_INIT(&refs);
5486 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5487 NULL);
5488 if (error)
5489 goto done;
5490 error = got_repo_match_object_id(&commit_id, NULL,
5491 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5492 got_ref_list_free(&refs);
5493 if (error)
5494 goto done;
5497 if (worktree) {
5498 /* Release work tree lock. */
5499 got_worktree_close(worktree);
5500 worktree = NULL;
5503 error = got_object_open_as_commit(&commit, repo, commit_id);
5504 if (error)
5505 goto done;
5507 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5508 commit, repo);
5509 if (error)
5510 goto done;
5512 error = got_object_id_by_path(&obj_id, repo, commit,
5513 link_target ? link_target : in_repo_path);
5514 if (error)
5515 goto done;
5517 error = got_object_get_type(&obj_type, repo, obj_id);
5518 if (error)
5519 goto done;
5521 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5522 error = got_error_path(link_target ? link_target : in_repo_path,
5523 GOT_ERR_OBJ_TYPE);
5524 goto done;
5527 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5528 if (error)
5529 goto done;
5530 bca.f = got_opentemp();
5531 if (bca.f == NULL) {
5532 error = got_error_from_errno("got_opentemp");
5533 goto done;
5535 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5536 &bca.line_offsets, bca.f, blob);
5537 if (error || bca.nlines == 0)
5538 goto done;
5540 /* Don't include \n at EOF in the blame line count. */
5541 if (bca.line_offsets[bca.nlines - 1] == filesize)
5542 bca.nlines--;
5544 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5545 if (bca.lines == NULL) {
5546 error = got_error_from_errno("calloc");
5547 goto done;
5549 bca.lineno_cur = 1;
5550 bca.nlines_prec = 0;
5551 i = bca.nlines;
5552 while (i > 0) {
5553 i /= 10;
5554 bca.nlines_prec++;
5556 bca.repo = repo;
5558 fd2 = got_opentempfd();
5559 if (fd2 == -1) {
5560 error = got_error_from_errno("got_opentempfd");
5561 goto done;
5563 fd3 = got_opentempfd();
5564 if (fd3 == -1) {
5565 error = got_error_from_errno("got_opentempfd");
5566 goto done;
5568 f1 = got_opentemp();
5569 if (f1 == NULL) {
5570 error = got_error_from_errno("got_opentemp");
5571 goto done;
5573 f2 = got_opentemp();
5574 if (f2 == NULL) {
5575 error = got_error_from_errno("got_opentemp");
5576 goto done;
5578 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5579 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5580 check_cancelled, NULL, fd2, fd3, f1, f2);
5581 done:
5582 free(in_repo_path);
5583 free(link_target);
5584 free(repo_path);
5585 free(cwd);
5586 free(commit_id);
5587 free(obj_id);
5588 if (commit)
5589 got_object_commit_close(commit);
5591 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5592 error = got_error_from_errno("close");
5593 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5594 error = got_error_from_errno("close");
5595 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5596 error = got_error_from_errno("close");
5597 if (f1 && fclose(f1) == EOF && error == NULL)
5598 error = got_error_from_errno("fclose");
5599 if (f2 && fclose(f2) == EOF && error == NULL)
5600 error = got_error_from_errno("fclose");
5602 if (blob)
5603 got_object_blob_close(blob);
5604 if (worktree)
5605 got_worktree_close(worktree);
5606 if (repo) {
5607 const struct got_error *close_err = got_repo_close(repo);
5608 if (error == NULL)
5609 error = close_err;
5611 if (pack_fds) {
5612 const struct got_error *pack_err =
5613 got_repo_pack_fds_close(pack_fds);
5614 if (error == NULL)
5615 error = pack_err;
5617 if (bca.lines) {
5618 for (i = 0; i < bca.nlines; i++) {
5619 struct blame_line *bline = &bca.lines[i];
5620 free(bline->id_str);
5621 free(bline->committer);
5623 free(bca.lines);
5625 free(bca.line_offsets);
5626 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5627 error = got_error_from_errno("fclose");
5628 return error;
5631 __dead static void
5632 usage_tree(void)
5634 fprintf(stderr,
5635 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5636 getprogname());
5637 exit(1);
5640 static const struct got_error *
5641 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5642 const char *root_path, struct got_repository *repo)
5644 const struct got_error *err = NULL;
5645 int is_root_path = (strcmp(path, root_path) == 0);
5646 const char *modestr = "";
5647 mode_t mode = got_tree_entry_get_mode(te);
5648 char *link_target = NULL;
5650 path += strlen(root_path);
5651 while (path[0] == '/')
5652 path++;
5654 if (got_object_tree_entry_is_submodule(te))
5655 modestr = "$";
5656 else if (S_ISLNK(mode)) {
5657 int i;
5659 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5660 if (err)
5661 return err;
5662 for (i = 0; i < strlen(link_target); i++) {
5663 if (!isprint((unsigned char)link_target[i]))
5664 link_target[i] = '?';
5667 modestr = "@";
5669 else if (S_ISDIR(mode))
5670 modestr = "/";
5671 else if (mode & S_IXUSR)
5672 modestr = "*";
5674 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5675 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5676 link_target ? " -> ": "", link_target ? link_target : "");
5678 free(link_target);
5679 return NULL;
5682 static const struct got_error *
5683 print_tree(const char *path, struct got_commit_object *commit,
5684 int show_ids, int recurse, const char *root_path,
5685 struct got_repository *repo)
5687 const struct got_error *err = NULL;
5688 struct got_object_id *tree_id = NULL;
5689 struct got_tree_object *tree = NULL;
5690 int nentries, i;
5692 err = got_object_id_by_path(&tree_id, repo, commit, path);
5693 if (err)
5694 goto done;
5696 err = got_object_open_as_tree(&tree, repo, tree_id);
5697 if (err)
5698 goto done;
5699 nentries = got_object_tree_get_nentries(tree);
5700 for (i = 0; i < nentries; i++) {
5701 struct got_tree_entry *te;
5702 char *id = NULL;
5704 if (sigint_received || sigpipe_received)
5705 break;
5707 te = got_object_tree_get_entry(tree, i);
5708 if (show_ids) {
5709 char *id_str;
5710 err = got_object_id_str(&id_str,
5711 got_tree_entry_get_id(te));
5712 if (err)
5713 goto done;
5714 if (asprintf(&id, "%s ", id_str) == -1) {
5715 err = got_error_from_errno("asprintf");
5716 free(id_str);
5717 goto done;
5719 free(id_str);
5721 err = print_entry(te, id, path, root_path, repo);
5722 free(id);
5723 if (err)
5724 goto done;
5726 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5727 char *child_path;
5728 if (asprintf(&child_path, "%s%s%s", path,
5729 path[0] == '/' && path[1] == '\0' ? "" : "/",
5730 got_tree_entry_get_name(te)) == -1) {
5731 err = got_error_from_errno("asprintf");
5732 goto done;
5734 err = print_tree(child_path, commit, show_ids, 1,
5735 root_path, repo);
5736 free(child_path);
5737 if (err)
5738 goto done;
5741 done:
5742 if (tree)
5743 got_object_tree_close(tree);
5744 free(tree_id);
5745 return err;
5748 static const struct got_error *
5749 cmd_tree(int argc, char *argv[])
5751 const struct got_error *error;
5752 struct got_repository *repo = NULL;
5753 struct got_worktree *worktree = NULL;
5754 const char *path, *refname = NULL;
5755 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5756 struct got_object_id *commit_id = NULL;
5757 struct got_commit_object *commit = NULL;
5758 char *commit_id_str = NULL;
5759 int show_ids = 0, recurse = 0;
5760 int ch;
5761 int *pack_fds = NULL;
5763 #ifndef PROFILE
5764 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5765 NULL) == -1)
5766 err(1, "pledge");
5767 #endif
5769 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5770 switch (ch) {
5771 case 'c':
5772 commit_id_str = optarg;
5773 break;
5774 case 'r':
5775 repo_path = realpath(optarg, NULL);
5776 if (repo_path == NULL)
5777 return got_error_from_errno2("realpath",
5778 optarg);
5779 got_path_strip_trailing_slashes(repo_path);
5780 break;
5781 case 'i':
5782 show_ids = 1;
5783 break;
5784 case 'R':
5785 recurse = 1;
5786 break;
5787 default:
5788 usage_tree();
5789 /* NOTREACHED */
5793 argc -= optind;
5794 argv += optind;
5796 if (argc == 1)
5797 path = argv[0];
5798 else if (argc > 1)
5799 usage_tree();
5800 else
5801 path = NULL;
5803 cwd = getcwd(NULL, 0);
5804 if (cwd == NULL) {
5805 error = got_error_from_errno("getcwd");
5806 goto done;
5809 error = got_repo_pack_fds_open(&pack_fds);
5810 if (error != NULL)
5811 goto done;
5813 if (repo_path == NULL) {
5814 error = got_worktree_open(&worktree, cwd);
5815 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5816 goto done;
5817 else
5818 error = NULL;
5819 if (worktree) {
5820 repo_path =
5821 strdup(got_worktree_get_repo_path(worktree));
5822 if (repo_path == NULL)
5823 error = got_error_from_errno("strdup");
5824 if (error)
5825 goto done;
5826 } else {
5827 repo_path = strdup(cwd);
5828 if (repo_path == NULL) {
5829 error = got_error_from_errno("strdup");
5830 goto done;
5835 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5836 if (error != NULL)
5837 goto done;
5839 if (worktree) {
5840 const char *prefix = got_worktree_get_path_prefix(worktree);
5841 char *p;
5843 if (path == NULL)
5844 path = "";
5845 error = got_worktree_resolve_path(&p, worktree, path);
5846 if (error)
5847 goto done;
5848 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5849 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5850 p) == -1) {
5851 error = got_error_from_errno("asprintf");
5852 free(p);
5853 goto done;
5855 free(p);
5856 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5857 if (error)
5858 goto done;
5859 } else {
5860 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5861 if (error)
5862 goto done;
5863 if (path == NULL)
5864 path = "/";
5865 error = got_repo_map_path(&in_repo_path, repo, path);
5866 if (error != NULL)
5867 goto done;
5870 if (commit_id_str == NULL) {
5871 struct got_reference *head_ref;
5872 if (worktree)
5873 refname = got_worktree_get_head_ref_name(worktree);
5874 else
5875 refname = GOT_REF_HEAD;
5876 error = got_ref_open(&head_ref, repo, refname, 0);
5877 if (error != NULL)
5878 goto done;
5879 error = got_ref_resolve(&commit_id, repo, head_ref);
5880 got_ref_close(head_ref);
5881 if (error != NULL)
5882 goto done;
5883 } else {
5884 struct got_reflist_head refs;
5885 TAILQ_INIT(&refs);
5886 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5887 NULL);
5888 if (error)
5889 goto done;
5890 error = got_repo_match_object_id(&commit_id, NULL,
5891 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5892 got_ref_list_free(&refs);
5893 if (error)
5894 goto done;
5897 if (worktree) {
5898 /* Release work tree lock. */
5899 got_worktree_close(worktree);
5900 worktree = NULL;
5903 error = got_object_open_as_commit(&commit, repo, commit_id);
5904 if (error)
5905 goto done;
5907 error = print_tree(in_repo_path, commit, show_ids, recurse,
5908 in_repo_path, repo);
5909 done:
5910 free(in_repo_path);
5911 free(repo_path);
5912 free(cwd);
5913 free(commit_id);
5914 if (commit)
5915 got_object_commit_close(commit);
5916 if (worktree)
5917 got_worktree_close(worktree);
5918 if (repo) {
5919 const struct got_error *close_err = got_repo_close(repo);
5920 if (error == NULL)
5921 error = close_err;
5923 if (pack_fds) {
5924 const struct got_error *pack_err =
5925 got_repo_pack_fds_close(pack_fds);
5926 if (error == NULL)
5927 error = pack_err;
5929 return error;
5932 __dead static void
5933 usage_status(void)
5935 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5936 "[-S status-codes] [path ...]\n", getprogname());
5937 exit(1);
5940 struct got_status_arg {
5941 char *status_codes;
5942 int suppress;
5945 static const struct got_error *
5946 print_status(void *arg, unsigned char status, unsigned char staged_status,
5947 const char *path, struct got_object_id *blob_id,
5948 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5949 int dirfd, const char *de_name)
5951 struct got_status_arg *st = arg;
5953 if (status == staged_status && (status == GOT_STATUS_DELETE))
5954 status = GOT_STATUS_NO_CHANGE;
5955 if (st != NULL && st->status_codes) {
5956 size_t ncodes = strlen(st->status_codes);
5957 int i, j = 0;
5959 for (i = 0; i < ncodes ; i++) {
5960 if (st->suppress) {
5961 if (status == st->status_codes[i] ||
5962 staged_status == st->status_codes[i]) {
5963 j++;
5964 continue;
5966 } else {
5967 if (status == st->status_codes[i] ||
5968 staged_status == st->status_codes[i])
5969 break;
5973 if (st->suppress && j == 0)
5974 goto print;
5976 if (i == ncodes)
5977 return NULL;
5979 print:
5980 printf("%c%c %s\n", status, staged_status, path);
5981 return NULL;
5984 static const struct got_error *
5985 cmd_status(int argc, char *argv[])
5987 const struct got_error *error = NULL;
5988 struct got_repository *repo = NULL;
5989 struct got_worktree *worktree = NULL;
5990 struct got_status_arg st;
5991 char *cwd = NULL;
5992 struct got_pathlist_head paths;
5993 struct got_pathlist_entry *pe;
5994 int ch, i, no_ignores = 0;
5995 int *pack_fds = NULL;
5997 TAILQ_INIT(&paths);
5999 memset(&st, 0, sizeof(st));
6000 st.status_codes = NULL;
6001 st.suppress = 0;
6003 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6004 switch (ch) {
6005 case 'I':
6006 no_ignores = 1;
6007 break;
6008 case 'S':
6009 if (st.status_codes != NULL && st.suppress == 0)
6010 option_conflict('S', 's');
6011 st.suppress = 1;
6012 /* fallthrough */
6013 case 's':
6014 for (i = 0; i < strlen(optarg); i++) {
6015 switch (optarg[i]) {
6016 case GOT_STATUS_MODIFY:
6017 case GOT_STATUS_ADD:
6018 case GOT_STATUS_DELETE:
6019 case GOT_STATUS_CONFLICT:
6020 case GOT_STATUS_MISSING:
6021 case GOT_STATUS_OBSTRUCTED:
6022 case GOT_STATUS_UNVERSIONED:
6023 case GOT_STATUS_MODE_CHANGE:
6024 case GOT_STATUS_NONEXISTENT:
6025 break;
6026 default:
6027 errx(1, "invalid status code '%c'",
6028 optarg[i]);
6031 if (ch == 's' && st.suppress)
6032 option_conflict('s', 'S');
6033 st.status_codes = optarg;
6034 break;
6035 default:
6036 usage_status();
6037 /* NOTREACHED */
6041 argc -= optind;
6042 argv += optind;
6044 #ifndef PROFILE
6045 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6046 NULL) == -1)
6047 err(1, "pledge");
6048 #endif
6049 cwd = getcwd(NULL, 0);
6050 if (cwd == NULL) {
6051 error = got_error_from_errno("getcwd");
6052 goto done;
6055 error = got_repo_pack_fds_open(&pack_fds);
6056 if (error != NULL)
6057 goto done;
6059 error = got_worktree_open(&worktree, cwd);
6060 if (error) {
6061 if (error->code == GOT_ERR_NOT_WORKTREE)
6062 error = wrap_not_worktree_error(error, "status", cwd);
6063 goto done;
6066 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6067 NULL, pack_fds);
6068 if (error != NULL)
6069 goto done;
6071 error = apply_unveil(got_repo_get_path(repo), 1,
6072 got_worktree_get_root_path(worktree));
6073 if (error)
6074 goto done;
6076 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6077 if (error)
6078 goto done;
6080 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6081 print_status, &st, check_cancelled, NULL);
6082 done:
6083 if (pack_fds) {
6084 const struct got_error *pack_err =
6085 got_repo_pack_fds_close(pack_fds);
6086 if (error == NULL)
6087 error = pack_err;
6090 TAILQ_FOREACH(pe, &paths, entry)
6091 free((char *)pe->path);
6092 got_pathlist_free(&paths);
6093 free(cwd);
6094 return error;
6097 __dead static void
6098 usage_ref(void)
6100 fprintf(stderr,
6101 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6102 "[-s reference] [-d] [name]\n",
6103 getprogname());
6104 exit(1);
6107 static const struct got_error *
6108 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6110 static const struct got_error *err = NULL;
6111 struct got_reflist_head refs;
6112 struct got_reflist_entry *re;
6114 TAILQ_INIT(&refs);
6115 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6116 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6117 repo);
6118 if (err)
6119 return err;
6121 TAILQ_FOREACH(re, &refs, entry) {
6122 char *refstr;
6123 refstr = got_ref_to_str(re->ref);
6124 if (refstr == NULL) {
6125 err = got_error_from_errno("got_ref_to_str");
6126 break;
6128 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6129 free(refstr);
6132 got_ref_list_free(&refs);
6133 return err;
6136 static const struct got_error *
6137 delete_ref_by_name(struct got_repository *repo, const char *refname)
6139 const struct got_error *err;
6140 struct got_reference *ref;
6142 err = got_ref_open(&ref, repo, refname, 0);
6143 if (err)
6144 return err;
6146 err = delete_ref(repo, ref);
6147 got_ref_close(ref);
6148 return err;
6151 static const struct got_error *
6152 add_ref(struct got_repository *repo, const char *refname, const char *target)
6154 const struct got_error *err = NULL;
6155 struct got_object_id *id = NULL;
6156 struct got_reference *ref = NULL;
6157 struct got_reflist_head refs;
6160 * Don't let the user create a reference name with a leading '-'.
6161 * While technically a valid reference name, this case is usually
6162 * an unintended typo.
6164 if (refname[0] == '-')
6165 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6167 TAILQ_INIT(&refs);
6168 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6169 if (err)
6170 goto done;
6171 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6172 &refs, repo);
6173 got_ref_list_free(&refs);
6174 if (err)
6175 goto done;
6177 err = got_ref_alloc(&ref, refname, id);
6178 if (err)
6179 goto done;
6181 err = got_ref_write(ref, repo);
6182 done:
6183 if (ref)
6184 got_ref_close(ref);
6185 free(id);
6186 return err;
6189 static const struct got_error *
6190 add_symref(struct got_repository *repo, const char *refname, const char *target)
6192 const struct got_error *err = NULL;
6193 struct got_reference *ref = NULL;
6194 struct got_reference *target_ref = NULL;
6197 * Don't let the user create a reference name with a leading '-'.
6198 * While technically a valid reference name, this case is usually
6199 * an unintended typo.
6201 if (refname[0] == '-')
6202 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6204 err = got_ref_open(&target_ref, repo, target, 0);
6205 if (err)
6206 return err;
6208 err = got_ref_alloc_symref(&ref, refname, target_ref);
6209 if (err)
6210 goto done;
6212 err = got_ref_write(ref, repo);
6213 done:
6214 if (target_ref)
6215 got_ref_close(target_ref);
6216 if (ref)
6217 got_ref_close(ref);
6218 return err;
6221 static const struct got_error *
6222 cmd_ref(int argc, char *argv[])
6224 const struct got_error *error = NULL;
6225 struct got_repository *repo = NULL;
6226 struct got_worktree *worktree = NULL;
6227 char *cwd = NULL, *repo_path = NULL;
6228 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6229 const char *obj_arg = NULL, *symref_target= NULL;
6230 char *refname = NULL;
6231 int *pack_fds = NULL;
6233 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6234 switch (ch) {
6235 case 'c':
6236 obj_arg = optarg;
6237 break;
6238 case 'd':
6239 do_delete = 1;
6240 break;
6241 case 'r':
6242 repo_path = realpath(optarg, NULL);
6243 if (repo_path == NULL)
6244 return got_error_from_errno2("realpath",
6245 optarg);
6246 got_path_strip_trailing_slashes(repo_path);
6247 break;
6248 case 'l':
6249 do_list = 1;
6250 break;
6251 case 's':
6252 symref_target = optarg;
6253 break;
6254 case 't':
6255 sort_by_time = 1;
6256 break;
6257 default:
6258 usage_ref();
6259 /* NOTREACHED */
6263 if (obj_arg && do_list)
6264 option_conflict('c', 'l');
6265 if (obj_arg && do_delete)
6266 option_conflict('c', 'd');
6267 if (obj_arg && symref_target)
6268 option_conflict('c', 's');
6269 if (symref_target && do_delete)
6270 option_conflict('s', 'd');
6271 if (symref_target && do_list)
6272 option_conflict('s', 'l');
6273 if (do_delete && do_list)
6274 option_conflict('d', 'l');
6275 if (sort_by_time && !do_list)
6276 errx(1, "-t option requires -l option");
6278 argc -= optind;
6279 argv += optind;
6281 if (do_list) {
6282 if (argc != 0 && argc != 1)
6283 usage_ref();
6284 if (argc == 1) {
6285 refname = strdup(argv[0]);
6286 if (refname == NULL) {
6287 error = got_error_from_errno("strdup");
6288 goto done;
6291 } else {
6292 if (argc != 1)
6293 usage_ref();
6294 refname = strdup(argv[0]);
6295 if (refname == NULL) {
6296 error = got_error_from_errno("strdup");
6297 goto done;
6301 if (refname)
6302 got_path_strip_trailing_slashes(refname);
6304 #ifndef PROFILE
6305 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6306 "sendfd unveil", NULL) == -1)
6307 err(1, "pledge");
6308 #endif
6309 cwd = getcwd(NULL, 0);
6310 if (cwd == NULL) {
6311 error = got_error_from_errno("getcwd");
6312 goto done;
6315 error = got_repo_pack_fds_open(&pack_fds);
6316 if (error != NULL)
6317 goto done;
6319 if (repo_path == NULL) {
6320 error = got_worktree_open(&worktree, cwd);
6321 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6322 goto done;
6323 else
6324 error = NULL;
6325 if (worktree) {
6326 repo_path =
6327 strdup(got_worktree_get_repo_path(worktree));
6328 if (repo_path == NULL)
6329 error = got_error_from_errno("strdup");
6330 if (error)
6331 goto done;
6332 } else {
6333 repo_path = strdup(cwd);
6334 if (repo_path == NULL) {
6335 error = got_error_from_errno("strdup");
6336 goto done;
6341 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6342 if (error != NULL)
6343 goto done;
6345 #ifndef PROFILE
6346 if (do_list) {
6347 /* Remove "cpath" promise. */
6348 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6349 NULL) == -1)
6350 err(1, "pledge");
6352 #endif
6354 error = apply_unveil(got_repo_get_path(repo), do_list,
6355 worktree ? got_worktree_get_root_path(worktree) : NULL);
6356 if (error)
6357 goto done;
6359 if (do_list)
6360 error = list_refs(repo, refname, sort_by_time);
6361 else if (do_delete)
6362 error = delete_ref_by_name(repo, refname);
6363 else if (symref_target)
6364 error = add_symref(repo, refname, symref_target);
6365 else {
6366 if (obj_arg == NULL)
6367 usage_ref();
6368 error = add_ref(repo, refname, obj_arg);
6370 done:
6371 free(refname);
6372 if (repo) {
6373 const struct got_error *close_err = got_repo_close(repo);
6374 if (error == NULL)
6375 error = close_err;
6377 if (worktree)
6378 got_worktree_close(worktree);
6379 if (pack_fds) {
6380 const struct got_error *pack_err =
6381 got_repo_pack_fds_close(pack_fds);
6382 if (error == NULL)
6383 error = pack_err;
6385 free(cwd);
6386 free(repo_path);
6387 return error;
6390 __dead static void
6391 usage_branch(void)
6393 fprintf(stderr,
6394 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6395 "[-n] [name]\n", getprogname());
6396 exit(1);
6399 static const struct got_error *
6400 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6401 struct got_reference *ref)
6403 const struct got_error *err = NULL;
6404 const char *refname, *marker = " ";
6405 char *refstr;
6407 refname = got_ref_get_name(ref);
6408 if (worktree && strcmp(refname,
6409 got_worktree_get_head_ref_name(worktree)) == 0) {
6410 struct got_object_id *id = NULL;
6412 err = got_ref_resolve(&id, repo, ref);
6413 if (err)
6414 return err;
6415 if (got_object_id_cmp(id,
6416 got_worktree_get_base_commit_id(worktree)) == 0)
6417 marker = "* ";
6418 else
6419 marker = "~ ";
6420 free(id);
6423 if (strncmp(refname, "refs/heads/", 11) == 0)
6424 refname += 11;
6425 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6426 refname += 18;
6427 if (strncmp(refname, "refs/remotes/", 13) == 0)
6428 refname += 13;
6430 refstr = got_ref_to_str(ref);
6431 if (refstr == NULL)
6432 return got_error_from_errno("got_ref_to_str");
6434 printf("%s%s: %s\n", marker, refname, refstr);
6435 free(refstr);
6436 return NULL;
6439 static const struct got_error *
6440 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6442 const char *refname;
6444 if (worktree == NULL)
6445 return got_error(GOT_ERR_NOT_WORKTREE);
6447 refname = got_worktree_get_head_ref_name(worktree);
6449 if (strncmp(refname, "refs/heads/", 11) == 0)
6450 refname += 11;
6451 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6452 refname += 18;
6454 printf("%s\n", refname);
6456 return NULL;
6459 static const struct got_error *
6460 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6461 int sort_by_time)
6463 static const struct got_error *err = NULL;
6464 struct got_reflist_head refs;
6465 struct got_reflist_entry *re;
6466 struct got_reference *temp_ref = NULL;
6467 int rebase_in_progress, histedit_in_progress;
6469 TAILQ_INIT(&refs);
6471 if (worktree) {
6472 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6473 worktree);
6474 if (err)
6475 return err;
6477 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6478 worktree);
6479 if (err)
6480 return err;
6482 if (rebase_in_progress || histedit_in_progress) {
6483 err = got_ref_open(&temp_ref, repo,
6484 got_worktree_get_head_ref_name(worktree), 0);
6485 if (err)
6486 return err;
6487 list_branch(repo, worktree, temp_ref);
6488 got_ref_close(temp_ref);
6492 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6493 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6494 repo);
6495 if (err)
6496 return err;
6498 TAILQ_FOREACH(re, &refs, entry)
6499 list_branch(repo, worktree, re->ref);
6501 got_ref_list_free(&refs);
6503 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6504 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6505 repo);
6506 if (err)
6507 return err;
6509 TAILQ_FOREACH(re, &refs, entry)
6510 list_branch(repo, worktree, re->ref);
6512 got_ref_list_free(&refs);
6514 return NULL;
6517 static const struct got_error *
6518 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6519 const char *branch_name)
6521 const struct got_error *err = NULL;
6522 struct got_reference *ref = NULL;
6523 char *refname, *remote_refname = NULL;
6525 if (strncmp(branch_name, "refs/", 5) == 0)
6526 branch_name += 5;
6527 if (strncmp(branch_name, "heads/", 6) == 0)
6528 branch_name += 6;
6529 else if (strncmp(branch_name, "remotes/", 8) == 0)
6530 branch_name += 8;
6532 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6533 return got_error_from_errno("asprintf");
6535 if (asprintf(&remote_refname, "refs/remotes/%s",
6536 branch_name) == -1) {
6537 err = got_error_from_errno("asprintf");
6538 goto done;
6541 err = got_ref_open(&ref, repo, refname, 0);
6542 if (err) {
6543 const struct got_error *err2;
6544 if (err->code != GOT_ERR_NOT_REF)
6545 goto done;
6547 * Keep 'err' intact such that if neither branch exists
6548 * we report "refs/heads" rather than "refs/remotes" in
6549 * our error message.
6551 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6552 if (err2)
6553 goto done;
6554 err = NULL;
6557 if (worktree &&
6558 strcmp(got_worktree_get_head_ref_name(worktree),
6559 got_ref_get_name(ref)) == 0) {
6560 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6561 "will not delete this work tree's current branch");
6562 goto done;
6565 err = delete_ref(repo, ref);
6566 done:
6567 if (ref)
6568 got_ref_close(ref);
6569 free(refname);
6570 free(remote_refname);
6571 return err;
6574 static const struct got_error *
6575 add_branch(struct got_repository *repo, const char *branch_name,
6576 struct got_object_id *base_commit_id)
6578 const struct got_error *err = NULL;
6579 struct got_reference *ref = NULL;
6580 char *base_refname = NULL, *refname = NULL;
6583 * Don't let the user create a branch name with a leading '-'.
6584 * While technically a valid reference name, this case is usually
6585 * an unintended typo.
6587 if (branch_name[0] == '-')
6588 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6590 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6591 branch_name += 11;
6593 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6594 err = got_error_from_errno("asprintf");
6595 goto done;
6598 err = got_ref_open(&ref, repo, refname, 0);
6599 if (err == NULL) {
6600 err = got_error(GOT_ERR_BRANCH_EXISTS);
6601 goto done;
6602 } else if (err->code != GOT_ERR_NOT_REF)
6603 goto done;
6605 err = got_ref_alloc(&ref, refname, base_commit_id);
6606 if (err)
6607 goto done;
6609 err = got_ref_write(ref, repo);
6610 done:
6611 if (ref)
6612 got_ref_close(ref);
6613 free(base_refname);
6614 free(refname);
6615 return err;
6618 static const struct got_error *
6619 cmd_branch(int argc, char *argv[])
6621 const struct got_error *error = NULL;
6622 struct got_repository *repo = NULL;
6623 struct got_worktree *worktree = NULL;
6624 char *cwd = NULL, *repo_path = NULL;
6625 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6626 const char *delref = NULL, *commit_id_arg = NULL;
6627 struct got_reference *ref = NULL;
6628 struct got_pathlist_head paths;
6629 struct got_pathlist_entry *pe;
6630 struct got_object_id *commit_id = NULL;
6631 char *commit_id_str = NULL;
6632 int *pack_fds = NULL;
6634 TAILQ_INIT(&paths);
6636 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6637 switch (ch) {
6638 case 'c':
6639 commit_id_arg = optarg;
6640 break;
6641 case 'd':
6642 delref = optarg;
6643 break;
6644 case 'r':
6645 repo_path = realpath(optarg, NULL);
6646 if (repo_path == NULL)
6647 return got_error_from_errno2("realpath",
6648 optarg);
6649 got_path_strip_trailing_slashes(repo_path);
6650 break;
6651 case 'l':
6652 do_list = 1;
6653 break;
6654 case 'n':
6655 do_update = 0;
6656 break;
6657 case 't':
6658 sort_by_time = 1;
6659 break;
6660 default:
6661 usage_branch();
6662 /* NOTREACHED */
6666 if (do_list && delref)
6667 option_conflict('l', 'd');
6668 if (sort_by_time && !do_list)
6669 errx(1, "-t option requires -l option");
6671 argc -= optind;
6672 argv += optind;
6674 if (!do_list && !delref && argc == 0)
6675 do_show = 1;
6677 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6678 errx(1, "-c option can only be used when creating a branch");
6680 if (do_list || delref) {
6681 if (argc > 0)
6682 usage_branch();
6683 } else if (!do_show && argc != 1)
6684 usage_branch();
6686 #ifndef PROFILE
6687 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6688 "sendfd unveil", NULL) == -1)
6689 err(1, "pledge");
6690 #endif
6691 cwd = getcwd(NULL, 0);
6692 if (cwd == NULL) {
6693 error = got_error_from_errno("getcwd");
6694 goto done;
6697 error = got_repo_pack_fds_open(&pack_fds);
6698 if (error != NULL)
6699 goto done;
6701 if (repo_path == NULL) {
6702 error = got_worktree_open(&worktree, cwd);
6703 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6704 goto done;
6705 else
6706 error = NULL;
6707 if (worktree) {
6708 repo_path =
6709 strdup(got_worktree_get_repo_path(worktree));
6710 if (repo_path == NULL)
6711 error = got_error_from_errno("strdup");
6712 if (error)
6713 goto done;
6714 } else {
6715 repo_path = strdup(cwd);
6716 if (repo_path == NULL) {
6717 error = got_error_from_errno("strdup");
6718 goto done;
6723 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6724 if (error != NULL)
6725 goto done;
6727 #ifndef PROFILE
6728 if (do_list || do_show) {
6729 /* Remove "cpath" promise. */
6730 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6731 NULL) == -1)
6732 err(1, "pledge");
6734 #endif
6736 error = apply_unveil(got_repo_get_path(repo), do_list,
6737 worktree ? got_worktree_get_root_path(worktree) : NULL);
6738 if (error)
6739 goto done;
6741 if (do_show)
6742 error = show_current_branch(repo, worktree);
6743 else if (do_list)
6744 error = list_branches(repo, worktree, sort_by_time);
6745 else if (delref)
6746 error = delete_branch(repo, worktree, delref);
6747 else {
6748 struct got_reflist_head refs;
6749 TAILQ_INIT(&refs);
6750 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6751 NULL);
6752 if (error)
6753 goto done;
6754 if (commit_id_arg == NULL)
6755 commit_id_arg = worktree ?
6756 got_worktree_get_head_ref_name(worktree) :
6757 GOT_REF_HEAD;
6758 error = got_repo_match_object_id(&commit_id, NULL,
6759 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6760 got_ref_list_free(&refs);
6761 if (error)
6762 goto done;
6763 error = add_branch(repo, argv[0], commit_id);
6764 if (error)
6765 goto done;
6766 if (worktree && do_update) {
6767 struct got_update_progress_arg upa;
6768 char *branch_refname = NULL;
6770 error = got_object_id_str(&commit_id_str, commit_id);
6771 if (error)
6772 goto done;
6773 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6774 worktree);
6775 if (error)
6776 goto done;
6777 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6778 == -1) {
6779 error = got_error_from_errno("asprintf");
6780 goto done;
6782 error = got_ref_open(&ref, repo, branch_refname, 0);
6783 free(branch_refname);
6784 if (error)
6785 goto done;
6786 error = switch_head_ref(ref, commit_id, worktree,
6787 repo);
6788 if (error)
6789 goto done;
6790 error = got_worktree_set_base_commit_id(worktree, repo,
6791 commit_id);
6792 if (error)
6793 goto done;
6794 memset(&upa, 0, sizeof(upa));
6795 error = got_worktree_checkout_files(worktree, &paths,
6796 repo, update_progress, &upa, check_cancelled,
6797 NULL);
6798 if (error)
6799 goto done;
6800 if (upa.did_something) {
6801 printf("Updated to %s: %s\n",
6802 got_worktree_get_head_ref_name(worktree),
6803 commit_id_str);
6805 print_update_progress_stats(&upa);
6808 done:
6809 if (ref)
6810 got_ref_close(ref);
6811 if (repo) {
6812 const struct got_error *close_err = got_repo_close(repo);
6813 if (error == NULL)
6814 error = close_err;
6816 if (worktree)
6817 got_worktree_close(worktree);
6818 if (pack_fds) {
6819 const struct got_error *pack_err =
6820 got_repo_pack_fds_close(pack_fds);
6821 if (error == NULL)
6822 error = pack_err;
6824 free(cwd);
6825 free(repo_path);
6826 free(commit_id);
6827 free(commit_id_str);
6828 TAILQ_FOREACH(pe, &paths, entry)
6829 free((char *)pe->path);
6830 got_pathlist_free(&paths);
6831 return error;
6835 __dead static void
6836 usage_tag(void)
6838 fprintf(stderr,
6839 "usage: %s tag [-c commit] [-r repository] [-l] "
6840 "[-m message] name\n", getprogname());
6841 exit(1);
6844 #if 0
6845 static const struct got_error *
6846 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6848 const struct got_error *err = NULL;
6849 struct got_reflist_entry *re, *se, *new;
6850 struct got_object_id *re_id, *se_id;
6851 struct got_tag_object *re_tag, *se_tag;
6852 time_t re_time, se_time;
6854 STAILQ_FOREACH(re, tags, entry) {
6855 se = STAILQ_FIRST(sorted);
6856 if (se == NULL) {
6857 err = got_reflist_entry_dup(&new, re);
6858 if (err)
6859 return err;
6860 STAILQ_INSERT_HEAD(sorted, new, entry);
6861 continue;
6862 } else {
6863 err = got_ref_resolve(&re_id, repo, re->ref);
6864 if (err)
6865 break;
6866 err = got_object_open_as_tag(&re_tag, repo, re_id);
6867 free(re_id);
6868 if (err)
6869 break;
6870 re_time = got_object_tag_get_tagger_time(re_tag);
6871 got_object_tag_close(re_tag);
6874 while (se) {
6875 err = got_ref_resolve(&se_id, repo, re->ref);
6876 if (err)
6877 break;
6878 err = got_object_open_as_tag(&se_tag, repo, se_id);
6879 free(se_id);
6880 if (err)
6881 break;
6882 se_time = got_object_tag_get_tagger_time(se_tag);
6883 got_object_tag_close(se_tag);
6885 if (se_time > re_time) {
6886 err = got_reflist_entry_dup(&new, re);
6887 if (err)
6888 return err;
6889 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6890 break;
6892 se = STAILQ_NEXT(se, entry);
6893 continue;
6896 done:
6897 return err;
6899 #endif
6901 static const struct got_error *
6902 get_tag_refname(char **refname, const char *tag_name)
6904 const struct got_error *err;
6906 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6907 *refname = strdup(tag_name);
6908 if (*refname == NULL)
6909 return got_error_from_errno("strdup");
6910 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6911 err = got_error_from_errno("asprintf");
6912 *refname = NULL;
6913 return err;
6916 return NULL;
6919 static const struct got_error *
6920 list_tags(struct got_repository *repo, const char *tag_name)
6922 static const struct got_error *err = NULL;
6923 struct got_reflist_head refs;
6924 struct got_reflist_entry *re;
6925 char *wanted_refname = NULL;
6927 TAILQ_INIT(&refs);
6929 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6930 if (err)
6931 return err;
6933 if (tag_name) {
6934 struct got_reference *ref;
6935 err = get_tag_refname(&wanted_refname, tag_name);
6936 if (err)
6937 goto done;
6938 /* Wanted tag reference should exist. */
6939 err = got_ref_open(&ref, repo, wanted_refname, 0);
6940 if (err)
6941 goto done;
6942 got_ref_close(ref);
6945 TAILQ_FOREACH(re, &refs, entry) {
6946 const char *refname;
6947 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6948 char datebuf[26];
6949 const char *tagger;
6950 time_t tagger_time;
6951 struct got_object_id *id;
6952 struct got_tag_object *tag;
6953 struct got_commit_object *commit = NULL;
6955 refname = got_ref_get_name(re->ref);
6956 if (strncmp(refname, "refs/tags/", 10) != 0 ||
6957 (wanted_refname && strcmp(refname, wanted_refname) != 0))
6958 continue;
6959 refname += 10;
6960 refstr = got_ref_to_str(re->ref);
6961 if (refstr == NULL) {
6962 err = got_error_from_errno("got_ref_to_str");
6963 break;
6965 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6966 free(refstr);
6968 err = got_ref_resolve(&id, repo, re->ref);
6969 if (err)
6970 break;
6971 err = got_object_open_as_tag(&tag, repo, id);
6972 if (err) {
6973 if (err->code != GOT_ERR_OBJ_TYPE) {
6974 free(id);
6975 break;
6977 /* "lightweight" tag */
6978 err = got_object_open_as_commit(&commit, repo, id);
6979 if (err) {
6980 free(id);
6981 break;
6983 tagger = got_object_commit_get_committer(commit);
6984 tagger_time =
6985 got_object_commit_get_committer_time(commit);
6986 err = got_object_id_str(&id_str, id);
6987 free(id);
6988 if (err)
6989 break;
6990 } else {
6991 free(id);
6992 tagger = got_object_tag_get_tagger(tag);
6993 tagger_time = got_object_tag_get_tagger_time(tag);
6994 err = got_object_id_str(&id_str,
6995 got_object_tag_get_object_id(tag));
6996 if (err)
6997 break;
6999 printf("from: %s\n", tagger);
7000 datestr = get_datestr(&tagger_time, datebuf);
7001 if (datestr)
7002 printf("date: %s UTC\n", datestr);
7003 if (commit)
7004 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7005 else {
7006 switch (got_object_tag_get_object_type(tag)) {
7007 case GOT_OBJ_TYPE_BLOB:
7008 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7009 id_str);
7010 break;
7011 case GOT_OBJ_TYPE_TREE:
7012 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7013 id_str);
7014 break;
7015 case GOT_OBJ_TYPE_COMMIT:
7016 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7017 id_str);
7018 break;
7019 case GOT_OBJ_TYPE_TAG:
7020 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7021 id_str);
7022 break;
7023 default:
7024 break;
7027 free(id_str);
7028 if (commit) {
7029 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7030 if (err)
7031 break;
7032 got_object_commit_close(commit);
7033 } else {
7034 tagmsg0 = strdup(got_object_tag_get_message(tag));
7035 got_object_tag_close(tag);
7036 if (tagmsg0 == NULL) {
7037 err = got_error_from_errno("strdup");
7038 break;
7042 tagmsg = tagmsg0;
7043 do {
7044 line = strsep(&tagmsg, "\n");
7045 if (line)
7046 printf(" %s\n", line);
7047 } while (line);
7048 free(tagmsg0);
7050 done:
7051 got_ref_list_free(&refs);
7052 free(wanted_refname);
7053 return err;
7056 static const struct got_error *
7057 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7058 const char *tag_name, const char *repo_path)
7060 const struct got_error *err = NULL;
7061 char *template = NULL, *initial_content = NULL;
7062 char *editor = NULL;
7063 int initial_content_len;
7064 int fd = -1;
7066 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7067 err = got_error_from_errno("asprintf");
7068 goto done;
7071 initial_content_len = asprintf(&initial_content,
7072 "\n# tagging commit %s as %s\n",
7073 commit_id_str, tag_name);
7074 if (initial_content_len == -1) {
7075 err = got_error_from_errno("asprintf");
7076 goto done;
7079 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7080 if (err)
7081 goto done;
7083 if (write(fd, initial_content, initial_content_len) == -1) {
7084 err = got_error_from_errno2("write", *tagmsg_path);
7085 goto done;
7088 err = get_editor(&editor);
7089 if (err)
7090 goto done;
7091 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7092 initial_content_len, 1);
7093 done:
7094 free(initial_content);
7095 free(template);
7096 free(editor);
7098 if (fd != -1 && close(fd) == -1 && err == NULL)
7099 err = got_error_from_errno2("close", *tagmsg_path);
7101 /* Editor is done; we can now apply unveil(2) */
7102 if (err == NULL)
7103 err = apply_unveil(repo_path, 0, NULL);
7104 if (err) {
7105 free(*tagmsg);
7106 *tagmsg = NULL;
7108 return err;
7111 static const struct got_error *
7112 add_tag(struct got_repository *repo, const char *tagger,
7113 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
7115 const struct got_error *err = NULL;
7116 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7117 char *label = NULL, *commit_id_str = NULL;
7118 struct got_reference *ref = NULL;
7119 char *refname = NULL, *tagmsg = NULL;
7120 char *tagmsg_path = NULL, *tag_id_str = NULL;
7121 int preserve_tagmsg = 0;
7122 struct got_reflist_head refs;
7124 TAILQ_INIT(&refs);
7127 * Don't let the user create a tag name with a leading '-'.
7128 * While technically a valid reference name, this case is usually
7129 * an unintended typo.
7131 if (tag_name[0] == '-')
7132 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7134 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7135 if (err)
7136 goto done;
7138 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7139 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7140 if (err)
7141 goto done;
7143 err = got_object_id_str(&commit_id_str, commit_id);
7144 if (err)
7145 goto done;
7147 err = get_tag_refname(&refname, tag_name);
7148 if (err)
7149 goto done;
7150 if (strncmp("refs/tags/", tag_name, 10) == 0)
7151 tag_name += 10;
7153 err = got_ref_open(&ref, repo, refname, 0);
7154 if (err == NULL) {
7155 err = got_error(GOT_ERR_TAG_EXISTS);
7156 goto done;
7157 } else if (err->code != GOT_ERR_NOT_REF)
7158 goto done;
7160 if (tagmsg_arg == NULL) {
7161 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7162 tag_name, got_repo_get_path(repo));
7163 if (err) {
7164 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7165 tagmsg_path != NULL)
7166 preserve_tagmsg = 1;
7167 goto done;
7171 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7172 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7173 if (err) {
7174 if (tagmsg_path)
7175 preserve_tagmsg = 1;
7176 goto done;
7179 err = got_ref_alloc(&ref, refname, tag_id);
7180 if (err) {
7181 if (tagmsg_path)
7182 preserve_tagmsg = 1;
7183 goto done;
7186 err = got_ref_write(ref, repo);
7187 if (err) {
7188 if (tagmsg_path)
7189 preserve_tagmsg = 1;
7190 goto done;
7193 err = got_object_id_str(&tag_id_str, tag_id);
7194 if (err) {
7195 if (tagmsg_path)
7196 preserve_tagmsg = 1;
7197 goto done;
7199 printf("Created tag %s\n", tag_id_str);
7200 done:
7201 if (preserve_tagmsg) {
7202 fprintf(stderr, "%s: tag message preserved in %s\n",
7203 getprogname(), tagmsg_path);
7204 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7205 err = got_error_from_errno2("unlink", tagmsg_path);
7206 free(tag_id_str);
7207 if (ref)
7208 got_ref_close(ref);
7209 free(commit_id);
7210 free(commit_id_str);
7211 free(refname);
7212 free(tagmsg);
7213 free(tagmsg_path);
7214 got_ref_list_free(&refs);
7215 return err;
7218 static const struct got_error *
7219 cmd_tag(int argc, char *argv[])
7221 const struct got_error *error = NULL;
7222 struct got_repository *repo = NULL;
7223 struct got_worktree *worktree = NULL;
7224 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7225 char *gitconfig_path = NULL, *tagger = NULL;
7226 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7227 int ch, do_list = 0;
7228 int *pack_fds = NULL;
7230 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7231 switch (ch) {
7232 case 'c':
7233 commit_id_arg = optarg;
7234 break;
7235 case 'm':
7236 tagmsg = optarg;
7237 break;
7238 case 'r':
7239 repo_path = realpath(optarg, NULL);
7240 if (repo_path == NULL)
7241 return got_error_from_errno2("realpath",
7242 optarg);
7243 got_path_strip_trailing_slashes(repo_path);
7244 break;
7245 case 'l':
7246 do_list = 1;
7247 break;
7248 default:
7249 usage_tag();
7250 /* NOTREACHED */
7254 argc -= optind;
7255 argv += optind;
7257 if (do_list) {
7258 if (commit_id_arg != NULL)
7259 errx(1,
7260 "-c option can only be used when creating a tag");
7261 if (tagmsg)
7262 option_conflict('l', 'm');
7263 if (argc > 1)
7264 usage_tag();
7265 } else if (argc != 1)
7266 usage_tag();
7268 if (argc == 1)
7269 tag_name = argv[0];
7271 #ifndef PROFILE
7272 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7273 "sendfd unveil", NULL) == -1)
7274 err(1, "pledge");
7275 #endif
7276 cwd = getcwd(NULL, 0);
7277 if (cwd == NULL) {
7278 error = got_error_from_errno("getcwd");
7279 goto done;
7282 error = got_repo_pack_fds_open(&pack_fds);
7283 if (error != NULL)
7284 goto done;
7286 if (repo_path == NULL) {
7287 error = got_worktree_open(&worktree, cwd);
7288 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7289 goto done;
7290 else
7291 error = NULL;
7292 if (worktree) {
7293 repo_path =
7294 strdup(got_worktree_get_repo_path(worktree));
7295 if (repo_path == NULL)
7296 error = got_error_from_errno("strdup");
7297 if (error)
7298 goto done;
7299 } else {
7300 repo_path = strdup(cwd);
7301 if (repo_path == NULL) {
7302 error = got_error_from_errno("strdup");
7303 goto done;
7308 if (do_list) {
7309 if (worktree) {
7310 /* Release work tree lock. */
7311 got_worktree_close(worktree);
7312 worktree = NULL;
7314 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7315 if (error != NULL)
7316 goto done;
7318 #ifndef PROFILE
7319 /* Remove "cpath" promise. */
7320 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7321 NULL) == -1)
7322 err(1, "pledge");
7323 #endif
7324 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7325 if (error)
7326 goto done;
7327 error = list_tags(repo, tag_name);
7328 } else {
7329 error = get_gitconfig_path(&gitconfig_path);
7330 if (error)
7331 goto done;
7332 error = got_repo_open(&repo, repo_path, gitconfig_path,
7333 pack_fds);
7334 if (error != NULL)
7335 goto done;
7337 error = get_author(&tagger, repo, worktree);
7338 if (error)
7339 goto done;
7340 if (worktree) {
7341 /* Release work tree lock. */
7342 got_worktree_close(worktree);
7343 worktree = NULL;
7346 if (tagmsg) {
7347 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7348 if (error)
7349 goto done;
7352 if (commit_id_arg == NULL) {
7353 struct got_reference *head_ref;
7354 struct got_object_id *commit_id;
7355 error = got_ref_open(&head_ref, repo,
7356 worktree ? got_worktree_get_head_ref_name(worktree)
7357 : GOT_REF_HEAD, 0);
7358 if (error)
7359 goto done;
7360 error = got_ref_resolve(&commit_id, repo, head_ref);
7361 got_ref_close(head_ref);
7362 if (error)
7363 goto done;
7364 error = got_object_id_str(&commit_id_str, commit_id);
7365 free(commit_id);
7366 if (error)
7367 goto done;
7370 error = add_tag(repo, tagger, tag_name,
7371 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7373 done:
7374 if (repo) {
7375 const struct got_error *close_err = got_repo_close(repo);
7376 if (error == NULL)
7377 error = close_err;
7379 if (worktree)
7380 got_worktree_close(worktree);
7381 if (pack_fds) {
7382 const struct got_error *pack_err =
7383 got_repo_pack_fds_close(pack_fds);
7384 if (error == NULL)
7385 error = pack_err;
7387 free(cwd);
7388 free(repo_path);
7389 free(gitconfig_path);
7390 free(commit_id_str);
7391 free(tagger);
7392 return error;
7395 __dead static void
7396 usage_add(void)
7398 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7399 getprogname());
7400 exit(1);
7403 static const struct got_error *
7404 add_progress(void *arg, unsigned char status, const char *path)
7406 while (path[0] == '/')
7407 path++;
7408 printf("%c %s\n", status, path);
7409 return NULL;
7412 static const struct got_error *
7413 cmd_add(int argc, char *argv[])
7415 const struct got_error *error = NULL;
7416 struct got_repository *repo = NULL;
7417 struct got_worktree *worktree = NULL;
7418 char *cwd = NULL;
7419 struct got_pathlist_head paths;
7420 struct got_pathlist_entry *pe;
7421 int ch, can_recurse = 0, no_ignores = 0;
7422 int *pack_fds = NULL;
7424 TAILQ_INIT(&paths);
7426 while ((ch = getopt(argc, argv, "IR")) != -1) {
7427 switch (ch) {
7428 case 'I':
7429 no_ignores = 1;
7430 break;
7431 case 'R':
7432 can_recurse = 1;
7433 break;
7434 default:
7435 usage_add();
7436 /* NOTREACHED */
7440 argc -= optind;
7441 argv += optind;
7443 #ifndef PROFILE
7444 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7445 NULL) == -1)
7446 err(1, "pledge");
7447 #endif
7448 if (argc < 1)
7449 usage_add();
7451 cwd = getcwd(NULL, 0);
7452 if (cwd == NULL) {
7453 error = got_error_from_errno("getcwd");
7454 goto done;
7457 error = got_repo_pack_fds_open(&pack_fds);
7458 if (error != NULL)
7459 goto done;
7461 error = got_worktree_open(&worktree, cwd);
7462 if (error) {
7463 if (error->code == GOT_ERR_NOT_WORKTREE)
7464 error = wrap_not_worktree_error(error, "add", cwd);
7465 goto done;
7468 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7469 NULL, pack_fds);
7470 if (error != NULL)
7471 goto done;
7473 error = apply_unveil(got_repo_get_path(repo), 1,
7474 got_worktree_get_root_path(worktree));
7475 if (error)
7476 goto done;
7478 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7479 if (error)
7480 goto done;
7482 if (!can_recurse) {
7483 char *ondisk_path;
7484 struct stat sb;
7485 TAILQ_FOREACH(pe, &paths, entry) {
7486 if (asprintf(&ondisk_path, "%s/%s",
7487 got_worktree_get_root_path(worktree),
7488 pe->path) == -1) {
7489 error = got_error_from_errno("asprintf");
7490 goto done;
7492 if (lstat(ondisk_path, &sb) == -1) {
7493 if (errno == ENOENT) {
7494 free(ondisk_path);
7495 continue;
7497 error = got_error_from_errno2("lstat",
7498 ondisk_path);
7499 free(ondisk_path);
7500 goto done;
7502 free(ondisk_path);
7503 if (S_ISDIR(sb.st_mode)) {
7504 error = got_error_msg(GOT_ERR_BAD_PATH,
7505 "adding directories requires -R option");
7506 goto done;
7511 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7512 NULL, repo, no_ignores);
7513 done:
7514 if (repo) {
7515 const struct got_error *close_err = got_repo_close(repo);
7516 if (error == NULL)
7517 error = close_err;
7519 if (worktree)
7520 got_worktree_close(worktree);
7521 if (pack_fds) {
7522 const struct got_error *pack_err =
7523 got_repo_pack_fds_close(pack_fds);
7524 if (error == NULL)
7525 error = pack_err;
7527 TAILQ_FOREACH(pe, &paths, entry)
7528 free((char *)pe->path);
7529 got_pathlist_free(&paths);
7530 free(cwd);
7531 return error;
7534 __dead static void
7535 usage_remove(void)
7537 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7538 "path ...\n", getprogname());
7539 exit(1);
7542 static const struct got_error *
7543 print_remove_status(void *arg, unsigned char status,
7544 unsigned char staged_status, const char *path)
7546 while (path[0] == '/')
7547 path++;
7548 if (status == GOT_STATUS_NONEXISTENT)
7549 return NULL;
7550 if (status == staged_status && (status == GOT_STATUS_DELETE))
7551 status = GOT_STATUS_NO_CHANGE;
7552 printf("%c%c %s\n", status, staged_status, path);
7553 return NULL;
7556 static const struct got_error *
7557 cmd_remove(int argc, char *argv[])
7559 const struct got_error *error = NULL;
7560 struct got_worktree *worktree = NULL;
7561 struct got_repository *repo = NULL;
7562 const char *status_codes = NULL;
7563 char *cwd = NULL;
7564 struct got_pathlist_head paths;
7565 struct got_pathlist_entry *pe;
7566 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7567 int ignore_missing_paths = 0;
7568 int *pack_fds = NULL;
7570 TAILQ_INIT(&paths);
7572 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7573 switch (ch) {
7574 case 'f':
7575 delete_local_mods = 1;
7576 ignore_missing_paths = 1;
7577 break;
7578 case 'k':
7579 keep_on_disk = 1;
7580 break;
7581 case 'R':
7582 can_recurse = 1;
7583 break;
7584 case 's':
7585 for (i = 0; i < strlen(optarg); i++) {
7586 switch (optarg[i]) {
7587 case GOT_STATUS_MODIFY:
7588 delete_local_mods = 1;
7589 break;
7590 case GOT_STATUS_MISSING:
7591 ignore_missing_paths = 1;
7592 break;
7593 default:
7594 errx(1, "invalid status code '%c'",
7595 optarg[i]);
7598 status_codes = optarg;
7599 break;
7600 default:
7601 usage_remove();
7602 /* NOTREACHED */
7606 argc -= optind;
7607 argv += optind;
7609 #ifndef PROFILE
7610 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7611 NULL) == -1)
7612 err(1, "pledge");
7613 #endif
7614 if (argc < 1)
7615 usage_remove();
7617 cwd = getcwd(NULL, 0);
7618 if (cwd == NULL) {
7619 error = got_error_from_errno("getcwd");
7620 goto done;
7623 error = got_repo_pack_fds_open(&pack_fds);
7624 if (error != NULL)
7625 goto done;
7627 error = got_worktree_open(&worktree, cwd);
7628 if (error) {
7629 if (error->code == GOT_ERR_NOT_WORKTREE)
7630 error = wrap_not_worktree_error(error, "remove", cwd);
7631 goto done;
7634 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7635 NULL, pack_fds);
7636 if (error)
7637 goto done;
7639 error = apply_unveil(got_repo_get_path(repo), 1,
7640 got_worktree_get_root_path(worktree));
7641 if (error)
7642 goto done;
7644 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7645 if (error)
7646 goto done;
7648 if (!can_recurse) {
7649 char *ondisk_path;
7650 struct stat sb;
7651 TAILQ_FOREACH(pe, &paths, entry) {
7652 if (asprintf(&ondisk_path, "%s/%s",
7653 got_worktree_get_root_path(worktree),
7654 pe->path) == -1) {
7655 error = got_error_from_errno("asprintf");
7656 goto done;
7658 if (lstat(ondisk_path, &sb) == -1) {
7659 if (errno == ENOENT) {
7660 free(ondisk_path);
7661 continue;
7663 error = got_error_from_errno2("lstat",
7664 ondisk_path);
7665 free(ondisk_path);
7666 goto done;
7668 free(ondisk_path);
7669 if (S_ISDIR(sb.st_mode)) {
7670 error = got_error_msg(GOT_ERR_BAD_PATH,
7671 "removing directories requires -R option");
7672 goto done;
7677 error = got_worktree_schedule_delete(worktree, &paths,
7678 delete_local_mods, status_codes, print_remove_status, NULL,
7679 repo, keep_on_disk, ignore_missing_paths);
7680 done:
7681 if (repo) {
7682 const struct got_error *close_err = got_repo_close(repo);
7683 if (error == NULL)
7684 error = close_err;
7686 if (worktree)
7687 got_worktree_close(worktree);
7688 if (pack_fds) {
7689 const struct got_error *pack_err =
7690 got_repo_pack_fds_close(pack_fds);
7691 if (error == NULL)
7692 error = pack_err;
7694 TAILQ_FOREACH(pe, &paths, entry)
7695 free((char *)pe->path);
7696 got_pathlist_free(&paths);
7697 free(cwd);
7698 return error;
7701 __dead static void
7702 usage_patch(void)
7704 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7705 "[-R] [patchfile]\n", getprogname());
7706 exit(1);
7709 static const struct got_error *
7710 patch_from_stdin(int *patchfd)
7712 const struct got_error *err = NULL;
7713 ssize_t r;
7714 char *path, buf[BUFSIZ];
7715 sig_t sighup, sigint, sigquit;
7717 err = got_opentemp_named_fd(&path, patchfd,
7718 GOT_TMPDIR_STR "/got-patch");
7719 if (err)
7720 return err;
7721 unlink(path);
7722 free(path);
7724 sighup = signal(SIGHUP, SIG_DFL);
7725 sigint = signal(SIGINT, SIG_DFL);
7726 sigquit = signal(SIGQUIT, SIG_DFL);
7728 for (;;) {
7729 r = read(0, buf, sizeof(buf));
7730 if (r == -1) {
7731 err = got_error_from_errno("read");
7732 break;
7734 if (r == 0)
7735 break;
7736 if (write(*patchfd, buf, r) == -1) {
7737 err = got_error_from_errno("write");
7738 break;
7742 signal(SIGHUP, sighup);
7743 signal(SIGINT, sigint);
7744 signal(SIGQUIT, sigquit);
7746 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7747 err = got_error_from_errno("lseek");
7749 if (err != NULL) {
7750 close(*patchfd);
7751 *patchfd = -1;
7754 return err;
7757 static const struct got_error *
7758 patch_progress(void *arg, const char *old, const char *new,
7759 unsigned char status, const struct got_error *error, long old_from,
7760 long old_lines, long new_from, long new_lines, long offset,
7761 int ws_mangled, const struct got_error *hunk_err)
7763 const char *path = new == NULL ? old : new;
7765 while (*path == '/')
7766 path++;
7768 if (status != 0)
7769 printf("%c %s\n", status, path);
7771 if (error != NULL)
7772 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7774 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7775 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7776 old_lines, new_from, new_lines);
7777 if (hunk_err != NULL)
7778 printf("%s\n", hunk_err->msg);
7779 else if (offset != 0)
7780 printf("applied with offset %ld\n", offset);
7781 else
7782 printf("hunk contains mangled whitespace\n");
7785 return NULL;
7788 static const struct got_error *
7789 cmd_patch(int argc, char *argv[])
7791 const struct got_error *error = NULL, *close_error = NULL;
7792 struct got_worktree *worktree = NULL;
7793 struct got_repository *repo = NULL;
7794 const char *errstr;
7795 char *cwd = NULL;
7796 int ch, nop = 0, strip = -1, reverse = 0;
7797 int patchfd;
7798 int *pack_fds = NULL;
7800 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7801 switch (ch) {
7802 case 'n':
7803 nop = 1;
7804 break;
7805 case 'p':
7806 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7807 if (errstr != NULL)
7808 errx(1, "pathname strip count is %s: %s",
7809 errstr, optarg);
7810 break;
7811 case 'R':
7812 reverse = 1;
7813 break;
7814 default:
7815 usage_patch();
7816 /* NOTREACHED */
7820 argc -= optind;
7821 argv += optind;
7823 if (argc == 0) {
7824 error = patch_from_stdin(&patchfd);
7825 if (error)
7826 return error;
7827 } else if (argc == 1) {
7828 patchfd = open(argv[0], O_RDONLY);
7829 if (patchfd == -1) {
7830 error = got_error_from_errno2("open", argv[0]);
7831 return error;
7833 } else
7834 usage_patch();
7836 if ((cwd = getcwd(NULL, 0)) == NULL) {
7837 error = got_error_from_errno("getcwd");
7838 goto done;
7841 error = got_repo_pack_fds_open(&pack_fds);
7842 if (error != NULL)
7843 goto done;
7845 error = got_worktree_open(&worktree, cwd);
7846 if (error != NULL)
7847 goto done;
7849 const char *repo_path = got_worktree_get_repo_path(worktree);
7850 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7851 if (error != NULL)
7852 goto done;
7854 error = apply_unveil(got_repo_get_path(repo), 0,
7855 got_worktree_get_root_path(worktree));
7856 if (error != NULL)
7857 goto done;
7859 #ifndef PROFILE
7860 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7861 NULL) == -1)
7862 err(1, "pledge");
7863 #endif
7865 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7866 &patch_progress, NULL, check_cancelled, NULL);
7868 done:
7869 if (repo) {
7870 close_error = got_repo_close(repo);
7871 if (error == NULL)
7872 error = close_error;
7874 if (worktree != NULL) {
7875 close_error = got_worktree_close(worktree);
7876 if (error == NULL)
7877 error = close_error;
7879 if (pack_fds) {
7880 const struct got_error *pack_err =
7881 got_repo_pack_fds_close(pack_fds);
7882 if (error == NULL)
7883 error = pack_err;
7885 free(cwd);
7886 return error;
7889 __dead static void
7890 usage_revert(void)
7892 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7893 "path ...\n", getprogname());
7894 exit(1);
7897 static const struct got_error *
7898 revert_progress(void *arg, unsigned char status, const char *path)
7900 if (status == GOT_STATUS_UNVERSIONED)
7901 return NULL;
7903 while (path[0] == '/')
7904 path++;
7905 printf("%c %s\n", status, path);
7906 return NULL;
7909 struct choose_patch_arg {
7910 FILE *patch_script_file;
7911 const char *action;
7914 static const struct got_error *
7915 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7916 int nchanges, const char *action)
7918 const struct got_error *err;
7919 char *line = NULL;
7920 size_t linesize = 0;
7921 ssize_t linelen;
7923 switch (status) {
7924 case GOT_STATUS_ADD:
7925 printf("A %s\n%s this addition? [y/n] ", path, action);
7926 break;
7927 case GOT_STATUS_DELETE:
7928 printf("D %s\n%s this deletion? [y/n] ", path, action);
7929 break;
7930 case GOT_STATUS_MODIFY:
7931 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7932 return got_error_from_errno("fseek");
7933 printf(GOT_COMMIT_SEP_STR);
7934 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7935 printf("%s", line);
7936 if (linelen == -1 && ferror(patch_file)) {
7937 err = got_error_from_errno("getline");
7938 free(line);
7939 return err;
7941 free(line);
7942 printf(GOT_COMMIT_SEP_STR);
7943 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7944 path, n, nchanges, action);
7945 break;
7946 default:
7947 return got_error_path(path, GOT_ERR_FILE_STATUS);
7950 return NULL;
7953 static const struct got_error *
7954 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7955 FILE *patch_file, int n, int nchanges)
7957 const struct got_error *err = NULL;
7958 char *line = NULL;
7959 size_t linesize = 0;
7960 ssize_t linelen;
7961 int resp = ' ';
7962 struct choose_patch_arg *a = arg;
7964 *choice = GOT_PATCH_CHOICE_NONE;
7966 if (a->patch_script_file) {
7967 char *nl;
7968 err = show_change(status, path, patch_file, n, nchanges,
7969 a->action);
7970 if (err)
7971 return err;
7972 linelen = getline(&line, &linesize, a->patch_script_file);
7973 if (linelen == -1) {
7974 if (ferror(a->patch_script_file))
7975 return got_error_from_errno("getline");
7976 return NULL;
7978 nl = strchr(line, '\n');
7979 if (nl)
7980 *nl = '\0';
7981 if (strcmp(line, "y") == 0) {
7982 *choice = GOT_PATCH_CHOICE_YES;
7983 printf("y\n");
7984 } else if (strcmp(line, "n") == 0) {
7985 *choice = GOT_PATCH_CHOICE_NO;
7986 printf("n\n");
7987 } else if (strcmp(line, "q") == 0 &&
7988 status == GOT_STATUS_MODIFY) {
7989 *choice = GOT_PATCH_CHOICE_QUIT;
7990 printf("q\n");
7991 } else
7992 printf("invalid response '%s'\n", line);
7993 free(line);
7994 return NULL;
7997 while (resp != 'y' && resp != 'n' && resp != 'q') {
7998 err = show_change(status, path, patch_file, n, nchanges,
7999 a->action);
8000 if (err)
8001 return err;
8002 resp = getchar();
8003 if (resp == '\n')
8004 resp = getchar();
8005 if (status == GOT_STATUS_MODIFY) {
8006 if (resp != 'y' && resp != 'n' && resp != 'q') {
8007 printf("invalid response '%c'\n", resp);
8008 resp = ' ';
8010 } else if (resp != 'y' && resp != 'n') {
8011 printf("invalid response '%c'\n", resp);
8012 resp = ' ';
8016 if (resp == 'y')
8017 *choice = GOT_PATCH_CHOICE_YES;
8018 else if (resp == 'n')
8019 *choice = GOT_PATCH_CHOICE_NO;
8020 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8021 *choice = GOT_PATCH_CHOICE_QUIT;
8023 return NULL;
8026 static const struct got_error *
8027 cmd_revert(int argc, char *argv[])
8029 const struct got_error *error = NULL;
8030 struct got_worktree *worktree = NULL;
8031 struct got_repository *repo = NULL;
8032 char *cwd = NULL, *path = NULL;
8033 struct got_pathlist_head paths;
8034 struct got_pathlist_entry *pe;
8035 int ch, can_recurse = 0, pflag = 0;
8036 FILE *patch_script_file = NULL;
8037 const char *patch_script_path = NULL;
8038 struct choose_patch_arg cpa;
8039 int *pack_fds = NULL;
8041 TAILQ_INIT(&paths);
8043 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8044 switch (ch) {
8045 case 'p':
8046 pflag = 1;
8047 break;
8048 case 'F':
8049 patch_script_path = optarg;
8050 break;
8051 case 'R':
8052 can_recurse = 1;
8053 break;
8054 default:
8055 usage_revert();
8056 /* NOTREACHED */
8060 argc -= optind;
8061 argv += optind;
8063 #ifndef PROFILE
8064 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8065 "unveil", NULL) == -1)
8066 err(1, "pledge");
8067 #endif
8068 if (argc < 1)
8069 usage_revert();
8070 if (patch_script_path && !pflag)
8071 errx(1, "-F option can only be used together with -p option");
8073 cwd = getcwd(NULL, 0);
8074 if (cwd == NULL) {
8075 error = got_error_from_errno("getcwd");
8076 goto done;
8079 error = got_repo_pack_fds_open(&pack_fds);
8080 if (error != NULL)
8081 goto done;
8083 error = got_worktree_open(&worktree, cwd);
8084 if (error) {
8085 if (error->code == GOT_ERR_NOT_WORKTREE)
8086 error = wrap_not_worktree_error(error, "revert", cwd);
8087 goto done;
8090 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8091 NULL, pack_fds);
8092 if (error != NULL)
8093 goto done;
8095 if (patch_script_path) {
8096 patch_script_file = fopen(patch_script_path, "re");
8097 if (patch_script_file == NULL) {
8098 error = got_error_from_errno2("fopen",
8099 patch_script_path);
8100 goto done;
8103 error = apply_unveil(got_repo_get_path(repo), 1,
8104 got_worktree_get_root_path(worktree));
8105 if (error)
8106 goto done;
8108 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8109 if (error)
8110 goto done;
8112 if (!can_recurse) {
8113 char *ondisk_path;
8114 struct stat sb;
8115 TAILQ_FOREACH(pe, &paths, entry) {
8116 if (asprintf(&ondisk_path, "%s/%s",
8117 got_worktree_get_root_path(worktree),
8118 pe->path) == -1) {
8119 error = got_error_from_errno("asprintf");
8120 goto done;
8122 if (lstat(ondisk_path, &sb) == -1) {
8123 if (errno == ENOENT) {
8124 free(ondisk_path);
8125 continue;
8127 error = got_error_from_errno2("lstat",
8128 ondisk_path);
8129 free(ondisk_path);
8130 goto done;
8132 free(ondisk_path);
8133 if (S_ISDIR(sb.st_mode)) {
8134 error = got_error_msg(GOT_ERR_BAD_PATH,
8135 "reverting directories requires -R option");
8136 goto done;
8141 cpa.patch_script_file = patch_script_file;
8142 cpa.action = "revert";
8143 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8144 pflag ? choose_patch : NULL, &cpa, repo);
8145 done:
8146 if (patch_script_file && fclose(patch_script_file) == EOF &&
8147 error == NULL)
8148 error = got_error_from_errno2("fclose", patch_script_path);
8149 if (repo) {
8150 const struct got_error *close_err = got_repo_close(repo);
8151 if (error == NULL)
8152 error = close_err;
8154 if (worktree)
8155 got_worktree_close(worktree);
8156 if (pack_fds) {
8157 const struct got_error *pack_err =
8158 got_repo_pack_fds_close(pack_fds);
8159 if (error == NULL)
8160 error = pack_err;
8162 free(path);
8163 free(cwd);
8164 return error;
8167 __dead static void
8168 usage_commit(void)
8170 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8171 "[path ...]\n", getprogname());
8172 exit(1);
8175 struct collect_commit_logmsg_arg {
8176 const char *cmdline_log;
8177 const char *prepared_log;
8178 int non_interactive;
8179 const char *editor;
8180 const char *worktree_path;
8181 const char *branch_name;
8182 const char *repo_path;
8183 char *logmsg_path;
8187 static const struct got_error *
8188 read_prepared_logmsg(char **logmsg, const char *path)
8190 const struct got_error *err = NULL;
8191 FILE *f = NULL;
8192 struct stat sb;
8193 size_t r;
8195 *logmsg = NULL;
8196 memset(&sb, 0, sizeof(sb));
8198 f = fopen(path, "re");
8199 if (f == NULL)
8200 return got_error_from_errno2("fopen", path);
8202 if (fstat(fileno(f), &sb) == -1) {
8203 err = got_error_from_errno2("fstat", path);
8204 goto done;
8206 if (sb.st_size == 0) {
8207 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8208 goto done;
8211 *logmsg = malloc(sb.st_size + 1);
8212 if (*logmsg == NULL) {
8213 err = got_error_from_errno("malloc");
8214 goto done;
8217 r = fread(*logmsg, 1, sb.st_size, f);
8218 if (r != sb.st_size) {
8219 if (ferror(f))
8220 err = got_error_from_errno2("fread", path);
8221 else
8222 err = got_error(GOT_ERR_IO);
8223 goto done;
8225 (*logmsg)[sb.st_size] = '\0';
8226 done:
8227 if (fclose(f) == EOF && err == NULL)
8228 err = got_error_from_errno2("fclose", path);
8229 if (err) {
8230 free(*logmsg);
8231 *logmsg = NULL;
8233 return err;
8237 static const struct got_error *
8238 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8239 void *arg)
8241 char *initial_content = NULL;
8242 struct got_pathlist_entry *pe;
8243 const struct got_error *err = NULL;
8244 char *template = NULL;
8245 struct collect_commit_logmsg_arg *a = arg;
8246 int initial_content_len;
8247 int fd = -1;
8248 size_t len;
8250 /* if a message was specified on the command line, just use it */
8251 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8252 len = strlen(a->cmdline_log) + 1;
8253 *logmsg = malloc(len + 1);
8254 if (*logmsg == NULL)
8255 return got_error_from_errno("malloc");
8256 strlcpy(*logmsg, a->cmdline_log, len);
8257 return NULL;
8258 } else if (a->prepared_log != NULL && a->non_interactive)
8259 return read_prepared_logmsg(logmsg, a->prepared_log);
8261 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8262 return got_error_from_errno("asprintf");
8264 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8265 if (err)
8266 goto done;
8268 if (a->prepared_log) {
8269 char *msg;
8270 err = read_prepared_logmsg(&msg, a->prepared_log);
8271 if (err)
8272 goto done;
8273 if (write(fd, msg, strlen(msg)) == -1) {
8274 err = got_error_from_errno2("write", a->logmsg_path);
8275 free(msg);
8276 goto done;
8278 free(msg);
8281 initial_content_len = asprintf(&initial_content,
8282 "\n# changes to be committed on branch %s:\n",
8283 a->branch_name);
8284 if (initial_content_len == -1) {
8285 err = got_error_from_errno("asprintf");
8286 goto done;
8289 if (write(fd, initial_content, initial_content_len) == -1) {
8290 err = got_error_from_errno2("write", a->logmsg_path);
8291 goto done;
8294 TAILQ_FOREACH(pe, commitable_paths, entry) {
8295 struct got_commitable *ct = pe->data;
8296 dprintf(fd, "# %c %s\n",
8297 got_commitable_get_status(ct),
8298 got_commitable_get_path(ct));
8301 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8302 initial_content_len, a->prepared_log ? 0 : 1);
8303 done:
8304 free(initial_content);
8305 free(template);
8307 if (fd != -1 && close(fd) == -1 && err == NULL)
8308 err = got_error_from_errno2("close", a->logmsg_path);
8310 /* Editor is done; we can now apply unveil(2) */
8311 if (err == NULL)
8312 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8313 if (err) {
8314 free(*logmsg);
8315 *logmsg = NULL;
8317 return err;
8320 static const struct got_error *
8321 cmd_commit(int argc, char *argv[])
8323 const struct got_error *error = NULL;
8324 struct got_worktree *worktree = NULL;
8325 struct got_repository *repo = NULL;
8326 char *cwd = NULL, *id_str = NULL;
8327 struct got_object_id *id = NULL;
8328 const char *logmsg = NULL;
8329 char *prepared_logmsg = NULL;
8330 struct collect_commit_logmsg_arg cl_arg;
8331 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8332 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8333 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8334 struct got_pathlist_head paths;
8335 int *pack_fds = NULL;
8337 TAILQ_INIT(&paths);
8338 cl_arg.logmsg_path = NULL;
8340 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8341 switch (ch) {
8342 case 'F':
8343 if (logmsg != NULL)
8344 option_conflict('F', 'm');
8345 prepared_logmsg = realpath(optarg, NULL);
8346 if (prepared_logmsg == NULL)
8347 return got_error_from_errno2("realpath",
8348 optarg);
8349 break;
8350 case 'm':
8351 if (prepared_logmsg)
8352 option_conflict('m', 'F');
8353 logmsg = optarg;
8354 break;
8355 case 'N':
8356 non_interactive = 1;
8357 break;
8358 case 'S':
8359 allow_bad_symlinks = 1;
8360 break;
8361 default:
8362 usage_commit();
8363 /* NOTREACHED */
8367 argc -= optind;
8368 argv += optind;
8370 #ifndef PROFILE
8371 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8372 "unveil", NULL) == -1)
8373 err(1, "pledge");
8374 #endif
8375 cwd = getcwd(NULL, 0);
8376 if (cwd == NULL) {
8377 error = got_error_from_errno("getcwd");
8378 goto done;
8381 error = got_repo_pack_fds_open(&pack_fds);
8382 if (error != NULL)
8383 goto done;
8385 error = got_worktree_open(&worktree, cwd);
8386 if (error) {
8387 if (error->code == GOT_ERR_NOT_WORKTREE)
8388 error = wrap_not_worktree_error(error, "commit", cwd);
8389 goto done;
8392 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8393 if (error)
8394 goto done;
8395 if (rebase_in_progress) {
8396 error = got_error(GOT_ERR_REBASING);
8397 goto done;
8400 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8401 worktree);
8402 if (error)
8403 goto done;
8405 error = get_gitconfig_path(&gitconfig_path);
8406 if (error)
8407 goto done;
8408 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8409 gitconfig_path, pack_fds);
8410 if (error != NULL)
8411 goto done;
8413 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8414 if (error)
8415 goto done;
8416 if (merge_in_progress) {
8417 error = got_error(GOT_ERR_MERGE_BUSY);
8418 goto done;
8421 error = get_author(&author, repo, worktree);
8422 if (error)
8423 return error;
8426 * unveil(2) traverses exec(2); if an editor is used we have
8427 * to apply unveil after the log message has been written.
8429 if (logmsg == NULL || strlen(logmsg) == 0)
8430 error = get_editor(&editor);
8431 else
8432 error = apply_unveil(got_repo_get_path(repo), 0,
8433 got_worktree_get_root_path(worktree));
8434 if (error)
8435 goto done;
8437 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8438 if (error)
8439 goto done;
8441 cl_arg.editor = editor;
8442 cl_arg.cmdline_log = logmsg;
8443 cl_arg.prepared_log = prepared_logmsg;
8444 cl_arg.non_interactive = non_interactive;
8445 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8446 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8447 if (!histedit_in_progress) {
8448 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8449 error = got_error(GOT_ERR_COMMIT_BRANCH);
8450 goto done;
8452 cl_arg.branch_name += 11;
8454 cl_arg.repo_path = got_repo_get_path(repo);
8455 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8456 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8457 print_status, NULL, repo);
8458 if (error) {
8459 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8460 cl_arg.logmsg_path != NULL)
8461 preserve_logmsg = 1;
8462 goto done;
8465 error = got_object_id_str(&id_str, id);
8466 if (error)
8467 goto done;
8468 printf("Created commit %s\n", id_str);
8469 done:
8470 if (preserve_logmsg) {
8471 fprintf(stderr, "%s: log message preserved in %s\n",
8472 getprogname(), cl_arg.logmsg_path);
8473 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8474 error == NULL)
8475 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8476 free(cl_arg.logmsg_path);
8477 if (repo) {
8478 const struct got_error *close_err = got_repo_close(repo);
8479 if (error == NULL)
8480 error = close_err;
8482 if (worktree)
8483 got_worktree_close(worktree);
8484 if (pack_fds) {
8485 const struct got_error *pack_err =
8486 got_repo_pack_fds_close(pack_fds);
8487 if (error == NULL)
8488 error = pack_err;
8490 free(cwd);
8491 free(id_str);
8492 free(gitconfig_path);
8493 free(editor);
8494 free(author);
8495 free(prepared_logmsg);
8496 return error;
8499 __dead static void
8500 usage_send(void)
8502 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8503 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8504 "[remote-repository]\n", getprogname());
8505 exit(1);
8508 static void
8509 print_load_info(int print_colored, int print_found, int print_trees,
8510 int ncolored, int nfound, int ntrees)
8512 if (print_colored) {
8513 printf("%d commit%s colored", ncolored,
8514 ncolored == 1 ? "" : "s");
8516 if (print_found) {
8517 printf("%s%d object%s found",
8518 ncolored > 0 ? "; " : "",
8519 nfound, nfound == 1 ? "" : "s");
8521 if (print_trees) {
8522 printf("; %d tree%s scanned", ntrees,
8523 ntrees == 1 ? "" : "s");
8527 struct got_send_progress_arg {
8528 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8529 int verbosity;
8530 int last_ncolored;
8531 int last_nfound;
8532 int last_ntrees;
8533 int loading_done;
8534 int last_ncommits;
8535 int last_nobj_total;
8536 int last_p_deltify;
8537 int last_p_written;
8538 int last_p_sent;
8539 int printed_something;
8540 int sent_something;
8541 struct got_pathlist_head *delete_branches;
8544 static const struct got_error *
8545 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8546 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8547 int nobj_written, off_t bytes_sent, const char *refname, int success)
8549 struct got_send_progress_arg *a = arg;
8550 char scaled_packsize[FMT_SCALED_STRSIZE];
8551 char scaled_sent[FMT_SCALED_STRSIZE];
8552 int p_deltify = 0, p_written = 0, p_sent = 0;
8553 int print_colored = 0, print_found = 0, print_trees = 0;
8554 int print_searching = 0, print_total = 0;
8555 int print_deltify = 0, print_written = 0, print_sent = 0;
8557 if (a->verbosity < 0)
8558 return NULL;
8560 if (refname) {
8561 const char *status = success ? "accepted" : "rejected";
8563 if (success) {
8564 struct got_pathlist_entry *pe;
8565 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8566 const char *branchname = pe->path;
8567 if (got_path_cmp(branchname, refname,
8568 strlen(branchname), strlen(refname)) == 0) {
8569 status = "deleted";
8570 a->sent_something = 1;
8571 break;
8576 if (a->printed_something)
8577 putchar('\n');
8578 printf("Server has %s %s", status, refname);
8579 a->printed_something = 1;
8580 return NULL;
8583 if (a->last_ncolored != ncolored) {
8584 print_colored = 1;
8585 a->last_ncolored = ncolored;
8588 if (a->last_nfound != nfound) {
8589 print_colored = 1;
8590 print_found = 1;
8591 a->last_nfound = nfound;
8594 if (a->last_ntrees != ntrees) {
8595 print_colored = 1;
8596 print_found = 1;
8597 print_trees = 1;
8598 a->last_ntrees = ntrees;
8601 if ((print_colored || print_found || print_trees) &&
8602 !a->loading_done) {
8603 printf("\r");
8604 print_load_info(print_colored, print_found, print_trees,
8605 ncolored, nfound, ntrees);
8606 a->printed_something = 1;
8607 fflush(stdout);
8608 return NULL;
8609 } else if (!a->loading_done) {
8610 printf("\r");
8611 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8612 printf("\n");
8613 a->loading_done = 1;
8616 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8617 return got_error_from_errno("fmt_scaled");
8618 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8619 return got_error_from_errno("fmt_scaled");
8621 if (a->last_ncommits != ncommits) {
8622 print_searching = 1;
8623 a->last_ncommits = ncommits;
8626 if (a->last_nobj_total != nobj_total) {
8627 print_searching = 1;
8628 print_total = 1;
8629 a->last_nobj_total = nobj_total;
8632 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8633 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8634 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8635 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8636 return got_error(GOT_ERR_NO_SPACE);
8639 if (nobj_deltify > 0 || nobj_written > 0) {
8640 if (nobj_deltify > 0) {
8641 p_deltify = (nobj_deltify * 100) / nobj_total;
8642 if (p_deltify != a->last_p_deltify) {
8643 a->last_p_deltify = p_deltify;
8644 print_searching = 1;
8645 print_total = 1;
8646 print_deltify = 1;
8649 if (nobj_written > 0) {
8650 p_written = (nobj_written * 100) / nobj_total;
8651 if (p_written != a->last_p_written) {
8652 a->last_p_written = p_written;
8653 print_searching = 1;
8654 print_total = 1;
8655 print_deltify = 1;
8656 print_written = 1;
8661 if (bytes_sent > 0) {
8662 p_sent = (bytes_sent * 100) / packfile_size;
8663 if (p_sent != a->last_p_sent) {
8664 a->last_p_sent = p_sent;
8665 print_searching = 1;
8666 print_total = 1;
8667 print_deltify = 1;
8668 print_written = 1;
8669 print_sent = 1;
8671 a->sent_something = 1;
8674 if (print_searching || print_total || print_deltify || print_written ||
8675 print_sent)
8676 printf("\r");
8677 if (print_searching)
8678 printf("packing %d reference%s", ncommits,
8679 ncommits == 1 ? "" : "s");
8680 if (print_total)
8681 printf("; %d object%s", nobj_total,
8682 nobj_total == 1 ? "" : "s");
8683 if (print_deltify)
8684 printf("; deltify: %d%%", p_deltify);
8685 if (print_sent)
8686 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8687 scaled_packsize, p_sent);
8688 else if (print_written)
8689 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8690 scaled_packsize, p_written);
8691 if (print_searching || print_total || print_deltify ||
8692 print_written || print_sent) {
8693 a->printed_something = 1;
8694 fflush(stdout);
8696 return NULL;
8699 static const struct got_error *
8700 cmd_send(int argc, char *argv[])
8702 const struct got_error *error = NULL;
8703 char *cwd = NULL, *repo_path = NULL;
8704 const char *remote_name;
8705 char *proto = NULL, *host = NULL, *port = NULL;
8706 char *repo_name = NULL, *server_path = NULL;
8707 const struct got_remote_repo *remotes, *remote = NULL;
8708 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8709 struct got_repository *repo = NULL;
8710 struct got_worktree *worktree = NULL;
8711 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8712 struct got_pathlist_head branches;
8713 struct got_pathlist_head tags;
8714 struct got_reflist_head all_branches;
8715 struct got_reflist_head all_tags;
8716 struct got_pathlist_head delete_args;
8717 struct got_pathlist_head delete_branches;
8718 struct got_reflist_entry *re;
8719 struct got_pathlist_entry *pe;
8720 int i, ch, sendfd = -1, sendstatus;
8721 pid_t sendpid = -1;
8722 struct got_send_progress_arg spa;
8723 int verbosity = 0, overwrite_refs = 0;
8724 int send_all_branches = 0, send_all_tags = 0;
8725 struct got_reference *ref = NULL;
8726 int *pack_fds = NULL;
8728 TAILQ_INIT(&branches);
8729 TAILQ_INIT(&tags);
8730 TAILQ_INIT(&all_branches);
8731 TAILQ_INIT(&all_tags);
8732 TAILQ_INIT(&delete_args);
8733 TAILQ_INIT(&delete_branches);
8735 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8736 switch (ch) {
8737 case 'a':
8738 send_all_branches = 1;
8739 break;
8740 case 'b':
8741 error = got_pathlist_append(&branches, optarg, NULL);
8742 if (error)
8743 return error;
8744 nbranches++;
8745 break;
8746 case 'd':
8747 error = got_pathlist_append(&delete_args, optarg, NULL);
8748 if (error)
8749 return error;
8750 break;
8751 case 'f':
8752 overwrite_refs = 1;
8753 break;
8754 case 'r':
8755 repo_path = realpath(optarg, NULL);
8756 if (repo_path == NULL)
8757 return got_error_from_errno2("realpath",
8758 optarg);
8759 got_path_strip_trailing_slashes(repo_path);
8760 break;
8761 case 't':
8762 error = got_pathlist_append(&tags, optarg, NULL);
8763 if (error)
8764 return error;
8765 ntags++;
8766 break;
8767 case 'T':
8768 send_all_tags = 1;
8769 break;
8770 case 'v':
8771 if (verbosity < 0)
8772 verbosity = 0;
8773 else if (verbosity < 3)
8774 verbosity++;
8775 break;
8776 case 'q':
8777 verbosity = -1;
8778 break;
8779 default:
8780 usage_send();
8781 /* NOTREACHED */
8784 argc -= optind;
8785 argv += optind;
8787 if (send_all_branches && !TAILQ_EMPTY(&branches))
8788 option_conflict('a', 'b');
8789 if (send_all_tags && !TAILQ_EMPTY(&tags))
8790 option_conflict('T', 't');
8793 if (argc == 0)
8794 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8795 else if (argc == 1)
8796 remote_name = argv[0];
8797 else
8798 usage_send();
8800 cwd = getcwd(NULL, 0);
8801 if (cwd == NULL) {
8802 error = got_error_from_errno("getcwd");
8803 goto done;
8806 error = got_repo_pack_fds_open(&pack_fds);
8807 if (error != NULL)
8808 goto done;
8810 if (repo_path == NULL) {
8811 error = got_worktree_open(&worktree, cwd);
8812 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8813 goto done;
8814 else
8815 error = NULL;
8816 if (worktree) {
8817 repo_path =
8818 strdup(got_worktree_get_repo_path(worktree));
8819 if (repo_path == NULL)
8820 error = got_error_from_errno("strdup");
8821 if (error)
8822 goto done;
8823 } else {
8824 repo_path = strdup(cwd);
8825 if (repo_path == NULL) {
8826 error = got_error_from_errno("strdup");
8827 goto done;
8832 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8833 if (error)
8834 goto done;
8836 if (worktree) {
8837 worktree_conf = got_worktree_get_gotconfig(worktree);
8838 if (worktree_conf) {
8839 got_gotconfig_get_remotes(&nremotes, &remotes,
8840 worktree_conf);
8841 for (i = 0; i < nremotes; i++) {
8842 if (strcmp(remotes[i].name, remote_name) == 0) {
8843 remote = &remotes[i];
8844 break;
8849 if (remote == NULL) {
8850 repo_conf = got_repo_get_gotconfig(repo);
8851 if (repo_conf) {
8852 got_gotconfig_get_remotes(&nremotes, &remotes,
8853 repo_conf);
8854 for (i = 0; i < nremotes; i++) {
8855 if (strcmp(remotes[i].name, remote_name) == 0) {
8856 remote = &remotes[i];
8857 break;
8862 if (remote == NULL) {
8863 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8864 for (i = 0; i < nremotes; i++) {
8865 if (strcmp(remotes[i].name, remote_name) == 0) {
8866 remote = &remotes[i];
8867 break;
8871 if (remote == NULL) {
8872 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8873 goto done;
8876 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8877 &repo_name, remote->send_url);
8878 if (error)
8879 goto done;
8881 if (strcmp(proto, "git") == 0) {
8882 #ifndef PROFILE
8883 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8884 "sendfd dns inet unveil", NULL) == -1)
8885 err(1, "pledge");
8886 #endif
8887 } else if (strcmp(proto, "git+ssh") == 0 ||
8888 strcmp(proto, "ssh") == 0) {
8889 #ifndef PROFILE
8890 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8891 "sendfd unveil", NULL) == -1)
8892 err(1, "pledge");
8893 #endif
8894 } else if (strcmp(proto, "http") == 0 ||
8895 strcmp(proto, "git+http") == 0) {
8896 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8897 goto done;
8898 } else {
8899 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8900 goto done;
8903 error = got_dial_apply_unveil(proto);
8904 if (error)
8905 goto done;
8907 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8908 if (error)
8909 goto done;
8911 if (send_all_branches) {
8912 error = got_ref_list(&all_branches, repo, "refs/heads",
8913 got_ref_cmp_by_name, NULL);
8914 if (error)
8915 goto done;
8916 TAILQ_FOREACH(re, &all_branches, entry) {
8917 const char *branchname = got_ref_get_name(re->ref);
8918 error = got_pathlist_append(&branches,
8919 branchname, NULL);
8920 if (error)
8921 goto done;
8922 nbranches++;
8924 } else if (nbranches == 0) {
8925 for (i = 0; i < remote->nsend_branches; i++) {
8926 got_pathlist_append(&branches,
8927 remote->send_branches[i], NULL);
8931 if (send_all_tags) {
8932 error = got_ref_list(&all_tags, repo, "refs/tags",
8933 got_ref_cmp_by_name, NULL);
8934 if (error)
8935 goto done;
8936 TAILQ_FOREACH(re, &all_tags, entry) {
8937 const char *tagname = got_ref_get_name(re->ref);
8938 error = got_pathlist_append(&tags,
8939 tagname, NULL);
8940 if (error)
8941 goto done;
8942 ntags++;
8947 * To prevent accidents only branches in refs/heads/ can be deleted
8948 * with 'got send -d'.
8949 * Deleting anything else requires local repository access or Git.
8951 TAILQ_FOREACH(pe, &delete_args, entry) {
8952 const char *branchname = pe->path;
8953 char *s;
8954 struct got_pathlist_entry *new;
8955 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8956 s = strdup(branchname);
8957 if (s == NULL) {
8958 error = got_error_from_errno("strdup");
8959 goto done;
8961 } else {
8962 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8963 error = got_error_from_errno("asprintf");
8964 goto done;
8967 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8968 if (error || new == NULL /* duplicate */)
8969 free(s);
8970 if (error)
8971 goto done;
8972 ndelete_branches++;
8975 if (nbranches == 0 && ndelete_branches == 0) {
8976 struct got_reference *head_ref;
8977 if (worktree)
8978 error = got_ref_open(&head_ref, repo,
8979 got_worktree_get_head_ref_name(worktree), 0);
8980 else
8981 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8982 if (error)
8983 goto done;
8984 if (got_ref_is_symbolic(head_ref)) {
8985 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8986 got_ref_close(head_ref);
8987 if (error)
8988 goto done;
8989 } else
8990 ref = head_ref;
8991 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8992 NULL);
8993 if (error)
8994 goto done;
8995 nbranches++;
8998 if (verbosity >= 0)
8999 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9000 port ? ":" : "", port ? port : "");
9002 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9003 server_path, verbosity);
9004 if (error)
9005 goto done;
9007 memset(&spa, 0, sizeof(spa));
9008 spa.last_scaled_packsize[0] = '\0';
9009 spa.last_p_deltify = -1;
9010 spa.last_p_written = -1;
9011 spa.verbosity = verbosity;
9012 spa.delete_branches = &delete_branches;
9013 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9014 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9015 check_cancelled, NULL);
9016 if (spa.printed_something)
9017 putchar('\n');
9018 if (error)
9019 goto done;
9020 if (!spa.sent_something && verbosity >= 0)
9021 printf("Already up-to-date\n");
9022 done:
9023 if (sendpid > 0) {
9024 if (kill(sendpid, SIGTERM) == -1)
9025 error = got_error_from_errno("kill");
9026 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9027 error = got_error_from_errno("waitpid");
9029 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9030 error = got_error_from_errno("close");
9031 if (repo) {
9032 const struct got_error *close_err = got_repo_close(repo);
9033 if (error == NULL)
9034 error = close_err;
9036 if (worktree)
9037 got_worktree_close(worktree);
9038 if (pack_fds) {
9039 const struct got_error *pack_err =
9040 got_repo_pack_fds_close(pack_fds);
9041 if (error == NULL)
9042 error = pack_err;
9044 if (ref)
9045 got_ref_close(ref);
9046 got_pathlist_free(&branches);
9047 got_pathlist_free(&tags);
9048 got_ref_list_free(&all_branches);
9049 got_ref_list_free(&all_tags);
9050 got_pathlist_free(&delete_args);
9051 TAILQ_FOREACH(pe, &delete_branches, entry)
9052 free((char *)pe->path);
9053 got_pathlist_free(&delete_branches);
9054 free(cwd);
9055 free(repo_path);
9056 free(proto);
9057 free(host);
9058 free(port);
9059 free(server_path);
9060 free(repo_name);
9061 return error;
9064 __dead static void
9065 usage_cherrypick(void)
9067 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9068 exit(1);
9071 static const struct got_error *
9072 cmd_cherrypick(int argc, char *argv[])
9074 const struct got_error *error = NULL;
9075 struct got_worktree *worktree = NULL;
9076 struct got_repository *repo = NULL;
9077 char *cwd = NULL, *commit_id_str = NULL;
9078 struct got_object_id *commit_id = NULL;
9079 struct got_commit_object *commit = NULL;
9080 struct got_object_qid *pid;
9081 int ch;
9082 struct got_update_progress_arg upa;
9083 int *pack_fds = NULL;
9085 while ((ch = getopt(argc, argv, "")) != -1) {
9086 switch (ch) {
9087 default:
9088 usage_cherrypick();
9089 /* NOTREACHED */
9093 argc -= optind;
9094 argv += optind;
9096 #ifndef PROFILE
9097 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9098 "unveil", NULL) == -1)
9099 err(1, "pledge");
9100 #endif
9101 if (argc != 1)
9102 usage_cherrypick();
9104 cwd = getcwd(NULL, 0);
9105 if (cwd == NULL) {
9106 error = got_error_from_errno("getcwd");
9107 goto done;
9110 error = got_repo_pack_fds_open(&pack_fds);
9111 if (error != NULL)
9112 goto done;
9114 error = got_worktree_open(&worktree, cwd);
9115 if (error) {
9116 if (error->code == GOT_ERR_NOT_WORKTREE)
9117 error = wrap_not_worktree_error(error, "cherrypick",
9118 cwd);
9119 goto done;
9122 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9123 NULL, pack_fds);
9124 if (error != NULL)
9125 goto done;
9127 error = apply_unveil(got_repo_get_path(repo), 0,
9128 got_worktree_get_root_path(worktree));
9129 if (error)
9130 goto done;
9132 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9133 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9134 if (error)
9135 goto done;
9136 error = got_object_id_str(&commit_id_str, commit_id);
9137 if (error)
9138 goto done;
9140 error = got_object_open_as_commit(&commit, repo, commit_id);
9141 if (error)
9142 goto done;
9143 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9144 memset(&upa, 0, sizeof(upa));
9145 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9146 commit_id, repo, update_progress, &upa, check_cancelled,
9147 NULL);
9148 if (error != NULL)
9149 goto done;
9151 if (upa.did_something)
9152 printf("Merged commit %s\n", commit_id_str);
9153 print_merge_progress_stats(&upa);
9154 done:
9155 if (commit)
9156 got_object_commit_close(commit);
9157 free(commit_id_str);
9158 if (worktree)
9159 got_worktree_close(worktree);
9160 if (repo) {
9161 const struct got_error *close_err = got_repo_close(repo);
9162 if (error == NULL)
9163 error = close_err;
9165 if (pack_fds) {
9166 const struct got_error *pack_err =
9167 got_repo_pack_fds_close(pack_fds);
9168 if (error == NULL)
9169 error = pack_err;
9172 return error;
9175 __dead static void
9176 usage_backout(void)
9178 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9179 exit(1);
9182 static const struct got_error *
9183 cmd_backout(int argc, char *argv[])
9185 const struct got_error *error = NULL;
9186 struct got_worktree *worktree = NULL;
9187 struct got_repository *repo = NULL;
9188 char *cwd = NULL, *commit_id_str = NULL;
9189 struct got_object_id *commit_id = NULL;
9190 struct got_commit_object *commit = NULL;
9191 struct got_object_qid *pid;
9192 int ch;
9193 struct got_update_progress_arg upa;
9194 int *pack_fds = NULL;
9196 while ((ch = getopt(argc, argv, "")) != -1) {
9197 switch (ch) {
9198 default:
9199 usage_backout();
9200 /* NOTREACHED */
9204 argc -= optind;
9205 argv += optind;
9207 #ifndef PROFILE
9208 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9209 "unveil", NULL) == -1)
9210 err(1, "pledge");
9211 #endif
9212 if (argc != 1)
9213 usage_backout();
9215 cwd = getcwd(NULL, 0);
9216 if (cwd == NULL) {
9217 error = got_error_from_errno("getcwd");
9218 goto done;
9221 error = got_repo_pack_fds_open(&pack_fds);
9222 if (error != NULL)
9223 goto done;
9225 error = got_worktree_open(&worktree, cwd);
9226 if (error) {
9227 if (error->code == GOT_ERR_NOT_WORKTREE)
9228 error = wrap_not_worktree_error(error, "backout", cwd);
9229 goto done;
9232 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9233 NULL, pack_fds);
9234 if (error != NULL)
9235 goto done;
9237 error = apply_unveil(got_repo_get_path(repo), 0,
9238 got_worktree_get_root_path(worktree));
9239 if (error)
9240 goto done;
9242 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9243 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9244 if (error)
9245 goto done;
9246 error = got_object_id_str(&commit_id_str, commit_id);
9247 if (error)
9248 goto done;
9250 error = got_object_open_as_commit(&commit, repo, commit_id);
9251 if (error)
9252 goto done;
9253 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9254 if (pid == NULL) {
9255 error = got_error(GOT_ERR_ROOT_COMMIT);
9256 goto done;
9259 memset(&upa, 0, sizeof(upa));
9260 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9261 repo, update_progress, &upa, check_cancelled, NULL);
9262 if (error != NULL)
9263 goto done;
9265 if (upa.did_something)
9266 printf("Backed out commit %s\n", commit_id_str);
9267 print_merge_progress_stats(&upa);
9268 done:
9269 if (commit)
9270 got_object_commit_close(commit);
9271 free(commit_id_str);
9272 if (worktree)
9273 got_worktree_close(worktree);
9274 if (repo) {
9275 const struct got_error *close_err = got_repo_close(repo);
9276 if (error == NULL)
9277 error = close_err;
9279 if (pack_fds) {
9280 const struct got_error *pack_err =
9281 got_repo_pack_fds_close(pack_fds);
9282 if (error == NULL)
9283 error = pack_err;
9285 return error;
9288 __dead static void
9289 usage_rebase(void)
9291 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9292 getprogname());
9293 exit(1);
9296 static void
9297 trim_logmsg(char *logmsg, int limit)
9299 char *nl;
9300 size_t len;
9302 len = strlen(logmsg);
9303 if (len > limit)
9304 len = limit;
9305 logmsg[len] = '\0';
9306 nl = strchr(logmsg, '\n');
9307 if (nl)
9308 *nl = '\0';
9311 static const struct got_error *
9312 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9314 const struct got_error *err;
9315 char *logmsg0 = NULL;
9316 const char *s;
9318 err = got_object_commit_get_logmsg(&logmsg0, commit);
9319 if (err)
9320 return err;
9322 s = logmsg0;
9323 while (isspace((unsigned char)s[0]))
9324 s++;
9326 *logmsg = strdup(s);
9327 if (*logmsg == NULL) {
9328 err = got_error_from_errno("strdup");
9329 goto done;
9332 trim_logmsg(*logmsg, limit);
9333 done:
9334 free(logmsg0);
9335 return err;
9338 static const struct got_error *
9339 show_rebase_merge_conflict(struct got_object_id *id,
9340 struct got_repository *repo)
9342 const struct got_error *err;
9343 struct got_commit_object *commit = NULL;
9344 char *id_str = NULL, *logmsg = NULL;
9346 err = got_object_open_as_commit(&commit, repo, id);
9347 if (err)
9348 return err;
9350 err = got_object_id_str(&id_str, id);
9351 if (err)
9352 goto done;
9354 id_str[12] = '\0';
9356 err = get_short_logmsg(&logmsg, 42, commit);
9357 if (err)
9358 goto done;
9360 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9361 done:
9362 free(id_str);
9363 got_object_commit_close(commit);
9364 free(logmsg);
9365 return err;
9368 static const struct got_error *
9369 show_rebase_progress(struct got_commit_object *commit,
9370 struct got_object_id *old_id, struct got_object_id *new_id)
9372 const struct got_error *err;
9373 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9375 err = got_object_id_str(&old_id_str, old_id);
9376 if (err)
9377 goto done;
9379 if (new_id) {
9380 err = got_object_id_str(&new_id_str, new_id);
9381 if (err)
9382 goto done;
9385 old_id_str[12] = '\0';
9386 if (new_id_str)
9387 new_id_str[12] = '\0';
9389 err = get_short_logmsg(&logmsg, 42, commit);
9390 if (err)
9391 goto done;
9393 printf("%s -> %s: %s\n", old_id_str,
9394 new_id_str ? new_id_str : "no-op change", logmsg);
9395 done:
9396 free(old_id_str);
9397 free(new_id_str);
9398 free(logmsg);
9399 return err;
9402 static const struct got_error *
9403 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9404 struct got_reference *branch, struct got_reference *new_base_branch,
9405 struct got_reference *tmp_branch, struct got_repository *repo,
9406 int create_backup)
9408 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9409 return got_worktree_rebase_complete(worktree, fileindex,
9410 new_base_branch, tmp_branch, branch, repo, create_backup);
9413 static const struct got_error *
9414 rebase_commit(struct got_pathlist_head *merged_paths,
9415 struct got_worktree *worktree, struct got_fileindex *fileindex,
9416 struct got_reference *tmp_branch,
9417 struct got_object_id *commit_id, struct got_repository *repo)
9419 const struct got_error *error;
9420 struct got_commit_object *commit;
9421 struct got_object_id *new_commit_id;
9423 error = got_object_open_as_commit(&commit, repo, commit_id);
9424 if (error)
9425 return error;
9427 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9428 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9429 if (error) {
9430 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9431 goto done;
9432 error = show_rebase_progress(commit, commit_id, NULL);
9433 } else {
9434 error = show_rebase_progress(commit, commit_id, new_commit_id);
9435 free(new_commit_id);
9437 done:
9438 got_object_commit_close(commit);
9439 return error;
9442 struct check_path_prefix_arg {
9443 const char *path_prefix;
9444 size_t len;
9445 int errcode;
9448 static const struct got_error *
9449 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9450 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9451 struct got_object_id *id1, struct got_object_id *id2,
9452 const char *path1, const char *path2,
9453 mode_t mode1, mode_t mode2, struct got_repository *repo)
9455 struct check_path_prefix_arg *a = arg;
9457 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9458 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9459 return got_error(a->errcode);
9461 return NULL;
9464 static const struct got_error *
9465 check_path_prefix(struct got_object_id *parent_id,
9466 struct got_object_id *commit_id, const char *path_prefix,
9467 int errcode, struct got_repository *repo)
9469 const struct got_error *err;
9470 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9471 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9472 struct check_path_prefix_arg cpp_arg;
9474 if (got_path_is_root_dir(path_prefix))
9475 return NULL;
9477 err = got_object_open_as_commit(&commit, repo, commit_id);
9478 if (err)
9479 goto done;
9481 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9482 if (err)
9483 goto done;
9485 err = got_object_open_as_tree(&tree1, repo,
9486 got_object_commit_get_tree_id(parent_commit));
9487 if (err)
9488 goto done;
9490 err = got_object_open_as_tree(&tree2, repo,
9491 got_object_commit_get_tree_id(commit));
9492 if (err)
9493 goto done;
9495 cpp_arg.path_prefix = path_prefix;
9496 while (cpp_arg.path_prefix[0] == '/')
9497 cpp_arg.path_prefix++;
9498 cpp_arg.len = strlen(cpp_arg.path_prefix);
9499 cpp_arg.errcode = errcode;
9500 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9501 check_path_prefix_in_diff, &cpp_arg, 0);
9502 done:
9503 if (tree1)
9504 got_object_tree_close(tree1);
9505 if (tree2)
9506 got_object_tree_close(tree2);
9507 if (commit)
9508 got_object_commit_close(commit);
9509 if (parent_commit)
9510 got_object_commit_close(parent_commit);
9511 return err;
9514 static const struct got_error *
9515 collect_commits(struct got_object_id_queue *commits,
9516 struct got_object_id *initial_commit_id,
9517 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9518 const char *path_prefix, int path_prefix_errcode,
9519 struct got_repository *repo)
9521 const struct got_error *err = NULL;
9522 struct got_commit_graph *graph = NULL;
9523 struct got_object_id *parent_id = NULL;
9524 struct got_object_qid *qid;
9525 struct got_object_id *commit_id = initial_commit_id;
9527 err = got_commit_graph_open(&graph, "/", 1);
9528 if (err)
9529 return err;
9531 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9532 check_cancelled, NULL);
9533 if (err)
9534 goto done;
9535 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9536 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9537 check_cancelled, NULL);
9538 if (err) {
9539 if (err->code == GOT_ERR_ITER_COMPLETED) {
9540 err = got_error_msg(GOT_ERR_ANCESTRY,
9541 "ran out of commits to rebase before "
9542 "youngest common ancestor commit has "
9543 "been reached?!?");
9545 goto done;
9546 } else {
9547 err = check_path_prefix(parent_id, commit_id,
9548 path_prefix, path_prefix_errcode, repo);
9549 if (err)
9550 goto done;
9552 err = got_object_qid_alloc(&qid, commit_id);
9553 if (err)
9554 goto done;
9555 STAILQ_INSERT_HEAD(commits, qid, entry);
9556 commit_id = parent_id;
9559 done:
9560 got_commit_graph_close(graph);
9561 return err;
9564 static const struct got_error *
9565 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9567 const struct got_error *err = NULL;
9568 time_t committer_time;
9569 struct tm tm;
9570 char datebuf[11]; /* YYYY-MM-DD + NUL */
9571 char *author0 = NULL, *author, *smallerthan;
9572 char *logmsg0 = NULL, *logmsg, *newline;
9574 committer_time = got_object_commit_get_committer_time(commit);
9575 if (gmtime_r(&committer_time, &tm) == NULL)
9576 return got_error_from_errno("gmtime_r");
9577 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9578 return got_error(GOT_ERR_NO_SPACE);
9580 author0 = strdup(got_object_commit_get_author(commit));
9581 if (author0 == NULL)
9582 return got_error_from_errno("strdup");
9583 author = author0;
9584 smallerthan = strchr(author, '<');
9585 if (smallerthan && smallerthan[1] != '\0')
9586 author = smallerthan + 1;
9587 author[strcspn(author, "@>")] = '\0';
9589 err = got_object_commit_get_logmsg(&logmsg0, commit);
9590 if (err)
9591 goto done;
9592 logmsg = logmsg0;
9593 while (*logmsg == '\n')
9594 logmsg++;
9595 newline = strchr(logmsg, '\n');
9596 if (newline)
9597 *newline = '\0';
9599 if (asprintf(brief_str, "%s %s %s",
9600 datebuf, author, logmsg) == -1)
9601 err = got_error_from_errno("asprintf");
9602 done:
9603 free(author0);
9604 free(logmsg0);
9605 return err;
9608 static const struct got_error *
9609 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9610 struct got_repository *repo)
9612 const struct got_error *err;
9613 char *id_str;
9615 err = got_object_id_str(&id_str, id);
9616 if (err)
9617 return err;
9619 err = got_ref_delete(ref, repo);
9620 if (err)
9621 goto done;
9623 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9624 done:
9625 free(id_str);
9626 return err;
9629 static const struct got_error *
9630 print_backup_ref(const char *branch_name, const char *new_id_str,
9631 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9632 struct got_reflist_object_id_map *refs_idmap,
9633 struct got_repository *repo)
9635 const struct got_error *err = NULL;
9636 struct got_reflist_head *refs;
9637 char *refs_str = NULL;
9638 struct got_object_id *new_commit_id = NULL;
9639 struct got_commit_object *new_commit = NULL;
9640 char *new_commit_brief_str = NULL;
9641 struct got_object_id *yca_id = NULL;
9642 struct got_commit_object *yca_commit = NULL;
9643 char *yca_id_str = NULL, *yca_brief_str = NULL;
9644 char *custom_refs_str;
9646 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9647 return got_error_from_errno("asprintf");
9649 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9650 0, 0, refs_idmap, custom_refs_str);
9651 if (err)
9652 goto done;
9654 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9655 if (err)
9656 goto done;
9658 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9659 if (refs) {
9660 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9661 if (err)
9662 goto done;
9665 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9666 if (err)
9667 goto done;
9669 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9670 if (err)
9671 goto done;
9673 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9674 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9675 if (err)
9676 goto done;
9678 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9679 refs_str ? " (" : "", refs_str ? refs_str : "",
9680 refs_str ? ")" : "", new_commit_brief_str);
9681 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9682 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9683 free(refs_str);
9684 refs_str = NULL;
9686 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9687 if (err)
9688 goto done;
9690 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9691 if (err)
9692 goto done;
9694 err = got_object_id_str(&yca_id_str, yca_id);
9695 if (err)
9696 goto done;
9698 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9699 if (refs) {
9700 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9701 if (err)
9702 goto done;
9704 printf("history forked at %s%s%s%s\n %s\n",
9705 yca_id_str,
9706 refs_str ? " (" : "", refs_str ? refs_str : "",
9707 refs_str ? ")" : "", yca_brief_str);
9709 done:
9710 free(custom_refs_str);
9711 free(new_commit_id);
9712 free(refs_str);
9713 free(yca_id);
9714 free(yca_id_str);
9715 free(yca_brief_str);
9716 if (new_commit)
9717 got_object_commit_close(new_commit);
9718 if (yca_commit)
9719 got_object_commit_close(yca_commit);
9721 return NULL;
9724 static const struct got_error *
9725 process_backup_refs(const char *backup_ref_prefix,
9726 const char *wanted_branch_name,
9727 int delete, struct got_repository *repo)
9729 const struct got_error *err;
9730 struct got_reflist_head refs, backup_refs;
9731 struct got_reflist_entry *re;
9732 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9733 struct got_object_id *old_commit_id = NULL;
9734 char *branch_name = NULL;
9735 struct got_commit_object *old_commit = NULL;
9736 struct got_reflist_object_id_map *refs_idmap = NULL;
9737 int wanted_branch_found = 0;
9739 TAILQ_INIT(&refs);
9740 TAILQ_INIT(&backup_refs);
9742 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9743 if (err)
9744 return err;
9746 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9747 if (err)
9748 goto done;
9750 if (wanted_branch_name) {
9751 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9752 wanted_branch_name += 11;
9755 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9756 got_ref_cmp_by_commit_timestamp_descending, repo);
9757 if (err)
9758 goto done;
9760 TAILQ_FOREACH(re, &backup_refs, entry) {
9761 const char *refname = got_ref_get_name(re->ref);
9762 char *slash;
9764 err = check_cancelled(NULL);
9765 if (err)
9766 break;
9768 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9769 if (err)
9770 break;
9772 err = got_object_open_as_commit(&old_commit, repo,
9773 old_commit_id);
9774 if (err)
9775 break;
9777 if (strncmp(backup_ref_prefix, refname,
9778 backup_ref_prefix_len) == 0)
9779 refname += backup_ref_prefix_len;
9781 while (refname[0] == '/')
9782 refname++;
9784 branch_name = strdup(refname);
9785 if (branch_name == NULL) {
9786 err = got_error_from_errno("strdup");
9787 break;
9789 slash = strrchr(branch_name, '/');
9790 if (slash) {
9791 *slash = '\0';
9792 refname += strlen(branch_name) + 1;
9795 if (wanted_branch_name == NULL ||
9796 strcmp(wanted_branch_name, branch_name) == 0) {
9797 wanted_branch_found = 1;
9798 if (delete) {
9799 err = delete_backup_ref(re->ref,
9800 old_commit_id, repo);
9801 } else {
9802 err = print_backup_ref(branch_name, refname,
9803 old_commit_id, old_commit, refs_idmap,
9804 repo);
9806 if (err)
9807 break;
9810 free(old_commit_id);
9811 old_commit_id = NULL;
9812 free(branch_name);
9813 branch_name = NULL;
9814 got_object_commit_close(old_commit);
9815 old_commit = NULL;
9818 if (wanted_branch_name && !wanted_branch_found) {
9819 err = got_error_fmt(GOT_ERR_NOT_REF,
9820 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9822 done:
9823 if (refs_idmap)
9824 got_reflist_object_id_map_free(refs_idmap);
9825 got_ref_list_free(&refs);
9826 got_ref_list_free(&backup_refs);
9827 free(old_commit_id);
9828 free(branch_name);
9829 if (old_commit)
9830 got_object_commit_close(old_commit);
9831 return err;
9834 static const struct got_error *
9835 abort_progress(void *arg, unsigned char status, const char *path)
9838 * Unversioned files should not clutter progress output when
9839 * an operation is aborted.
9841 if (status == GOT_STATUS_UNVERSIONED)
9842 return NULL;
9844 return update_progress(arg, status, path);
9847 static const struct got_error *
9848 cmd_rebase(int argc, char *argv[])
9850 const struct got_error *error = NULL;
9851 struct got_worktree *worktree = NULL;
9852 struct got_repository *repo = NULL;
9853 struct got_fileindex *fileindex = NULL;
9854 char *cwd = NULL;
9855 struct got_reference *branch = NULL;
9856 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9857 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9858 struct got_object_id *resume_commit_id = NULL;
9859 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9860 struct got_commit_object *commit = NULL;
9861 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9862 int histedit_in_progress = 0, merge_in_progress = 0;
9863 int create_backup = 1, list_backups = 0, delete_backups = 0;
9864 struct got_object_id_queue commits;
9865 struct got_pathlist_head merged_paths;
9866 const struct got_object_id_queue *parent_ids;
9867 struct got_object_qid *qid, *pid;
9868 struct got_update_progress_arg upa;
9869 int *pack_fds = NULL;
9871 STAILQ_INIT(&commits);
9872 TAILQ_INIT(&merged_paths);
9873 memset(&upa, 0, sizeof(upa));
9875 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9876 switch (ch) {
9877 case 'a':
9878 abort_rebase = 1;
9879 break;
9880 case 'c':
9881 continue_rebase = 1;
9882 break;
9883 case 'l':
9884 list_backups = 1;
9885 break;
9886 case 'X':
9887 delete_backups = 1;
9888 break;
9889 default:
9890 usage_rebase();
9891 /* NOTREACHED */
9895 argc -= optind;
9896 argv += optind;
9898 #ifndef PROFILE
9899 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9900 "unveil", NULL) == -1)
9901 err(1, "pledge");
9902 #endif
9903 if (list_backups) {
9904 if (abort_rebase)
9905 option_conflict('l', 'a');
9906 if (continue_rebase)
9907 option_conflict('l', 'c');
9908 if (delete_backups)
9909 option_conflict('l', 'X');
9910 if (argc != 0 && argc != 1)
9911 usage_rebase();
9912 } else if (delete_backups) {
9913 if (abort_rebase)
9914 option_conflict('X', 'a');
9915 if (continue_rebase)
9916 option_conflict('X', 'c');
9917 if (list_backups)
9918 option_conflict('l', 'X');
9919 if (argc != 0 && argc != 1)
9920 usage_rebase();
9921 } else {
9922 if (abort_rebase && continue_rebase)
9923 usage_rebase();
9924 else if (abort_rebase || continue_rebase) {
9925 if (argc != 0)
9926 usage_rebase();
9927 } else if (argc != 1)
9928 usage_rebase();
9931 cwd = getcwd(NULL, 0);
9932 if (cwd == NULL) {
9933 error = got_error_from_errno("getcwd");
9934 goto done;
9937 error = got_repo_pack_fds_open(&pack_fds);
9938 if (error != NULL)
9939 goto done;
9941 error = got_worktree_open(&worktree, cwd);
9942 if (error) {
9943 if (list_backups || delete_backups) {
9944 if (error->code != GOT_ERR_NOT_WORKTREE)
9945 goto done;
9946 } else {
9947 if (error->code == GOT_ERR_NOT_WORKTREE)
9948 error = wrap_not_worktree_error(error,
9949 "rebase", cwd);
9950 goto done;
9954 error = got_repo_open(&repo,
9955 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9956 pack_fds);
9957 if (error != NULL)
9958 goto done;
9960 error = apply_unveil(got_repo_get_path(repo), 0,
9961 worktree ? got_worktree_get_root_path(worktree) : NULL);
9962 if (error)
9963 goto done;
9965 if (list_backups || delete_backups) {
9966 error = process_backup_refs(
9967 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9968 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9969 goto done; /* nothing else to do */
9972 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9973 worktree);
9974 if (error)
9975 goto done;
9976 if (histedit_in_progress) {
9977 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9978 goto done;
9981 error = got_worktree_merge_in_progress(&merge_in_progress,
9982 worktree, repo);
9983 if (error)
9984 goto done;
9985 if (merge_in_progress) {
9986 error = got_error(GOT_ERR_MERGE_BUSY);
9987 goto done;
9990 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9991 if (error)
9992 goto done;
9994 if (abort_rebase) {
9995 if (!rebase_in_progress) {
9996 error = got_error(GOT_ERR_NOT_REBASING);
9997 goto done;
9999 error = got_worktree_rebase_continue(&resume_commit_id,
10000 &new_base_branch, &tmp_branch, &branch, &fileindex,
10001 worktree, repo);
10002 if (error)
10003 goto done;
10004 printf("Switching work tree to %s\n",
10005 got_ref_get_symref_target(new_base_branch));
10006 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10007 new_base_branch, abort_progress, &upa);
10008 if (error)
10009 goto done;
10010 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10011 print_merge_progress_stats(&upa);
10012 goto done; /* nothing else to do */
10015 if (continue_rebase) {
10016 if (!rebase_in_progress) {
10017 error = got_error(GOT_ERR_NOT_REBASING);
10018 goto done;
10020 error = got_worktree_rebase_continue(&resume_commit_id,
10021 &new_base_branch, &tmp_branch, &branch, &fileindex,
10022 worktree, repo);
10023 if (error)
10024 goto done;
10026 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10027 resume_commit_id, repo);
10028 if (error)
10029 goto done;
10031 yca_id = got_object_id_dup(resume_commit_id);
10032 if (yca_id == NULL) {
10033 error = got_error_from_errno("got_object_id_dup");
10034 goto done;
10036 } else {
10037 error = got_ref_open(&branch, repo, argv[0], 0);
10038 if (error != NULL)
10039 goto done;
10042 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10043 if (error)
10044 goto done;
10046 if (!continue_rebase) {
10047 struct got_object_id *base_commit_id;
10049 base_commit_id = got_worktree_get_base_commit_id(worktree);
10050 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10051 base_commit_id, branch_head_commit_id, 1, repo,
10052 check_cancelled, NULL);
10053 if (error)
10054 goto done;
10055 if (yca_id == NULL) {
10056 error = got_error_msg(GOT_ERR_ANCESTRY,
10057 "specified branch shares no common ancestry "
10058 "with work tree's branch");
10059 goto done;
10062 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10063 if (error) {
10064 if (error->code != GOT_ERR_ANCESTRY)
10065 goto done;
10066 error = NULL;
10067 } else {
10068 struct got_pathlist_head paths;
10069 printf("%s is already based on %s\n",
10070 got_ref_get_name(branch),
10071 got_worktree_get_head_ref_name(worktree));
10072 error = switch_head_ref(branch, branch_head_commit_id,
10073 worktree, repo);
10074 if (error)
10075 goto done;
10076 error = got_worktree_set_base_commit_id(worktree, repo,
10077 branch_head_commit_id);
10078 if (error)
10079 goto done;
10080 TAILQ_INIT(&paths);
10081 error = got_pathlist_append(&paths, "", NULL);
10082 if (error)
10083 goto done;
10084 error = got_worktree_checkout_files(worktree,
10085 &paths, repo, update_progress, &upa,
10086 check_cancelled, NULL);
10087 got_pathlist_free(&paths);
10088 if (error)
10089 goto done;
10090 if (upa.did_something) {
10091 char *id_str;
10092 error = got_object_id_str(&id_str,
10093 branch_head_commit_id);
10094 if (error)
10095 goto done;
10096 printf("Updated to %s: %s\n",
10097 got_worktree_get_head_ref_name(worktree),
10098 id_str);
10099 free(id_str);
10100 } else
10101 printf("Already up-to-date\n");
10102 print_update_progress_stats(&upa);
10103 goto done;
10107 commit_id = branch_head_commit_id;
10108 error = got_object_open_as_commit(&commit, repo, commit_id);
10109 if (error)
10110 goto done;
10112 parent_ids = got_object_commit_get_parent_ids(commit);
10113 pid = STAILQ_FIRST(parent_ids);
10114 if (pid == NULL) {
10115 error = got_error(GOT_ERR_EMPTY_REBASE);
10116 goto done;
10118 error = collect_commits(&commits, commit_id, &pid->id,
10119 yca_id, got_worktree_get_path_prefix(worktree),
10120 GOT_ERR_REBASE_PATH, repo);
10121 got_object_commit_close(commit);
10122 commit = NULL;
10123 if (error)
10124 goto done;
10126 if (!continue_rebase) {
10127 error = got_worktree_rebase_prepare(&new_base_branch,
10128 &tmp_branch, &fileindex, worktree, branch, repo);
10129 if (error)
10130 goto done;
10133 if (STAILQ_EMPTY(&commits)) {
10134 if (continue_rebase) {
10135 error = rebase_complete(worktree, fileindex,
10136 branch, new_base_branch, tmp_branch, repo,
10137 create_backup);
10138 goto done;
10139 } else {
10140 /* Fast-forward the reference of the branch. */
10141 struct got_object_id *new_head_commit_id;
10142 char *id_str;
10143 error = got_ref_resolve(&new_head_commit_id, repo,
10144 new_base_branch);
10145 if (error)
10146 goto done;
10147 error = got_object_id_str(&id_str, new_head_commit_id);
10148 printf("Forwarding %s to commit %s\n",
10149 got_ref_get_name(branch), id_str);
10150 free(id_str);
10151 error = got_ref_change_ref(branch,
10152 new_head_commit_id);
10153 if (error)
10154 goto done;
10155 /* No backup needed since objects did not change. */
10156 create_backup = 0;
10160 pid = NULL;
10161 STAILQ_FOREACH(qid, &commits, entry) {
10163 commit_id = &qid->id;
10164 parent_id = pid ? &pid->id : yca_id;
10165 pid = qid;
10167 memset(&upa, 0, sizeof(upa));
10168 error = got_worktree_rebase_merge_files(&merged_paths,
10169 worktree, fileindex, parent_id, commit_id, repo,
10170 update_progress, &upa, check_cancelled, NULL);
10171 if (error)
10172 goto done;
10174 print_merge_progress_stats(&upa);
10175 if (upa.conflicts > 0 || upa.missing > 0 ||
10176 upa.not_deleted > 0 || upa.unversioned > 0) {
10177 if (upa.conflicts > 0) {
10178 error = show_rebase_merge_conflict(&qid->id,
10179 repo);
10180 if (error)
10181 goto done;
10183 got_worktree_rebase_pathlist_free(&merged_paths);
10184 break;
10187 error = rebase_commit(&merged_paths, worktree, fileindex,
10188 tmp_branch, commit_id, repo);
10189 got_worktree_rebase_pathlist_free(&merged_paths);
10190 if (error)
10191 goto done;
10194 if (upa.conflicts > 0 || upa.missing > 0 ||
10195 upa.not_deleted > 0 || upa.unversioned > 0) {
10196 error = got_worktree_rebase_postpone(worktree, fileindex);
10197 if (error)
10198 goto done;
10199 if (upa.conflicts > 0 && upa.missing == 0 &&
10200 upa.not_deleted == 0 && upa.unversioned == 0) {
10201 error = got_error_msg(GOT_ERR_CONFLICTS,
10202 "conflicts must be resolved before rebasing "
10203 "can continue");
10204 } else if (upa.conflicts > 0) {
10205 error = got_error_msg(GOT_ERR_CONFLICTS,
10206 "conflicts must be resolved before rebasing "
10207 "can continue; changes destined for some "
10208 "files were not yet merged and should be "
10209 "merged manually if required before the "
10210 "rebase operation is continued");
10211 } else {
10212 error = got_error_msg(GOT_ERR_CONFLICTS,
10213 "changes destined for some files were not "
10214 "yet merged and should be merged manually "
10215 "if required before the rebase operation "
10216 "is continued");
10218 } else
10219 error = rebase_complete(worktree, fileindex, branch,
10220 new_base_branch, tmp_branch, repo, create_backup);
10221 done:
10222 got_object_id_queue_free(&commits);
10223 free(branch_head_commit_id);
10224 free(resume_commit_id);
10225 free(yca_id);
10226 if (commit)
10227 got_object_commit_close(commit);
10228 if (branch)
10229 got_ref_close(branch);
10230 if (new_base_branch)
10231 got_ref_close(new_base_branch);
10232 if (tmp_branch)
10233 got_ref_close(tmp_branch);
10234 if (worktree)
10235 got_worktree_close(worktree);
10236 if (repo) {
10237 const struct got_error *close_err = got_repo_close(repo);
10238 if (error == NULL)
10239 error = close_err;
10241 if (pack_fds) {
10242 const struct got_error *pack_err =
10243 got_repo_pack_fds_close(pack_fds);
10244 if (error == NULL)
10245 error = pack_err;
10247 return error;
10250 __dead static void
10251 usage_histedit(void)
10253 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10254 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10255 getprogname());
10256 exit(1);
10259 #define GOT_HISTEDIT_PICK 'p'
10260 #define GOT_HISTEDIT_EDIT 'e'
10261 #define GOT_HISTEDIT_FOLD 'f'
10262 #define GOT_HISTEDIT_DROP 'd'
10263 #define GOT_HISTEDIT_MESG 'm'
10265 static const struct got_histedit_cmd {
10266 unsigned char code;
10267 const char *name;
10268 const char *desc;
10269 } got_histedit_cmds[] = {
10270 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10271 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10272 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10273 "be used" },
10274 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10275 { GOT_HISTEDIT_MESG, "mesg",
10276 "single-line log message for commit above (open editor if empty)" },
10279 struct got_histedit_list_entry {
10280 TAILQ_ENTRY(got_histedit_list_entry) entry;
10281 struct got_object_id *commit_id;
10282 const struct got_histedit_cmd *cmd;
10283 char *logmsg;
10285 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10287 static const struct got_error *
10288 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10289 FILE *f, struct got_repository *repo)
10291 const struct got_error *err = NULL;
10292 char *logmsg = NULL, *id_str = NULL;
10293 struct got_commit_object *commit = NULL;
10294 int n;
10296 err = got_object_open_as_commit(&commit, repo, commit_id);
10297 if (err)
10298 goto done;
10300 err = get_short_logmsg(&logmsg, 34, commit);
10301 if (err)
10302 goto done;
10304 err = got_object_id_str(&id_str, commit_id);
10305 if (err)
10306 goto done;
10308 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10309 if (n < 0)
10310 err = got_ferror(f, GOT_ERR_IO);
10311 done:
10312 if (commit)
10313 got_object_commit_close(commit);
10314 free(id_str);
10315 free(logmsg);
10316 return err;
10319 static const struct got_error *
10320 histedit_write_commit_list(struct got_object_id_queue *commits,
10321 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10322 struct got_repository *repo)
10324 const struct got_error *err = NULL;
10325 struct got_object_qid *qid;
10326 const char *histedit_cmd = NULL;
10328 if (STAILQ_EMPTY(commits))
10329 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10331 STAILQ_FOREACH(qid, commits, entry) {
10332 histedit_cmd = got_histedit_cmds[0].name;
10333 if (edit_only)
10334 histedit_cmd = "edit";
10335 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10336 histedit_cmd = "fold";
10337 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10338 if (err)
10339 break;
10340 if (edit_logmsg_only) {
10341 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10342 if (n < 0) {
10343 err = got_ferror(f, GOT_ERR_IO);
10344 break;
10349 return err;
10352 static const struct got_error *
10353 write_cmd_list(FILE *f, const char *branch_name,
10354 struct got_object_id_queue *commits)
10356 const struct got_error *err = NULL;
10357 size_t i;
10358 int n;
10359 char *id_str;
10360 struct got_object_qid *qid;
10362 qid = STAILQ_FIRST(commits);
10363 err = got_object_id_str(&id_str, &qid->id);
10364 if (err)
10365 return err;
10367 n = fprintf(f,
10368 "# Editing the history of branch '%s' starting at\n"
10369 "# commit %s\n"
10370 "# Commits will be processed in order from top to "
10371 "bottom of this file.\n", branch_name, id_str);
10372 if (n < 0) {
10373 err = got_ferror(f, GOT_ERR_IO);
10374 goto done;
10377 n = fprintf(f, "# Available histedit commands:\n");
10378 if (n < 0) {
10379 err = got_ferror(f, GOT_ERR_IO);
10380 goto done;
10383 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10384 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10385 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10386 cmd->desc);
10387 if (n < 0) {
10388 err = got_ferror(f, GOT_ERR_IO);
10389 break;
10392 done:
10393 free(id_str);
10394 return err;
10397 static const struct got_error *
10398 histedit_syntax_error(int lineno)
10400 static char msg[42];
10401 int ret;
10403 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10404 lineno);
10405 if (ret == -1 || ret >= sizeof(msg))
10406 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10408 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10411 static const struct got_error *
10412 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10413 char *logmsg, struct got_repository *repo)
10415 const struct got_error *err;
10416 struct got_commit_object *folded_commit = NULL;
10417 char *id_str, *folded_logmsg = NULL;
10419 err = got_object_id_str(&id_str, hle->commit_id);
10420 if (err)
10421 return err;
10423 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10424 if (err)
10425 goto done;
10427 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10428 if (err)
10429 goto done;
10430 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10431 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10432 folded_logmsg) == -1) {
10433 err = got_error_from_errno("asprintf");
10435 done:
10436 if (folded_commit)
10437 got_object_commit_close(folded_commit);
10438 free(id_str);
10439 free(folded_logmsg);
10440 return err;
10443 static struct got_histedit_list_entry *
10444 get_folded_commits(struct got_histedit_list_entry *hle)
10446 struct got_histedit_list_entry *prev, *folded = NULL;
10448 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10449 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10450 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10451 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10452 folded = prev;
10453 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10456 return folded;
10459 static const struct got_error *
10460 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10461 struct got_repository *repo)
10463 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10464 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10465 const struct got_error *err = NULL;
10466 struct got_commit_object *commit = NULL;
10467 int logmsg_len;
10468 int fd;
10469 struct got_histedit_list_entry *folded = NULL;
10471 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10472 if (err)
10473 return err;
10475 folded = get_folded_commits(hle);
10476 if (folded) {
10477 while (folded != hle) {
10478 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10479 folded = TAILQ_NEXT(folded, entry);
10480 continue;
10482 err = append_folded_commit_msg(&new_msg, folded,
10483 logmsg, repo);
10484 if (err)
10485 goto done;
10486 free(logmsg);
10487 logmsg = new_msg;
10488 folded = TAILQ_NEXT(folded, entry);
10492 err = got_object_id_str(&id_str, hle->commit_id);
10493 if (err)
10494 goto done;
10495 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10496 if (err)
10497 goto done;
10498 logmsg_len = asprintf(&new_msg,
10499 "%s\n# original log message of commit %s: %s",
10500 logmsg ? logmsg : "", id_str, orig_logmsg);
10501 if (logmsg_len == -1) {
10502 err = got_error_from_errno("asprintf");
10503 goto done;
10505 free(logmsg);
10506 logmsg = new_msg;
10508 err = got_object_id_str(&id_str, hle->commit_id);
10509 if (err)
10510 goto done;
10512 err = got_opentemp_named_fd(&logmsg_path, &fd,
10513 GOT_TMPDIR_STR "/got-logmsg");
10514 if (err)
10515 goto done;
10517 write(fd, logmsg, logmsg_len);
10518 close(fd);
10520 err = get_editor(&editor);
10521 if (err)
10522 goto done;
10524 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10525 logmsg_len, 0);
10526 if (err) {
10527 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10528 goto done;
10529 err = NULL;
10530 hle->logmsg = strdup(new_msg);
10531 if (hle->logmsg == NULL)
10532 err = got_error_from_errno("strdup");
10534 done:
10535 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10536 err = got_error_from_errno2("unlink", logmsg_path);
10537 free(logmsg_path);
10538 free(logmsg);
10539 free(orig_logmsg);
10540 free(editor);
10541 if (commit)
10542 got_object_commit_close(commit);
10543 return err;
10546 static const struct got_error *
10547 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10548 FILE *f, struct got_repository *repo)
10550 const struct got_error *err = NULL;
10551 char *line = NULL, *p, *end;
10552 size_t i, size;
10553 ssize_t len;
10554 int lineno = 0;
10555 const struct got_histedit_cmd *cmd;
10556 struct got_object_id *commit_id = NULL;
10557 struct got_histedit_list_entry *hle = NULL;
10559 for (;;) {
10560 len = getline(&line, &size, f);
10561 if (len == -1) {
10562 const struct got_error *getline_err;
10563 if (feof(f))
10564 break;
10565 getline_err = got_error_from_errno("getline");
10566 err = got_ferror(f, getline_err->code);
10567 break;
10569 lineno++;
10570 p = line;
10571 while (isspace((unsigned char)p[0]))
10572 p++;
10573 if (p[0] == '#' || p[0] == '\0') {
10574 free(line);
10575 line = NULL;
10576 continue;
10578 cmd = NULL;
10579 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10580 cmd = &got_histedit_cmds[i];
10581 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10582 isspace((unsigned char)p[strlen(cmd->name)])) {
10583 p += strlen(cmd->name);
10584 break;
10586 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10587 p++;
10588 break;
10591 if (i == nitems(got_histedit_cmds)) {
10592 err = histedit_syntax_error(lineno);
10593 break;
10595 while (isspace((unsigned char)p[0]))
10596 p++;
10597 if (cmd->code == GOT_HISTEDIT_MESG) {
10598 if (hle == NULL || hle->logmsg != NULL) {
10599 err = got_error(GOT_ERR_HISTEDIT_CMD);
10600 break;
10602 if (p[0] == '\0') {
10603 err = histedit_edit_logmsg(hle, repo);
10604 if (err)
10605 break;
10606 } else {
10607 hle->logmsg = strdup(p);
10608 if (hle->logmsg == NULL) {
10609 err = got_error_from_errno("strdup");
10610 break;
10613 free(line);
10614 line = NULL;
10615 continue;
10616 } else {
10617 end = p;
10618 while (end[0] && !isspace((unsigned char)end[0]))
10619 end++;
10620 *end = '\0';
10622 err = got_object_resolve_id_str(&commit_id, repo, p);
10623 if (err) {
10624 /* override error code */
10625 err = histedit_syntax_error(lineno);
10626 break;
10629 hle = malloc(sizeof(*hle));
10630 if (hle == NULL) {
10631 err = got_error_from_errno("malloc");
10632 break;
10634 hle->cmd = cmd;
10635 hle->commit_id = commit_id;
10636 hle->logmsg = NULL;
10637 commit_id = NULL;
10638 free(line);
10639 line = NULL;
10640 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10643 free(line);
10644 free(commit_id);
10645 return err;
10648 static const struct got_error *
10649 histedit_check_script(struct got_histedit_list *histedit_cmds,
10650 struct got_object_id_queue *commits, struct got_repository *repo)
10652 const struct got_error *err = NULL;
10653 struct got_object_qid *qid;
10654 struct got_histedit_list_entry *hle;
10655 static char msg[92];
10656 char *id_str;
10658 if (TAILQ_EMPTY(histedit_cmds))
10659 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10660 "histedit script contains no commands");
10661 if (STAILQ_EMPTY(commits))
10662 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10664 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10665 struct got_histedit_list_entry *hle2;
10666 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10667 if (hle == hle2)
10668 continue;
10669 if (got_object_id_cmp(hle->commit_id,
10670 hle2->commit_id) != 0)
10671 continue;
10672 err = got_object_id_str(&id_str, hle->commit_id);
10673 if (err)
10674 return err;
10675 snprintf(msg, sizeof(msg), "commit %s is listed "
10676 "more than once in histedit script", id_str);
10677 free(id_str);
10678 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10682 STAILQ_FOREACH(qid, commits, entry) {
10683 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10684 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10685 break;
10687 if (hle == NULL) {
10688 err = got_object_id_str(&id_str, &qid->id);
10689 if (err)
10690 return err;
10691 snprintf(msg, sizeof(msg),
10692 "commit %s missing from histedit script", id_str);
10693 free(id_str);
10694 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10698 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10699 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10700 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10701 "last commit in histedit script cannot be folded");
10703 return NULL;
10706 static const struct got_error *
10707 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10708 const char *path, struct got_object_id_queue *commits,
10709 struct got_repository *repo)
10711 const struct got_error *err = NULL;
10712 char *editor;
10713 FILE *f = NULL;
10715 err = get_editor(&editor);
10716 if (err)
10717 return err;
10719 if (spawn_editor(editor, path) == -1) {
10720 err = got_error_from_errno("failed spawning editor");
10721 goto done;
10724 f = fopen(path, "re");
10725 if (f == NULL) {
10726 err = got_error_from_errno("fopen");
10727 goto done;
10729 err = histedit_parse_list(histedit_cmds, f, repo);
10730 if (err)
10731 goto done;
10733 err = histedit_check_script(histedit_cmds, commits, repo);
10734 done:
10735 if (f && fclose(f) == EOF && err == NULL)
10736 err = got_error_from_errno("fclose");
10737 free(editor);
10738 return err;
10741 static const struct got_error *
10742 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10743 struct got_object_id_queue *, const char *, const char *,
10744 struct got_repository *);
10746 static const struct got_error *
10747 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10748 struct got_object_id_queue *commits, const char *branch_name,
10749 int edit_logmsg_only, int fold_only, int edit_only,
10750 struct got_repository *repo)
10752 const struct got_error *err;
10753 FILE *f = NULL;
10754 char *path = NULL;
10756 err = got_opentemp_named(&path, &f, "got-histedit");
10757 if (err)
10758 return err;
10760 err = write_cmd_list(f, branch_name, commits);
10761 if (err)
10762 goto done;
10764 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10765 fold_only, edit_only, repo);
10766 if (err)
10767 goto done;
10769 if (edit_logmsg_only || fold_only || edit_only) {
10770 rewind(f);
10771 err = histedit_parse_list(histedit_cmds, f, repo);
10772 } else {
10773 if (fclose(f) == EOF) {
10774 err = got_error_from_errno("fclose");
10775 goto done;
10777 f = NULL;
10778 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10779 if (err) {
10780 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10781 err->code != GOT_ERR_HISTEDIT_CMD)
10782 goto done;
10783 err = histedit_edit_list_retry(histedit_cmds, err,
10784 commits, path, branch_name, repo);
10787 done:
10788 if (f && fclose(f) == EOF && err == NULL)
10789 err = got_error_from_errno("fclose");
10790 if (path && unlink(path) != 0 && err == NULL)
10791 err = got_error_from_errno2("unlink", path);
10792 free(path);
10793 return err;
10796 static const struct got_error *
10797 histedit_save_list(struct got_histedit_list *histedit_cmds,
10798 struct got_worktree *worktree, struct got_repository *repo)
10800 const struct got_error *err = NULL;
10801 char *path = NULL;
10802 FILE *f = NULL;
10803 struct got_histedit_list_entry *hle;
10804 struct got_commit_object *commit = NULL;
10806 err = got_worktree_get_histedit_script_path(&path, worktree);
10807 if (err)
10808 return err;
10810 f = fopen(path, "we");
10811 if (f == NULL) {
10812 err = got_error_from_errno2("fopen", path);
10813 goto done;
10815 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10816 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10817 repo);
10818 if (err)
10819 break;
10821 if (hle->logmsg) {
10822 int n = fprintf(f, "%c %s\n",
10823 GOT_HISTEDIT_MESG, hle->logmsg);
10824 if (n < 0) {
10825 err = got_ferror(f, GOT_ERR_IO);
10826 break;
10830 done:
10831 if (f && fclose(f) == EOF && err == NULL)
10832 err = got_error_from_errno("fclose");
10833 free(path);
10834 if (commit)
10835 got_object_commit_close(commit);
10836 return err;
10839 static void
10840 histedit_free_list(struct got_histedit_list *histedit_cmds)
10842 struct got_histedit_list_entry *hle;
10844 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10845 TAILQ_REMOVE(histedit_cmds, hle, entry);
10846 free(hle);
10850 static const struct got_error *
10851 histedit_load_list(struct got_histedit_list *histedit_cmds,
10852 const char *path, struct got_repository *repo)
10854 const struct got_error *err = NULL;
10855 FILE *f = NULL;
10857 f = fopen(path, "re");
10858 if (f == NULL) {
10859 err = got_error_from_errno2("fopen", path);
10860 goto done;
10863 err = histedit_parse_list(histedit_cmds, f, repo);
10864 done:
10865 if (f && fclose(f) == EOF && err == NULL)
10866 err = got_error_from_errno("fclose");
10867 return err;
10870 static const struct got_error *
10871 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10872 const struct got_error *edit_err, struct got_object_id_queue *commits,
10873 const char *path, const char *branch_name, struct got_repository *repo)
10875 const struct got_error *err = NULL, *prev_err = edit_err;
10876 int resp = ' ';
10878 while (resp != 'c' && resp != 'r' && resp != 'a') {
10879 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10880 "or (a)bort: ", getprogname(), prev_err->msg);
10881 resp = getchar();
10882 if (resp == '\n')
10883 resp = getchar();
10884 if (resp == 'c') {
10885 histedit_free_list(histedit_cmds);
10886 err = histedit_run_editor(histedit_cmds, path, commits,
10887 repo);
10888 if (err) {
10889 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10890 err->code != GOT_ERR_HISTEDIT_CMD)
10891 break;
10892 prev_err = err;
10893 resp = ' ';
10894 continue;
10896 break;
10897 } else if (resp == 'r') {
10898 histedit_free_list(histedit_cmds);
10899 err = histedit_edit_script(histedit_cmds,
10900 commits, branch_name, 0, 0, 0, repo);
10901 if (err) {
10902 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10903 err->code != GOT_ERR_HISTEDIT_CMD)
10904 break;
10905 prev_err = err;
10906 resp = ' ';
10907 continue;
10909 break;
10910 } else if (resp == 'a') {
10911 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10912 break;
10913 } else
10914 printf("invalid response '%c'\n", resp);
10917 return err;
10920 static const struct got_error *
10921 histedit_complete(struct got_worktree *worktree,
10922 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10923 struct got_reference *branch, struct got_repository *repo)
10925 printf("Switching work tree to %s\n",
10926 got_ref_get_symref_target(branch));
10927 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10928 branch, repo);
10931 static const struct got_error *
10932 show_histedit_progress(struct got_commit_object *commit,
10933 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10935 const struct got_error *err;
10936 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10938 err = got_object_id_str(&old_id_str, hle->commit_id);
10939 if (err)
10940 goto done;
10942 if (new_id) {
10943 err = got_object_id_str(&new_id_str, new_id);
10944 if (err)
10945 goto done;
10948 old_id_str[12] = '\0';
10949 if (new_id_str)
10950 new_id_str[12] = '\0';
10952 if (hle->logmsg) {
10953 logmsg = strdup(hle->logmsg);
10954 if (logmsg == NULL) {
10955 err = got_error_from_errno("strdup");
10956 goto done;
10958 trim_logmsg(logmsg, 42);
10959 } else {
10960 err = get_short_logmsg(&logmsg, 42, commit);
10961 if (err)
10962 goto done;
10965 switch (hle->cmd->code) {
10966 case GOT_HISTEDIT_PICK:
10967 case GOT_HISTEDIT_EDIT:
10968 printf("%s -> %s: %s\n", old_id_str,
10969 new_id_str ? new_id_str : "no-op change", logmsg);
10970 break;
10971 case GOT_HISTEDIT_DROP:
10972 case GOT_HISTEDIT_FOLD:
10973 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10974 logmsg);
10975 break;
10976 default:
10977 break;
10979 done:
10980 free(old_id_str);
10981 free(new_id_str);
10982 return err;
10985 static const struct got_error *
10986 histedit_commit(struct got_pathlist_head *merged_paths,
10987 struct got_worktree *worktree, struct got_fileindex *fileindex,
10988 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10989 struct got_repository *repo)
10991 const struct got_error *err;
10992 struct got_commit_object *commit;
10993 struct got_object_id *new_commit_id;
10995 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10996 && hle->logmsg == NULL) {
10997 err = histedit_edit_logmsg(hle, repo);
10998 if (err)
10999 return err;
11002 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11003 if (err)
11004 return err;
11006 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11007 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11008 hle->logmsg, repo);
11009 if (err) {
11010 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11011 goto done;
11012 err = show_histedit_progress(commit, hle, NULL);
11013 } else {
11014 err = show_histedit_progress(commit, hle, new_commit_id);
11015 free(new_commit_id);
11017 done:
11018 got_object_commit_close(commit);
11019 return err;
11022 static const struct got_error *
11023 histedit_skip_commit(struct got_histedit_list_entry *hle,
11024 struct got_worktree *worktree, struct got_repository *repo)
11026 const struct got_error *error;
11027 struct got_commit_object *commit;
11029 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11030 repo);
11031 if (error)
11032 return error;
11034 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11035 if (error)
11036 return error;
11038 error = show_histedit_progress(commit, hle, NULL);
11039 got_object_commit_close(commit);
11040 return error;
11043 static const struct got_error *
11044 check_local_changes(void *arg, unsigned char status,
11045 unsigned char staged_status, const char *path,
11046 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11047 struct got_object_id *commit_id, int dirfd, const char *de_name)
11049 int *have_local_changes = arg;
11051 switch (status) {
11052 case GOT_STATUS_ADD:
11053 case GOT_STATUS_DELETE:
11054 case GOT_STATUS_MODIFY:
11055 case GOT_STATUS_CONFLICT:
11056 *have_local_changes = 1;
11057 return got_error(GOT_ERR_CANCELLED);
11058 default:
11059 break;
11062 switch (staged_status) {
11063 case GOT_STATUS_ADD:
11064 case GOT_STATUS_DELETE:
11065 case GOT_STATUS_MODIFY:
11066 *have_local_changes = 1;
11067 return got_error(GOT_ERR_CANCELLED);
11068 default:
11069 break;
11072 return NULL;
11075 static const struct got_error *
11076 cmd_histedit(int argc, char *argv[])
11078 const struct got_error *error = NULL;
11079 struct got_worktree *worktree = NULL;
11080 struct got_fileindex *fileindex = NULL;
11081 struct got_repository *repo = NULL;
11082 char *cwd = NULL;
11083 struct got_reference *branch = NULL;
11084 struct got_reference *tmp_branch = NULL;
11085 struct got_object_id *resume_commit_id = NULL;
11086 struct got_object_id *base_commit_id = NULL;
11087 struct got_object_id *head_commit_id = NULL;
11088 struct got_commit_object *commit = NULL;
11089 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11090 struct got_update_progress_arg upa;
11091 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11092 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11093 int list_backups = 0, delete_backups = 0;
11094 const char *edit_script_path = NULL;
11095 struct got_object_id_queue commits;
11096 struct got_pathlist_head merged_paths;
11097 const struct got_object_id_queue *parent_ids;
11098 struct got_object_qid *pid;
11099 struct got_histedit_list histedit_cmds;
11100 struct got_histedit_list_entry *hle;
11101 int *pack_fds = NULL;
11103 STAILQ_INIT(&commits);
11104 TAILQ_INIT(&histedit_cmds);
11105 TAILQ_INIT(&merged_paths);
11106 memset(&upa, 0, sizeof(upa));
11108 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11109 switch (ch) {
11110 case 'a':
11111 abort_edit = 1;
11112 break;
11113 case 'c':
11114 continue_edit = 1;
11115 break;
11116 case 'e':
11117 edit_only = 1;
11118 break;
11119 case 'f':
11120 fold_only = 1;
11121 break;
11122 case 'F':
11123 edit_script_path = optarg;
11124 break;
11125 case 'm':
11126 edit_logmsg_only = 1;
11127 break;
11128 case 'l':
11129 list_backups = 1;
11130 break;
11131 case 'X':
11132 delete_backups = 1;
11133 break;
11134 default:
11135 usage_histedit();
11136 /* NOTREACHED */
11140 argc -= optind;
11141 argv += optind;
11143 #ifndef PROFILE
11144 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11145 "unveil", NULL) == -1)
11146 err(1, "pledge");
11147 #endif
11148 if (abort_edit && continue_edit)
11149 option_conflict('a', 'c');
11150 if (edit_script_path && edit_logmsg_only)
11151 option_conflict('F', 'm');
11152 if (abort_edit && edit_logmsg_only)
11153 option_conflict('a', 'm');
11154 if (continue_edit && edit_logmsg_only)
11155 option_conflict('c', 'm');
11156 if (abort_edit && fold_only)
11157 option_conflict('a', 'f');
11158 if (continue_edit && fold_only)
11159 option_conflict('c', 'f');
11160 if (fold_only && edit_logmsg_only)
11161 option_conflict('f', 'm');
11162 if (edit_script_path && fold_only)
11163 option_conflict('F', 'f');
11164 if (abort_edit && edit_only)
11165 option_conflict('a', 'e');
11166 if (continue_edit && edit_only)
11167 option_conflict('c', 'e');
11168 if (edit_only && edit_logmsg_only)
11169 option_conflict('e', 'm');
11170 if (edit_script_path && edit_only)
11171 option_conflict('F', 'e');
11172 if (list_backups) {
11173 if (abort_edit)
11174 option_conflict('l', 'a');
11175 if (continue_edit)
11176 option_conflict('l', 'c');
11177 if (edit_script_path)
11178 option_conflict('l', 'F');
11179 if (edit_logmsg_only)
11180 option_conflict('l', 'm');
11181 if (fold_only)
11182 option_conflict('l', 'f');
11183 if (edit_only)
11184 option_conflict('l', 'e');
11185 if (delete_backups)
11186 option_conflict('l', 'X');
11187 if (argc != 0 && argc != 1)
11188 usage_histedit();
11189 } else if (delete_backups) {
11190 if (abort_edit)
11191 option_conflict('X', 'a');
11192 if (continue_edit)
11193 option_conflict('X', 'c');
11194 if (edit_script_path)
11195 option_conflict('X', 'F');
11196 if (edit_logmsg_only)
11197 option_conflict('X', 'm');
11198 if (fold_only)
11199 option_conflict('X', 'f');
11200 if (edit_only)
11201 option_conflict('X', 'e');
11202 if (list_backups)
11203 option_conflict('X', 'l');
11204 if (argc != 0 && argc != 1)
11205 usage_histedit();
11206 } else if (argc != 0)
11207 usage_histedit();
11210 * This command cannot apply unveil(2) in all cases because the
11211 * user may choose to run an editor to edit the histedit script
11212 * and to edit individual commit log messages.
11213 * unveil(2) traverses exec(2); if an editor is used we have to
11214 * apply unveil after edit script and log messages have been written.
11215 * XXX TODO: Make use of unveil(2) where possible.
11218 cwd = getcwd(NULL, 0);
11219 if (cwd == NULL) {
11220 error = got_error_from_errno("getcwd");
11221 goto done;
11224 error = got_repo_pack_fds_open(&pack_fds);
11225 if (error != NULL)
11226 goto done;
11228 error = got_worktree_open(&worktree, cwd);
11229 if (error) {
11230 if (list_backups || delete_backups) {
11231 if (error->code != GOT_ERR_NOT_WORKTREE)
11232 goto done;
11233 } else {
11234 if (error->code == GOT_ERR_NOT_WORKTREE)
11235 error = wrap_not_worktree_error(error,
11236 "histedit", cwd);
11237 goto done;
11241 if (list_backups || delete_backups) {
11242 error = got_repo_open(&repo,
11243 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11244 NULL, pack_fds);
11245 if (error != NULL)
11246 goto done;
11247 error = apply_unveil(got_repo_get_path(repo), 0,
11248 worktree ? got_worktree_get_root_path(worktree) : NULL);
11249 if (error)
11250 goto done;
11251 error = process_backup_refs(
11252 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11253 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11254 goto done; /* nothing else to do */
11257 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11258 NULL, pack_fds);
11259 if (error != NULL)
11260 goto done;
11262 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11263 if (error)
11264 goto done;
11265 if (rebase_in_progress) {
11266 error = got_error(GOT_ERR_REBASING);
11267 goto done;
11270 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11271 repo);
11272 if (error)
11273 goto done;
11274 if (merge_in_progress) {
11275 error = got_error(GOT_ERR_MERGE_BUSY);
11276 goto done;
11279 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11280 if (error)
11281 goto done;
11283 if (edit_in_progress && edit_logmsg_only) {
11284 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11285 "histedit operation is in progress in this "
11286 "work tree and must be continued or aborted "
11287 "before the -m option can be used");
11288 goto done;
11290 if (edit_in_progress && fold_only) {
11291 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11292 "histedit operation is in progress in this "
11293 "work tree and must be continued or aborted "
11294 "before the -f option can be used");
11295 goto done;
11297 if (edit_in_progress && edit_only) {
11298 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11299 "histedit operation is in progress in this "
11300 "work tree and must be continued or aborted "
11301 "before the -e option can be used");
11302 goto done;
11305 if (edit_in_progress && abort_edit) {
11306 error = got_worktree_histedit_continue(&resume_commit_id,
11307 &tmp_branch, &branch, &base_commit_id, &fileindex,
11308 worktree, repo);
11309 if (error)
11310 goto done;
11311 printf("Switching work tree to %s\n",
11312 got_ref_get_symref_target(branch));
11313 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11314 branch, base_commit_id, abort_progress, &upa);
11315 if (error)
11316 goto done;
11317 printf("Histedit of %s aborted\n",
11318 got_ref_get_symref_target(branch));
11319 print_merge_progress_stats(&upa);
11320 goto done; /* nothing else to do */
11321 } else if (abort_edit) {
11322 error = got_error(GOT_ERR_NOT_HISTEDIT);
11323 goto done;
11326 if (continue_edit) {
11327 char *path;
11329 if (!edit_in_progress) {
11330 error = got_error(GOT_ERR_NOT_HISTEDIT);
11331 goto done;
11334 error = got_worktree_get_histedit_script_path(&path, worktree);
11335 if (error)
11336 goto done;
11338 error = histedit_load_list(&histedit_cmds, path, repo);
11339 free(path);
11340 if (error)
11341 goto done;
11343 error = got_worktree_histedit_continue(&resume_commit_id,
11344 &tmp_branch, &branch, &base_commit_id, &fileindex,
11345 worktree, repo);
11346 if (error)
11347 goto done;
11349 error = got_ref_resolve(&head_commit_id, repo, branch);
11350 if (error)
11351 goto done;
11353 error = got_object_open_as_commit(&commit, repo,
11354 head_commit_id);
11355 if (error)
11356 goto done;
11357 parent_ids = got_object_commit_get_parent_ids(commit);
11358 pid = STAILQ_FIRST(parent_ids);
11359 if (pid == NULL) {
11360 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11361 goto done;
11363 error = collect_commits(&commits, head_commit_id, &pid->id,
11364 base_commit_id, got_worktree_get_path_prefix(worktree),
11365 GOT_ERR_HISTEDIT_PATH, repo);
11366 got_object_commit_close(commit);
11367 commit = NULL;
11368 if (error)
11369 goto done;
11370 } else {
11371 if (edit_in_progress) {
11372 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11373 goto done;
11376 error = got_ref_open(&branch, repo,
11377 got_worktree_get_head_ref_name(worktree), 0);
11378 if (error != NULL)
11379 goto done;
11381 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11382 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11383 "will not edit commit history of a branch outside "
11384 "the \"refs/heads/\" reference namespace");
11385 goto done;
11388 error = got_ref_resolve(&head_commit_id, repo, branch);
11389 got_ref_close(branch);
11390 branch = NULL;
11391 if (error)
11392 goto done;
11394 error = got_object_open_as_commit(&commit, repo,
11395 head_commit_id);
11396 if (error)
11397 goto done;
11398 parent_ids = got_object_commit_get_parent_ids(commit);
11399 pid = STAILQ_FIRST(parent_ids);
11400 if (pid == NULL) {
11401 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11402 goto done;
11404 error = collect_commits(&commits, head_commit_id, &pid->id,
11405 got_worktree_get_base_commit_id(worktree),
11406 got_worktree_get_path_prefix(worktree),
11407 GOT_ERR_HISTEDIT_PATH, repo);
11408 got_object_commit_close(commit);
11409 commit = NULL;
11410 if (error)
11411 goto done;
11413 if (STAILQ_EMPTY(&commits)) {
11414 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11415 goto done;
11418 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11419 &base_commit_id, &fileindex, worktree, repo);
11420 if (error)
11421 goto done;
11423 if (edit_script_path) {
11424 error = histedit_load_list(&histedit_cmds,
11425 edit_script_path, repo);
11426 if (error) {
11427 got_worktree_histedit_abort(worktree, fileindex,
11428 repo, branch, base_commit_id,
11429 abort_progress, &upa);
11430 print_merge_progress_stats(&upa);
11431 goto done;
11433 } else {
11434 const char *branch_name;
11435 branch_name = got_ref_get_symref_target(branch);
11436 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11437 branch_name += 11;
11438 error = histedit_edit_script(&histedit_cmds, &commits,
11439 branch_name, edit_logmsg_only, fold_only,
11440 edit_only, repo);
11441 if (error) {
11442 got_worktree_histedit_abort(worktree, fileindex,
11443 repo, branch, base_commit_id,
11444 abort_progress, &upa);
11445 print_merge_progress_stats(&upa);
11446 goto done;
11451 error = histedit_save_list(&histedit_cmds, worktree,
11452 repo);
11453 if (error) {
11454 got_worktree_histedit_abort(worktree, fileindex,
11455 repo, branch, base_commit_id,
11456 abort_progress, &upa);
11457 print_merge_progress_stats(&upa);
11458 goto done;
11463 error = histedit_check_script(&histedit_cmds, &commits, repo);
11464 if (error)
11465 goto done;
11467 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11468 if (resume_commit_id) {
11469 if (got_object_id_cmp(hle->commit_id,
11470 resume_commit_id) != 0)
11471 continue;
11473 resume_commit_id = NULL;
11474 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11475 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11476 error = histedit_skip_commit(hle, worktree,
11477 repo);
11478 if (error)
11479 goto done;
11480 } else {
11481 struct got_pathlist_head paths;
11482 int have_changes = 0;
11484 TAILQ_INIT(&paths);
11485 error = got_pathlist_append(&paths, "", NULL);
11486 if (error)
11487 goto done;
11488 error = got_worktree_status(worktree, &paths,
11489 repo, 0, check_local_changes, &have_changes,
11490 check_cancelled, NULL);
11491 got_pathlist_free(&paths);
11492 if (error) {
11493 if (error->code != GOT_ERR_CANCELLED)
11494 goto done;
11495 if (sigint_received || sigpipe_received)
11496 goto done;
11498 if (have_changes) {
11499 error = histedit_commit(NULL, worktree,
11500 fileindex, tmp_branch, hle, repo);
11501 if (error)
11502 goto done;
11503 } else {
11504 error = got_object_open_as_commit(
11505 &commit, repo, hle->commit_id);
11506 if (error)
11507 goto done;
11508 error = show_histedit_progress(commit,
11509 hle, NULL);
11510 got_object_commit_close(commit);
11511 commit = NULL;
11512 if (error)
11513 goto done;
11516 continue;
11519 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11520 error = histedit_skip_commit(hle, worktree, repo);
11521 if (error)
11522 goto done;
11523 continue;
11526 error = got_object_open_as_commit(&commit, repo,
11527 hle->commit_id);
11528 if (error)
11529 goto done;
11530 parent_ids = got_object_commit_get_parent_ids(commit);
11531 pid = STAILQ_FIRST(parent_ids);
11533 error = got_worktree_histedit_merge_files(&merged_paths,
11534 worktree, fileindex, &pid->id, hle->commit_id, repo,
11535 update_progress, &upa, check_cancelled, NULL);
11536 if (error)
11537 goto done;
11538 got_object_commit_close(commit);
11539 commit = NULL;
11541 print_merge_progress_stats(&upa);
11542 if (upa.conflicts > 0 || upa.missing > 0 ||
11543 upa.not_deleted > 0 || upa.unversioned > 0) {
11544 if (upa.conflicts > 0) {
11545 error = show_rebase_merge_conflict(
11546 hle->commit_id, repo);
11547 if (error)
11548 goto done;
11550 got_worktree_rebase_pathlist_free(&merged_paths);
11551 break;
11554 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11555 char *id_str;
11556 error = got_object_id_str(&id_str, hle->commit_id);
11557 if (error)
11558 goto done;
11559 printf("Stopping histedit for amending commit %s\n",
11560 id_str);
11561 free(id_str);
11562 got_worktree_rebase_pathlist_free(&merged_paths);
11563 error = got_worktree_histedit_postpone(worktree,
11564 fileindex);
11565 goto done;
11568 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11569 error = histedit_skip_commit(hle, worktree, repo);
11570 if (error)
11571 goto done;
11572 continue;
11575 error = histedit_commit(&merged_paths, worktree, fileindex,
11576 tmp_branch, hle, repo);
11577 got_worktree_rebase_pathlist_free(&merged_paths);
11578 if (error)
11579 goto done;
11582 if (upa.conflicts > 0 || upa.missing > 0 ||
11583 upa.not_deleted > 0 || upa.unversioned > 0) {
11584 error = got_worktree_histedit_postpone(worktree, fileindex);
11585 if (error)
11586 goto done;
11587 if (upa.conflicts > 0 && upa.missing == 0 &&
11588 upa.not_deleted == 0 && upa.unversioned == 0) {
11589 error = got_error_msg(GOT_ERR_CONFLICTS,
11590 "conflicts must be resolved before histedit "
11591 "can continue");
11592 } else if (upa.conflicts > 0) {
11593 error = got_error_msg(GOT_ERR_CONFLICTS,
11594 "conflicts must be resolved before histedit "
11595 "can continue; changes destined for some "
11596 "files were not yet merged and should be "
11597 "merged manually if required before the "
11598 "histedit operation is continued");
11599 } else {
11600 error = got_error_msg(GOT_ERR_CONFLICTS,
11601 "changes destined for some files were not "
11602 "yet merged and should be merged manually "
11603 "if required before the histedit operation "
11604 "is continued");
11606 } else
11607 error = histedit_complete(worktree, fileindex, tmp_branch,
11608 branch, repo);
11609 done:
11610 got_object_id_queue_free(&commits);
11611 histedit_free_list(&histedit_cmds);
11612 free(head_commit_id);
11613 free(base_commit_id);
11614 free(resume_commit_id);
11615 if (commit)
11616 got_object_commit_close(commit);
11617 if (branch)
11618 got_ref_close(branch);
11619 if (tmp_branch)
11620 got_ref_close(tmp_branch);
11621 if (worktree)
11622 got_worktree_close(worktree);
11623 if (repo) {
11624 const struct got_error *close_err = got_repo_close(repo);
11625 if (error == NULL)
11626 error = close_err;
11628 if (pack_fds) {
11629 const struct got_error *pack_err =
11630 got_repo_pack_fds_close(pack_fds);
11631 if (error == NULL)
11632 error = pack_err;
11634 return error;
11637 __dead static void
11638 usage_integrate(void)
11640 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11641 exit(1);
11644 static const struct got_error *
11645 cmd_integrate(int argc, char *argv[])
11647 const struct got_error *error = NULL;
11648 struct got_repository *repo = NULL;
11649 struct got_worktree *worktree = NULL;
11650 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11651 const char *branch_arg = NULL;
11652 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11653 struct got_fileindex *fileindex = NULL;
11654 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11655 int ch;
11656 struct got_update_progress_arg upa;
11657 int *pack_fds = NULL;
11659 while ((ch = getopt(argc, argv, "")) != -1) {
11660 switch (ch) {
11661 default:
11662 usage_integrate();
11663 /* NOTREACHED */
11667 argc -= optind;
11668 argv += optind;
11670 if (argc != 1)
11671 usage_integrate();
11672 branch_arg = argv[0];
11673 #ifndef PROFILE
11674 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11675 "unveil", NULL) == -1)
11676 err(1, "pledge");
11677 #endif
11678 cwd = getcwd(NULL, 0);
11679 if (cwd == NULL) {
11680 error = got_error_from_errno("getcwd");
11681 goto done;
11684 error = got_repo_pack_fds_open(&pack_fds);
11685 if (error != NULL)
11686 goto done;
11688 error = got_worktree_open(&worktree, cwd);
11689 if (error) {
11690 if (error->code == GOT_ERR_NOT_WORKTREE)
11691 error = wrap_not_worktree_error(error, "integrate",
11692 cwd);
11693 goto done;
11696 error = check_rebase_or_histedit_in_progress(worktree);
11697 if (error)
11698 goto done;
11700 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11701 NULL, pack_fds);
11702 if (error != NULL)
11703 goto done;
11705 error = apply_unveil(got_repo_get_path(repo), 0,
11706 got_worktree_get_root_path(worktree));
11707 if (error)
11708 goto done;
11710 error = check_merge_in_progress(worktree, repo);
11711 if (error)
11712 goto done;
11714 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11715 error = got_error_from_errno("asprintf");
11716 goto done;
11719 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11720 &base_branch_ref, worktree, refname, repo);
11721 if (error)
11722 goto done;
11724 refname = strdup(got_ref_get_name(branch_ref));
11725 if (refname == NULL) {
11726 error = got_error_from_errno("strdup");
11727 got_worktree_integrate_abort(worktree, fileindex, repo,
11728 branch_ref, base_branch_ref);
11729 goto done;
11731 base_refname = strdup(got_ref_get_name(base_branch_ref));
11732 if (base_refname == NULL) {
11733 error = got_error_from_errno("strdup");
11734 got_worktree_integrate_abort(worktree, fileindex, repo,
11735 branch_ref, base_branch_ref);
11736 goto done;
11739 error = got_ref_resolve(&commit_id, repo, branch_ref);
11740 if (error)
11741 goto done;
11743 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11744 if (error)
11745 goto done;
11747 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11748 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11749 "specified branch has already been integrated");
11750 got_worktree_integrate_abort(worktree, fileindex, repo,
11751 branch_ref, base_branch_ref);
11752 goto done;
11755 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11756 if (error) {
11757 if (error->code == GOT_ERR_ANCESTRY)
11758 error = got_error(GOT_ERR_REBASE_REQUIRED);
11759 got_worktree_integrate_abort(worktree, fileindex, repo,
11760 branch_ref, base_branch_ref);
11761 goto done;
11764 memset(&upa, 0, sizeof(upa));
11765 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11766 branch_ref, base_branch_ref, update_progress, &upa,
11767 check_cancelled, NULL);
11768 if (error)
11769 goto done;
11771 printf("Integrated %s into %s\n", refname, base_refname);
11772 print_update_progress_stats(&upa);
11773 done:
11774 if (repo) {
11775 const struct got_error *close_err = got_repo_close(repo);
11776 if (error == NULL)
11777 error = close_err;
11779 if (worktree)
11780 got_worktree_close(worktree);
11781 if (pack_fds) {
11782 const struct got_error *pack_err =
11783 got_repo_pack_fds_close(pack_fds);
11784 if (error == NULL)
11785 error = pack_err;
11787 free(cwd);
11788 free(base_commit_id);
11789 free(commit_id);
11790 free(refname);
11791 free(base_refname);
11792 return error;
11795 __dead static void
11796 usage_merge(void)
11798 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11799 getprogname());
11800 exit(1);
11803 static const struct got_error *
11804 cmd_merge(int argc, char *argv[])
11806 const struct got_error *error = NULL;
11807 struct got_worktree *worktree = NULL;
11808 struct got_repository *repo = NULL;
11809 struct got_fileindex *fileindex = NULL;
11810 char *cwd = NULL, *id_str = NULL, *author = NULL;
11811 struct got_reference *branch = NULL, *wt_branch = NULL;
11812 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11813 struct got_object_id *wt_branch_tip = NULL;
11814 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11815 int interrupt_merge = 0;
11816 struct got_update_progress_arg upa;
11817 struct got_object_id *merge_commit_id = NULL;
11818 char *branch_name = NULL;
11819 int *pack_fds = NULL;
11821 memset(&upa, 0, sizeof(upa));
11823 while ((ch = getopt(argc, argv, "acn")) != -1) {
11824 switch (ch) {
11825 case 'a':
11826 abort_merge = 1;
11827 break;
11828 case 'c':
11829 continue_merge = 1;
11830 break;
11831 case 'n':
11832 interrupt_merge = 1;
11833 break;
11834 default:
11835 usage_rebase();
11836 /* NOTREACHED */
11840 argc -= optind;
11841 argv += optind;
11843 #ifndef PROFILE
11844 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11845 "unveil", NULL) == -1)
11846 err(1, "pledge");
11847 #endif
11849 if (abort_merge && continue_merge)
11850 option_conflict('a', 'c');
11851 if (abort_merge || continue_merge) {
11852 if (argc != 0)
11853 usage_merge();
11854 } else if (argc != 1)
11855 usage_merge();
11857 cwd = getcwd(NULL, 0);
11858 if (cwd == NULL) {
11859 error = got_error_from_errno("getcwd");
11860 goto done;
11863 error = got_repo_pack_fds_open(&pack_fds);
11864 if (error != NULL)
11865 goto done;
11867 error = got_worktree_open(&worktree, cwd);
11868 if (error) {
11869 if (error->code == GOT_ERR_NOT_WORKTREE)
11870 error = wrap_not_worktree_error(error,
11871 "merge", cwd);
11872 goto done;
11875 error = got_repo_open(&repo,
11876 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11877 pack_fds);
11878 if (error != NULL)
11879 goto done;
11881 error = apply_unveil(got_repo_get_path(repo), 0,
11882 worktree ? got_worktree_get_root_path(worktree) : NULL);
11883 if (error)
11884 goto done;
11886 error = check_rebase_or_histedit_in_progress(worktree);
11887 if (error)
11888 goto done;
11890 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11891 repo);
11892 if (error)
11893 goto done;
11895 if (abort_merge) {
11896 if (!merge_in_progress) {
11897 error = got_error(GOT_ERR_NOT_MERGING);
11898 goto done;
11900 error = got_worktree_merge_continue(&branch_name,
11901 &branch_tip, &fileindex, worktree, repo);
11902 if (error)
11903 goto done;
11904 error = got_worktree_merge_abort(worktree, fileindex, repo,
11905 abort_progress, &upa);
11906 if (error)
11907 goto done;
11908 printf("Merge of %s aborted\n", branch_name);
11909 goto done; /* nothing else to do */
11912 error = get_author(&author, repo, worktree);
11913 if (error)
11914 goto done;
11916 if (continue_merge) {
11917 if (!merge_in_progress) {
11918 error = got_error(GOT_ERR_NOT_MERGING);
11919 goto done;
11921 error = got_worktree_merge_continue(&branch_name,
11922 &branch_tip, &fileindex, worktree, repo);
11923 if (error)
11924 goto done;
11925 } else {
11926 error = got_ref_open(&branch, repo, argv[0], 0);
11927 if (error != NULL)
11928 goto done;
11929 branch_name = strdup(got_ref_get_name(branch));
11930 if (branch_name == NULL) {
11931 error = got_error_from_errno("strdup");
11932 goto done;
11934 error = got_ref_resolve(&branch_tip, repo, branch);
11935 if (error)
11936 goto done;
11939 error = got_ref_open(&wt_branch, repo,
11940 got_worktree_get_head_ref_name(worktree), 0);
11941 if (error)
11942 goto done;
11943 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11944 if (error)
11945 goto done;
11946 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11947 wt_branch_tip, branch_tip, 0, repo,
11948 check_cancelled, NULL);
11949 if (error && error->code != GOT_ERR_ANCESTRY)
11950 goto done;
11952 if (!continue_merge) {
11953 error = check_path_prefix(wt_branch_tip, branch_tip,
11954 got_worktree_get_path_prefix(worktree),
11955 GOT_ERR_MERGE_PATH, repo);
11956 if (error)
11957 goto done;
11958 if (yca_id) {
11959 error = check_same_branch(wt_branch_tip, branch,
11960 yca_id, repo);
11961 if (error) {
11962 if (error->code != GOT_ERR_ANCESTRY)
11963 goto done;
11964 error = NULL;
11965 } else {
11966 static char msg[512];
11967 snprintf(msg, sizeof(msg),
11968 "cannot create a merge commit because "
11969 "%s is based on %s; %s can be integrated "
11970 "with 'got integrate' instead", branch_name,
11971 got_worktree_get_head_ref_name(worktree),
11972 branch_name);
11973 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11974 goto done;
11977 error = got_worktree_merge_prepare(&fileindex, worktree,
11978 branch, repo);
11979 if (error)
11980 goto done;
11982 error = got_worktree_merge_branch(worktree, fileindex,
11983 yca_id, branch_tip, repo, update_progress, &upa,
11984 check_cancelled, NULL);
11985 if (error)
11986 goto done;
11987 print_merge_progress_stats(&upa);
11988 if (!upa.did_something) {
11989 error = got_worktree_merge_abort(worktree, fileindex,
11990 repo, abort_progress, &upa);
11991 if (error)
11992 goto done;
11993 printf("Already up-to-date\n");
11994 goto done;
11998 if (interrupt_merge) {
11999 error = got_worktree_merge_postpone(worktree, fileindex);
12000 if (error)
12001 goto done;
12002 printf("Merge of %s interrupted on request\n", branch_name);
12003 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12004 upa.not_deleted > 0 || upa.unversioned > 0) {
12005 error = got_worktree_merge_postpone(worktree, fileindex);
12006 if (error)
12007 goto done;
12008 if (upa.conflicts > 0 && upa.missing == 0 &&
12009 upa.not_deleted == 0 && upa.unversioned == 0) {
12010 error = got_error_msg(GOT_ERR_CONFLICTS,
12011 "conflicts must be resolved before merging "
12012 "can continue");
12013 } else if (upa.conflicts > 0) {
12014 error = got_error_msg(GOT_ERR_CONFLICTS,
12015 "conflicts must be resolved before merging "
12016 "can continue; changes destined for some "
12017 "files were not yet merged and "
12018 "should be merged manually if required before the "
12019 "merge operation is continued");
12020 } else {
12021 error = got_error_msg(GOT_ERR_CONFLICTS,
12022 "changes destined for some "
12023 "files were not yet merged and should be "
12024 "merged manually if required before the "
12025 "merge operation is continued");
12027 goto done;
12028 } else {
12029 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12030 fileindex, author, NULL, 1, branch_tip, branch_name,
12031 repo, continue_merge ? print_status : NULL, NULL);
12032 if (error)
12033 goto done;
12034 error = got_worktree_merge_complete(worktree, fileindex, repo);
12035 if (error)
12036 goto done;
12037 error = got_object_id_str(&id_str, merge_commit_id);
12038 if (error)
12039 goto done;
12040 printf("Merged %s into %s: %s\n", branch_name,
12041 got_worktree_get_head_ref_name(worktree),
12042 id_str);
12045 done:
12046 free(id_str);
12047 free(merge_commit_id);
12048 free(author);
12049 free(branch_tip);
12050 free(branch_name);
12051 free(yca_id);
12052 if (branch)
12053 got_ref_close(branch);
12054 if (wt_branch)
12055 got_ref_close(wt_branch);
12056 if (worktree)
12057 got_worktree_close(worktree);
12058 if (repo) {
12059 const struct got_error *close_err = got_repo_close(repo);
12060 if (error == NULL)
12061 error = close_err;
12063 if (pack_fds) {
12064 const struct got_error *pack_err =
12065 got_repo_pack_fds_close(pack_fds);
12066 if (error == NULL)
12067 error = pack_err;
12069 return error;
12072 __dead static void
12073 usage_stage(void)
12075 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12076 "[-S] [file-path ...]\n",
12077 getprogname());
12078 exit(1);
12081 static const struct got_error *
12082 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12083 const char *path, struct got_object_id *blob_id,
12084 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12085 int dirfd, const char *de_name)
12087 const struct got_error *err = NULL;
12088 char *id_str = NULL;
12090 if (staged_status != GOT_STATUS_ADD &&
12091 staged_status != GOT_STATUS_MODIFY &&
12092 staged_status != GOT_STATUS_DELETE)
12093 return NULL;
12095 if (staged_status == GOT_STATUS_ADD ||
12096 staged_status == GOT_STATUS_MODIFY)
12097 err = got_object_id_str(&id_str, staged_blob_id);
12098 else
12099 err = got_object_id_str(&id_str, blob_id);
12100 if (err)
12101 return err;
12103 printf("%s %c %s\n", id_str, staged_status, path);
12104 free(id_str);
12105 return NULL;
12108 static const struct got_error *
12109 cmd_stage(int argc, char *argv[])
12111 const struct got_error *error = NULL;
12112 struct got_repository *repo = NULL;
12113 struct got_worktree *worktree = NULL;
12114 char *cwd = NULL;
12115 struct got_pathlist_head paths;
12116 struct got_pathlist_entry *pe;
12117 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12118 FILE *patch_script_file = NULL;
12119 const char *patch_script_path = NULL;
12120 struct choose_patch_arg cpa;
12121 int *pack_fds = NULL;
12123 TAILQ_INIT(&paths);
12125 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12126 switch (ch) {
12127 case 'l':
12128 list_stage = 1;
12129 break;
12130 case 'p':
12131 pflag = 1;
12132 break;
12133 case 'F':
12134 patch_script_path = optarg;
12135 break;
12136 case 'S':
12137 allow_bad_symlinks = 1;
12138 break;
12139 default:
12140 usage_stage();
12141 /* NOTREACHED */
12145 argc -= optind;
12146 argv += optind;
12148 #ifndef PROFILE
12149 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12150 "unveil", NULL) == -1)
12151 err(1, "pledge");
12152 #endif
12153 if (list_stage && (pflag || patch_script_path))
12154 errx(1, "-l option cannot be used with other options");
12155 if (patch_script_path && !pflag)
12156 errx(1, "-F option can only be used together with -p option");
12158 cwd = getcwd(NULL, 0);
12159 if (cwd == NULL) {
12160 error = got_error_from_errno("getcwd");
12161 goto done;
12164 error = got_repo_pack_fds_open(&pack_fds);
12165 if (error != NULL)
12166 goto done;
12168 error = got_worktree_open(&worktree, cwd);
12169 if (error) {
12170 if (error->code == GOT_ERR_NOT_WORKTREE)
12171 error = wrap_not_worktree_error(error, "stage", cwd);
12172 goto done;
12175 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12176 NULL, pack_fds);
12177 if (error != NULL)
12178 goto done;
12180 if (patch_script_path) {
12181 patch_script_file = fopen(patch_script_path, "re");
12182 if (patch_script_file == NULL) {
12183 error = got_error_from_errno2("fopen",
12184 patch_script_path);
12185 goto done;
12188 error = apply_unveil(got_repo_get_path(repo), 0,
12189 got_worktree_get_root_path(worktree));
12190 if (error)
12191 goto done;
12193 error = check_merge_in_progress(worktree, repo);
12194 if (error)
12195 goto done;
12197 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12198 if (error)
12199 goto done;
12201 if (list_stage)
12202 error = got_worktree_status(worktree, &paths, repo, 0,
12203 print_stage, NULL, check_cancelled, NULL);
12204 else {
12205 cpa.patch_script_file = patch_script_file;
12206 cpa.action = "stage";
12207 error = got_worktree_stage(worktree, &paths,
12208 pflag ? NULL : print_status, NULL,
12209 pflag ? choose_patch : NULL, &cpa,
12210 allow_bad_symlinks, repo);
12212 done:
12213 if (patch_script_file && fclose(patch_script_file) == EOF &&
12214 error == NULL)
12215 error = got_error_from_errno2("fclose", patch_script_path);
12216 if (repo) {
12217 const struct got_error *close_err = got_repo_close(repo);
12218 if (error == NULL)
12219 error = close_err;
12221 if (worktree)
12222 got_worktree_close(worktree);
12223 if (pack_fds) {
12224 const struct got_error *pack_err =
12225 got_repo_pack_fds_close(pack_fds);
12226 if (error == NULL)
12227 error = pack_err;
12229 TAILQ_FOREACH(pe, &paths, entry)
12230 free((char *)pe->path);
12231 got_pathlist_free(&paths);
12232 free(cwd);
12233 return error;
12236 __dead static void
12237 usage_unstage(void)
12239 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12240 "[file-path ...]\n",
12241 getprogname());
12242 exit(1);
12246 static const struct got_error *
12247 cmd_unstage(int argc, char *argv[])
12249 const struct got_error *error = NULL;
12250 struct got_repository *repo = NULL;
12251 struct got_worktree *worktree = NULL;
12252 char *cwd = NULL;
12253 struct got_pathlist_head paths;
12254 struct got_pathlist_entry *pe;
12255 int ch, pflag = 0;
12256 struct got_update_progress_arg upa;
12257 FILE *patch_script_file = NULL;
12258 const char *patch_script_path = NULL;
12259 struct choose_patch_arg cpa;
12260 int *pack_fds = NULL;
12262 TAILQ_INIT(&paths);
12264 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12265 switch (ch) {
12266 case 'p':
12267 pflag = 1;
12268 break;
12269 case 'F':
12270 patch_script_path = optarg;
12271 break;
12272 default:
12273 usage_unstage();
12274 /* NOTREACHED */
12278 argc -= optind;
12279 argv += optind;
12281 #ifndef PROFILE
12282 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12283 "unveil", NULL) == -1)
12284 err(1, "pledge");
12285 #endif
12286 if (patch_script_path && !pflag)
12287 errx(1, "-F option can only be used together with -p option");
12289 cwd = getcwd(NULL, 0);
12290 if (cwd == NULL) {
12291 error = got_error_from_errno("getcwd");
12292 goto done;
12295 error = got_repo_pack_fds_open(&pack_fds);
12296 if (error != NULL)
12297 goto done;
12299 error = got_worktree_open(&worktree, cwd);
12300 if (error) {
12301 if (error->code == GOT_ERR_NOT_WORKTREE)
12302 error = wrap_not_worktree_error(error, "unstage", cwd);
12303 goto done;
12306 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12307 NULL, pack_fds);
12308 if (error != NULL)
12309 goto done;
12311 if (patch_script_path) {
12312 patch_script_file = fopen(patch_script_path, "re");
12313 if (patch_script_file == NULL) {
12314 error = got_error_from_errno2("fopen",
12315 patch_script_path);
12316 goto done;
12320 error = apply_unveil(got_repo_get_path(repo), 0,
12321 got_worktree_get_root_path(worktree));
12322 if (error)
12323 goto done;
12325 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12326 if (error)
12327 goto done;
12329 cpa.patch_script_file = patch_script_file;
12330 cpa.action = "unstage";
12331 memset(&upa, 0, sizeof(upa));
12332 error = got_worktree_unstage(worktree, &paths, update_progress,
12333 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12334 if (!error)
12335 print_merge_progress_stats(&upa);
12336 done:
12337 if (patch_script_file && fclose(patch_script_file) == EOF &&
12338 error == NULL)
12339 error = got_error_from_errno2("fclose", patch_script_path);
12340 if (repo) {
12341 const struct got_error *close_err = got_repo_close(repo);
12342 if (error == NULL)
12343 error = close_err;
12345 if (worktree)
12346 got_worktree_close(worktree);
12347 if (pack_fds) {
12348 const struct got_error *pack_err =
12349 got_repo_pack_fds_close(pack_fds);
12350 if (error == NULL)
12351 error = pack_err;
12353 TAILQ_FOREACH(pe, &paths, entry)
12354 free((char *)pe->path);
12355 got_pathlist_free(&paths);
12356 free(cwd);
12357 return error;
12360 __dead static void
12361 usage_cat(void)
12363 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12364 "arg1 [arg2 ...]\n", getprogname());
12365 exit(1);
12368 static const struct got_error *
12369 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12371 const struct got_error *err;
12372 struct got_blob_object *blob;
12373 int fd = -1;
12375 fd = got_opentempfd();
12376 if (fd == -1)
12377 return got_error_from_errno("got_opentempfd");
12379 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12380 if (err)
12381 goto done;
12383 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12384 done:
12385 if (fd != -1 && close(fd) == -1 && err == NULL)
12386 err = got_error_from_errno("close");
12387 if (blob)
12388 got_object_blob_close(blob);
12389 return err;
12392 static const struct got_error *
12393 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12395 const struct got_error *err;
12396 struct got_tree_object *tree;
12397 int nentries, i;
12399 err = got_object_open_as_tree(&tree, repo, id);
12400 if (err)
12401 return err;
12403 nentries = got_object_tree_get_nentries(tree);
12404 for (i = 0; i < nentries; i++) {
12405 struct got_tree_entry *te;
12406 char *id_str;
12407 if (sigint_received || sigpipe_received)
12408 break;
12409 te = got_object_tree_get_entry(tree, i);
12410 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12411 if (err)
12412 break;
12413 fprintf(outfile, "%s %.7o %s\n", id_str,
12414 got_tree_entry_get_mode(te),
12415 got_tree_entry_get_name(te));
12416 free(id_str);
12419 got_object_tree_close(tree);
12420 return err;
12423 static void
12424 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12426 long long h, m;
12427 char sign = '+';
12429 if (gmtoff < 0) {
12430 sign = '-';
12431 gmtoff = -gmtoff;
12434 h = (long long)gmtoff / 3600;
12435 m = ((long long)gmtoff - h*3600) / 60;
12436 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12439 static const struct got_error *
12440 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12442 const struct got_error *err;
12443 struct got_commit_object *commit;
12444 const struct got_object_id_queue *parent_ids;
12445 struct got_object_qid *pid;
12446 char *id_str = NULL;
12447 const char *logmsg = NULL;
12448 char gmtoff[6];
12450 err = got_object_open_as_commit(&commit, repo, id);
12451 if (err)
12452 return err;
12454 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12455 if (err)
12456 goto done;
12458 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12459 parent_ids = got_object_commit_get_parent_ids(commit);
12460 fprintf(outfile, "numparents %d\n",
12461 got_object_commit_get_nparents(commit));
12462 STAILQ_FOREACH(pid, parent_ids, entry) {
12463 char *pid_str;
12464 err = got_object_id_str(&pid_str, &pid->id);
12465 if (err)
12466 goto done;
12467 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12468 free(pid_str);
12470 format_gmtoff(gmtoff, sizeof(gmtoff),
12471 got_object_commit_get_author_gmtoff(commit));
12472 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12473 got_object_commit_get_author(commit),
12474 (long long)got_object_commit_get_author_time(commit),
12475 gmtoff);
12477 format_gmtoff(gmtoff, sizeof(gmtoff),
12478 got_object_commit_get_committer_gmtoff(commit));
12479 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12480 got_object_commit_get_author(commit),
12481 (long long)got_object_commit_get_committer_time(commit),
12482 gmtoff);
12484 logmsg = got_object_commit_get_logmsg_raw(commit);
12485 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12486 fprintf(outfile, "%s", logmsg);
12487 done:
12488 free(id_str);
12489 got_object_commit_close(commit);
12490 return err;
12493 static const struct got_error *
12494 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12496 const struct got_error *err;
12497 struct got_tag_object *tag;
12498 char *id_str = NULL;
12499 const char *tagmsg = NULL;
12500 char gmtoff[6];
12502 err = got_object_open_as_tag(&tag, repo, id);
12503 if (err)
12504 return err;
12506 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12507 if (err)
12508 goto done;
12510 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12512 switch (got_object_tag_get_object_type(tag)) {
12513 case GOT_OBJ_TYPE_BLOB:
12514 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12515 GOT_OBJ_LABEL_BLOB);
12516 break;
12517 case GOT_OBJ_TYPE_TREE:
12518 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12519 GOT_OBJ_LABEL_TREE);
12520 break;
12521 case GOT_OBJ_TYPE_COMMIT:
12522 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12523 GOT_OBJ_LABEL_COMMIT);
12524 break;
12525 case GOT_OBJ_TYPE_TAG:
12526 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12527 GOT_OBJ_LABEL_TAG);
12528 break;
12529 default:
12530 break;
12533 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12534 got_object_tag_get_name(tag));
12536 format_gmtoff(gmtoff, sizeof(gmtoff),
12537 got_object_tag_get_tagger_gmtoff(tag));
12538 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12539 got_object_tag_get_tagger(tag),
12540 (long long)got_object_tag_get_tagger_time(tag),
12541 gmtoff);
12543 tagmsg = got_object_tag_get_message(tag);
12544 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12545 fprintf(outfile, "%s", tagmsg);
12546 done:
12547 free(id_str);
12548 got_object_tag_close(tag);
12549 return err;
12552 static const struct got_error *
12553 cmd_cat(int argc, char *argv[])
12555 const struct got_error *error;
12556 struct got_repository *repo = NULL;
12557 struct got_worktree *worktree = NULL;
12558 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12559 const char *commit_id_str = NULL;
12560 struct got_object_id *id = NULL, *commit_id = NULL;
12561 struct got_commit_object *commit = NULL;
12562 int ch, obj_type, i, force_path = 0;
12563 struct got_reflist_head refs;
12564 int *pack_fds = NULL;
12566 TAILQ_INIT(&refs);
12568 #ifndef PROFILE
12569 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12570 NULL) == -1)
12571 err(1, "pledge");
12572 #endif
12574 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12575 switch (ch) {
12576 case 'c':
12577 commit_id_str = optarg;
12578 break;
12579 case 'r':
12580 repo_path = realpath(optarg, NULL);
12581 if (repo_path == NULL)
12582 return got_error_from_errno2("realpath",
12583 optarg);
12584 got_path_strip_trailing_slashes(repo_path);
12585 break;
12586 case 'P':
12587 force_path = 1;
12588 break;
12589 default:
12590 usage_cat();
12591 /* NOTREACHED */
12595 argc -= optind;
12596 argv += optind;
12598 cwd = getcwd(NULL, 0);
12599 if (cwd == NULL) {
12600 error = got_error_from_errno("getcwd");
12601 goto done;
12604 error = got_repo_pack_fds_open(&pack_fds);
12605 if (error != NULL)
12606 goto done;
12608 if (repo_path == NULL) {
12609 error = got_worktree_open(&worktree, cwd);
12610 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12611 goto done;
12612 if (worktree) {
12613 repo_path = strdup(
12614 got_worktree_get_repo_path(worktree));
12615 if (repo_path == NULL) {
12616 error = got_error_from_errno("strdup");
12617 goto done;
12620 /* Release work tree lock. */
12621 got_worktree_close(worktree);
12622 worktree = NULL;
12626 if (repo_path == NULL) {
12627 repo_path = strdup(cwd);
12628 if (repo_path == NULL)
12629 return got_error_from_errno("strdup");
12632 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12633 free(repo_path);
12634 if (error != NULL)
12635 goto done;
12637 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12638 if (error)
12639 goto done;
12641 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12642 if (error)
12643 goto done;
12645 if (commit_id_str == NULL)
12646 commit_id_str = GOT_REF_HEAD;
12647 error = got_repo_match_object_id(&commit_id, NULL,
12648 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12649 if (error)
12650 goto done;
12652 error = got_object_open_as_commit(&commit, repo, commit_id);
12653 if (error)
12654 goto done;
12656 for (i = 0; i < argc; i++) {
12657 if (force_path) {
12658 error = got_object_id_by_path(&id, repo, commit,
12659 argv[i]);
12660 if (error)
12661 break;
12662 } else {
12663 error = got_repo_match_object_id(&id, &label, argv[i],
12664 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12665 repo);
12666 if (error) {
12667 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12668 error->code != GOT_ERR_NOT_REF)
12669 break;
12670 error = got_object_id_by_path(&id, repo,
12671 commit, argv[i]);
12672 if (error)
12673 break;
12677 error = got_object_get_type(&obj_type, repo, id);
12678 if (error)
12679 break;
12681 switch (obj_type) {
12682 case GOT_OBJ_TYPE_BLOB:
12683 error = cat_blob(id, repo, stdout);
12684 break;
12685 case GOT_OBJ_TYPE_TREE:
12686 error = cat_tree(id, repo, stdout);
12687 break;
12688 case GOT_OBJ_TYPE_COMMIT:
12689 error = cat_commit(id, repo, stdout);
12690 break;
12691 case GOT_OBJ_TYPE_TAG:
12692 error = cat_tag(id, repo, stdout);
12693 break;
12694 default:
12695 error = got_error(GOT_ERR_OBJ_TYPE);
12696 break;
12698 if (error)
12699 break;
12700 free(label);
12701 label = NULL;
12702 free(id);
12703 id = NULL;
12705 done:
12706 free(label);
12707 free(id);
12708 free(commit_id);
12709 if (commit)
12710 got_object_commit_close(commit);
12711 if (worktree)
12712 got_worktree_close(worktree);
12713 if (repo) {
12714 const struct got_error *close_err = got_repo_close(repo);
12715 if (error == NULL)
12716 error = close_err;
12718 if (pack_fds) {
12719 const struct got_error *pack_err =
12720 got_repo_pack_fds_close(pack_fds);
12721 if (error == NULL)
12722 error = pack_err;
12725 got_ref_list_free(&refs);
12726 return error;
12729 __dead static void
12730 usage_info(void)
12732 fprintf(stderr, "usage: %s info [path ...]\n",
12733 getprogname());
12734 exit(1);
12737 static const struct got_error *
12738 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12739 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12740 struct got_object_id *commit_id)
12742 const struct got_error *err = NULL;
12743 char *id_str = NULL;
12744 char datebuf[128];
12745 struct tm mytm, *tm;
12746 struct got_pathlist_head *paths = arg;
12747 struct got_pathlist_entry *pe;
12750 * Clear error indication from any of the path arguments which
12751 * would cause this file index entry to be displayed.
12753 TAILQ_FOREACH(pe, paths, entry) {
12754 if (got_path_cmp(path, pe->path, strlen(path),
12755 pe->path_len) == 0 ||
12756 got_path_is_child(path, pe->path, pe->path_len))
12757 pe->data = NULL; /* no error */
12760 printf(GOT_COMMIT_SEP_STR);
12761 if (S_ISLNK(mode))
12762 printf("symlink: %s\n", path);
12763 else if (S_ISREG(mode)) {
12764 printf("file: %s\n", path);
12765 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12766 } else if (S_ISDIR(mode))
12767 printf("directory: %s\n", path);
12768 else
12769 printf("something: %s\n", path);
12771 tm = localtime_r(&mtime, &mytm);
12772 if (tm == NULL)
12773 return NULL;
12774 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12775 return got_error(GOT_ERR_NO_SPACE);
12776 printf("timestamp: %s\n", datebuf);
12778 if (blob_id) {
12779 err = got_object_id_str(&id_str, blob_id);
12780 if (err)
12781 return err;
12782 printf("based on blob: %s\n", id_str);
12783 free(id_str);
12786 if (staged_blob_id) {
12787 err = got_object_id_str(&id_str, staged_blob_id);
12788 if (err)
12789 return err;
12790 printf("based on staged blob: %s\n", id_str);
12791 free(id_str);
12794 if (commit_id) {
12795 err = got_object_id_str(&id_str, commit_id);
12796 if (err)
12797 return err;
12798 printf("based on commit: %s\n", id_str);
12799 free(id_str);
12802 return NULL;
12805 static const struct got_error *
12806 cmd_info(int argc, char *argv[])
12808 const struct got_error *error = NULL;
12809 struct got_worktree *worktree = NULL;
12810 char *cwd = NULL, *id_str = NULL;
12811 struct got_pathlist_head paths;
12812 struct got_pathlist_entry *pe;
12813 char *uuidstr = NULL;
12814 int ch, show_files = 0;
12815 int *pack_fds = NULL;
12817 TAILQ_INIT(&paths);
12819 while ((ch = getopt(argc, argv, "")) != -1) {
12820 switch (ch) {
12821 default:
12822 usage_info();
12823 /* NOTREACHED */
12827 argc -= optind;
12828 argv += optind;
12830 #ifndef PROFILE
12831 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12832 NULL) == -1)
12833 err(1, "pledge");
12834 #endif
12835 cwd = getcwd(NULL, 0);
12836 if (cwd == NULL) {
12837 error = got_error_from_errno("getcwd");
12838 goto done;
12841 error = got_repo_pack_fds_open(&pack_fds);
12842 if (error != NULL)
12843 goto done;
12845 error = got_worktree_open(&worktree, cwd);
12846 if (error) {
12847 if (error->code == GOT_ERR_NOT_WORKTREE)
12848 error = wrap_not_worktree_error(error, "info", cwd);
12849 goto done;
12852 #ifndef PROFILE
12853 /* Remove "cpath" promise. */
12854 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12855 NULL) == -1)
12856 err(1, "pledge");
12857 #endif
12858 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12859 if (error)
12860 goto done;
12862 if (argc >= 1) {
12863 error = get_worktree_paths_from_argv(&paths, argc, argv,
12864 worktree);
12865 if (error)
12866 goto done;
12867 show_files = 1;
12870 error = got_object_id_str(&id_str,
12871 got_worktree_get_base_commit_id(worktree));
12872 if (error)
12873 goto done;
12875 error = got_worktree_get_uuid(&uuidstr, worktree);
12876 if (error)
12877 goto done;
12879 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12880 printf("work tree base commit: %s\n", id_str);
12881 printf("work tree path prefix: %s\n",
12882 got_worktree_get_path_prefix(worktree));
12883 printf("work tree branch reference: %s\n",
12884 got_worktree_get_head_ref_name(worktree));
12885 printf("work tree UUID: %s\n", uuidstr);
12886 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12888 if (show_files) {
12889 struct got_pathlist_entry *pe;
12890 TAILQ_FOREACH(pe, &paths, entry) {
12891 if (pe->path_len == 0)
12892 continue;
12894 * Assume this path will fail. This will be corrected
12895 * in print_path_info() in case the path does suceeed.
12897 pe->data = (void *)got_error_path(pe->path,
12898 GOT_ERR_BAD_PATH);
12900 error = got_worktree_path_info(worktree, &paths,
12901 print_path_info, &paths, check_cancelled, NULL);
12902 if (error)
12903 goto done;
12904 TAILQ_FOREACH(pe, &paths, entry) {
12905 if (pe->data != NULL) {
12906 error = pe->data; /* bad path */
12907 break;
12911 done:
12912 if (pack_fds) {
12913 const struct got_error *pack_err =
12914 got_repo_pack_fds_close(pack_fds);
12915 if (error == NULL)
12916 error = pack_err;
12918 TAILQ_FOREACH(pe, &paths, entry)
12919 free((char *)pe->path);
12920 got_pathlist_free(&paths);
12921 free(cwd);
12922 free(id_str);
12923 free(uuidstr);
12924 return error;