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 diff_context, ignore_whitespace, force_text_diff, outfile);
3588 done:
3589 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3590 err = got_error_from_errno("close");
3591 if (blob1)
3592 got_object_blob_close(blob1);
3593 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3594 err = got_error_from_errno("close");
3595 got_object_blob_close(blob2);
3596 if (f1 && fclose(f1) == EOF && err == NULL)
3597 err = got_error_from_errno("fclose");
3598 if (f2 && fclose(f2) == EOF && err == NULL)
3599 err = got_error_from_errno("fclose");
3600 return err;
3603 static const struct got_error *
3604 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3605 const char *path, int diff_context, int ignore_whitespace,
3606 int force_text_diff, struct got_repository *repo, FILE *outfile)
3608 const struct got_error *err = NULL;
3609 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3610 struct got_diff_blob_output_unidiff_arg arg;
3611 FILE *f1 = NULL, *f2 = NULL;
3612 int fd1 = -1, fd2 = -1;
3614 if (tree_id1) {
3615 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3616 if (err)
3617 goto done;
3618 fd1 = got_opentempfd();
3619 if (fd1 == -1) {
3620 err = got_error_from_errno("got_opentempfd");
3621 goto done;
3625 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3626 if (err)
3627 goto done;
3629 f1 = got_opentemp();
3630 if (f1 == NULL) {
3631 err = got_error_from_errno("got_opentemp");
3632 goto done;
3635 f2 = got_opentemp();
3636 if (f2 == NULL) {
3637 err = got_error_from_errno("got_opentemp");
3638 goto done;
3640 fd2 = got_opentempfd();
3641 if (fd2 == -1) {
3642 err = got_error_from_errno("got_opentempfd");
3643 goto done;
3645 arg.diff_context = diff_context;
3646 arg.ignore_whitespace = ignore_whitespace;
3647 arg.force_text_diff = force_text_diff;
3648 arg.outfile = outfile;
3649 arg.line_offsets = NULL;
3650 arg.nlines = 0;
3651 while (path[0] == '/')
3652 path++;
3653 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3654 got_diff_blob_output_unidiff, &arg, 1);
3655 done:
3656 if (tree1)
3657 got_object_tree_close(tree1);
3658 if (tree2)
3659 got_object_tree_close(tree2);
3660 if (f1 && fclose(f1) == EOF && err == NULL)
3661 err = got_error_from_errno("fclose");
3662 if (f2 && fclose(f2) == EOF && err == NULL)
3663 err = got_error_from_errno("fclose");
3664 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3665 err = got_error_from_errno("close");
3666 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3667 err = got_error_from_errno("close");
3668 return err;
3671 static const struct got_error *
3672 get_changed_paths(struct got_pathlist_head *paths,
3673 struct got_commit_object *commit, struct got_repository *repo)
3675 const struct got_error *err = NULL;
3676 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3677 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3678 struct got_object_qid *qid;
3680 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3681 if (qid != NULL) {
3682 struct got_commit_object *pcommit;
3683 err = got_object_open_as_commit(&pcommit, repo,
3684 &qid->id);
3685 if (err)
3686 return err;
3688 tree_id1 = got_object_id_dup(
3689 got_object_commit_get_tree_id(pcommit));
3690 if (tree_id1 == NULL) {
3691 got_object_commit_close(pcommit);
3692 return got_error_from_errno("got_object_id_dup");
3694 got_object_commit_close(pcommit);
3698 if (tree_id1) {
3699 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3700 if (err)
3701 goto done;
3704 tree_id2 = got_object_commit_get_tree_id(commit);
3705 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3706 if (err)
3707 goto done;
3709 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3710 got_diff_tree_collect_changed_paths, paths, 0);
3711 done:
3712 if (tree1)
3713 got_object_tree_close(tree1);
3714 if (tree2)
3715 got_object_tree_close(tree2);
3716 free(tree_id1);
3717 return err;
3720 static const struct got_error *
3721 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3722 const char *path, int diff_context, struct got_repository *repo,
3723 FILE *outfile)
3725 const struct got_error *err = NULL;
3726 struct got_commit_object *pcommit = NULL;
3727 char *id_str1 = NULL, *id_str2 = NULL;
3728 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3729 struct got_object_qid *qid;
3731 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3732 if (qid != NULL) {
3733 err = got_object_open_as_commit(&pcommit, repo,
3734 &qid->id);
3735 if (err)
3736 return err;
3737 err = got_object_id_str(&id_str1, &qid->id);
3738 if (err)
3739 goto done;
3742 err = got_object_id_str(&id_str2, id);
3743 if (err)
3744 goto done;
3746 if (path && path[0] != '\0') {
3747 int obj_type;
3748 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3749 if (err)
3750 goto done;
3751 if (pcommit) {
3752 err = got_object_id_by_path(&obj_id1, repo,
3753 pcommit, path);
3754 if (err) {
3755 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3756 free(obj_id2);
3757 goto done;
3761 err = got_object_get_type(&obj_type, repo, obj_id2);
3762 if (err) {
3763 free(obj_id2);
3764 goto done;
3766 fprintf(outfile,
3767 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3768 fprintf(outfile, "commit - %s\n",
3769 id_str1 ? id_str1 : "/dev/null");
3770 fprintf(outfile, "commit + %s\n", id_str2);
3771 switch (obj_type) {
3772 case GOT_OBJ_TYPE_BLOB:
3773 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3774 0, 0, repo, outfile);
3775 break;
3776 case GOT_OBJ_TYPE_TREE:
3777 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3778 0, 0, repo, outfile);
3779 break;
3780 default:
3781 err = got_error(GOT_ERR_OBJ_TYPE);
3782 break;
3784 free(obj_id1);
3785 free(obj_id2);
3786 } else {
3787 obj_id2 = got_object_commit_get_tree_id(commit);
3788 if (pcommit)
3789 obj_id1 = got_object_commit_get_tree_id(pcommit);
3790 fprintf(outfile,
3791 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3792 fprintf(outfile, "commit - %s\n",
3793 id_str1 ? id_str1 : "/dev/null");
3794 fprintf(outfile, "commit + %s\n", id_str2);
3795 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3796 repo, outfile);
3798 done:
3799 free(id_str1);
3800 free(id_str2);
3801 if (pcommit)
3802 got_object_commit_close(pcommit);
3803 return err;
3806 static char *
3807 get_datestr(time_t *time, char *datebuf)
3809 struct tm mytm, *tm;
3810 char *p, *s;
3812 tm = gmtime_r(time, &mytm);
3813 if (tm == NULL)
3814 return NULL;
3815 s = asctime_r(tm, datebuf);
3816 if (s == NULL)
3817 return NULL;
3818 p = strchr(s, '\n');
3819 if (p)
3820 *p = '\0';
3821 return s;
3824 static const struct got_error *
3825 match_commit(int *have_match, struct got_object_id *id,
3826 struct got_commit_object *commit, regex_t *regex)
3828 const struct got_error *err = NULL;
3829 regmatch_t regmatch;
3830 char *id_str = NULL, *logmsg = NULL;
3832 *have_match = 0;
3834 err = got_object_id_str(&id_str, id);
3835 if (err)
3836 return err;
3838 err = got_object_commit_get_logmsg(&logmsg, commit);
3839 if (err)
3840 goto done;
3842 if (regexec(regex, got_object_commit_get_author(commit), 1,
3843 &regmatch, 0) == 0 ||
3844 regexec(regex, got_object_commit_get_committer(commit), 1,
3845 &regmatch, 0) == 0 ||
3846 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3847 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3848 *have_match = 1;
3849 done:
3850 free(id_str);
3851 free(logmsg);
3852 return err;
3855 static void
3856 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3857 regex_t *regex)
3859 regmatch_t regmatch;
3860 struct got_pathlist_entry *pe;
3862 *have_match = 0;
3864 TAILQ_FOREACH(pe, changed_paths, entry) {
3865 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3866 *have_match = 1;
3867 break;
3872 static const struct got_error *
3873 match_patch(int *have_match, struct got_commit_object *commit,
3874 struct got_object_id *id, const char *path, int diff_context,
3875 struct got_repository *repo, regex_t *regex, FILE *f)
3877 const struct got_error *err = NULL;
3878 char *line = NULL;
3879 size_t linesize = 0;
3880 ssize_t linelen;
3881 regmatch_t regmatch;
3883 *have_match = 0;
3885 err = got_opentemp_truncate(f);
3886 if (err)
3887 return err;
3889 err = print_patch(commit, id, path, diff_context, repo, f);
3890 if (err)
3891 goto done;
3893 if (fseeko(f, 0L, SEEK_SET) == -1) {
3894 err = got_error_from_errno("fseeko");
3895 goto done;
3898 while ((linelen = getline(&line, &linesize, f)) != -1) {
3899 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3900 *have_match = 1;
3901 break;
3904 done:
3905 free(line);
3906 return err;
3909 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3911 static const struct got_error*
3912 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3913 struct got_object_id *id, struct got_repository *repo,
3914 int local_only)
3916 static const struct got_error *err = NULL;
3917 struct got_reflist_entry *re;
3918 char *s;
3919 const char *name;
3921 *refs_str = NULL;
3923 TAILQ_FOREACH(re, refs, entry) {
3924 struct got_tag_object *tag = NULL;
3925 struct got_object_id *ref_id;
3926 int cmp;
3928 name = got_ref_get_name(re->ref);
3929 if (strcmp(name, GOT_REF_HEAD) == 0)
3930 continue;
3931 if (strncmp(name, "refs/", 5) == 0)
3932 name += 5;
3933 if (strncmp(name, "got/", 4) == 0)
3934 continue;
3935 if (strncmp(name, "heads/", 6) == 0)
3936 name += 6;
3937 if (strncmp(name, "remotes/", 8) == 0) {
3938 if (local_only)
3939 continue;
3940 name += 8;
3941 s = strstr(name, "/" GOT_REF_HEAD);
3942 if (s != NULL && s[strlen(s)] == '\0')
3943 continue;
3945 err = got_ref_resolve(&ref_id, repo, re->ref);
3946 if (err)
3947 break;
3948 if (strncmp(name, "tags/", 5) == 0) {
3949 err = got_object_open_as_tag(&tag, repo, ref_id);
3950 if (err) {
3951 if (err->code != GOT_ERR_OBJ_TYPE) {
3952 free(ref_id);
3953 break;
3955 /* Ref points at something other than a tag. */
3956 err = NULL;
3957 tag = NULL;
3960 cmp = got_object_id_cmp(tag ?
3961 got_object_tag_get_object_id(tag) : ref_id, id);
3962 free(ref_id);
3963 if (tag)
3964 got_object_tag_close(tag);
3965 if (cmp != 0)
3966 continue;
3967 s = *refs_str;
3968 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3969 s ? ", " : "", name) == -1) {
3970 err = got_error_from_errno("asprintf");
3971 free(s);
3972 *refs_str = NULL;
3973 break;
3975 free(s);
3978 return err;
3981 static const struct got_error *
3982 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3983 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3985 const struct got_error *err = NULL;
3986 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3987 char *comma, *s, *nl;
3988 struct got_reflist_head *refs;
3989 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3990 struct tm tm;
3991 time_t committer_time;
3993 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3994 if (refs) {
3995 err = build_refs_str(&ref_str, refs, id, repo, 1);
3996 if (err)
3997 return err;
3999 /* Display the first matching ref only. */
4000 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4001 *comma = '\0';
4004 if (ref_str == NULL) {
4005 err = got_object_id_str(&id_str, id);
4006 if (err)
4007 return err;
4010 committer_time = got_object_commit_get_committer_time(commit);
4011 if (gmtime_r(&committer_time, &tm) == NULL) {
4012 err = got_error_from_errno("gmtime_r");
4013 goto done;
4015 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4016 err = got_error(GOT_ERR_NO_SPACE);
4017 goto done;
4020 err = got_object_commit_get_logmsg(&logmsg0, commit);
4021 if (err)
4022 goto done;
4024 s = logmsg0;
4025 while (isspace((unsigned char)s[0]))
4026 s++;
4028 nl = strchr(s, '\n');
4029 if (nl) {
4030 *nl = '\0';
4033 if (ref_str)
4034 printf("%s%-7s %s\n", datebuf, ref_str, s);
4035 else
4036 printf("%s%.7s %s\n", datebuf, id_str, s);
4038 if (fflush(stdout) != 0 && err == NULL)
4039 err = got_error_from_errno("fflush");
4040 done:
4041 free(id_str);
4042 free(ref_str);
4043 free(logmsg0);
4044 return err;
4047 static const struct got_error *
4048 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4049 struct got_repository *repo, const char *path,
4050 struct got_pathlist_head *changed_paths, int show_patch,
4051 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4052 const char *custom_refs_str)
4054 const struct got_error *err = NULL;
4055 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4056 char datebuf[26];
4057 time_t committer_time;
4058 const char *author, *committer;
4059 char *refs_str = NULL;
4061 err = got_object_id_str(&id_str, id);
4062 if (err)
4063 return err;
4065 if (custom_refs_str == NULL) {
4066 struct got_reflist_head *refs;
4067 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4068 if (refs) {
4069 err = build_refs_str(&refs_str, refs, id, repo, 0);
4070 if (err)
4071 goto done;
4075 printf(GOT_COMMIT_SEP_STR);
4076 if (custom_refs_str)
4077 printf("commit %s (%s)\n", id_str, custom_refs_str);
4078 else
4079 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4080 refs_str ? refs_str : "", refs_str ? ")" : "");
4081 free(id_str);
4082 id_str = NULL;
4083 free(refs_str);
4084 refs_str = NULL;
4085 printf("from: %s\n", got_object_commit_get_author(commit));
4086 committer_time = got_object_commit_get_committer_time(commit);
4087 datestr = get_datestr(&committer_time, datebuf);
4088 if (datestr)
4089 printf("date: %s UTC\n", datestr);
4090 author = got_object_commit_get_author(commit);
4091 committer = got_object_commit_get_committer(commit);
4092 if (strcmp(author, committer) != 0)
4093 printf("via: %s\n", committer);
4094 if (got_object_commit_get_nparents(commit) > 1) {
4095 const struct got_object_id_queue *parent_ids;
4096 struct got_object_qid *qid;
4097 int n = 1;
4098 parent_ids = got_object_commit_get_parent_ids(commit);
4099 STAILQ_FOREACH(qid, parent_ids, entry) {
4100 err = got_object_id_str(&id_str, &qid->id);
4101 if (err)
4102 goto done;
4103 printf("parent %d: %s\n", n++, id_str);
4104 free(id_str);
4105 id_str = NULL;
4109 err = got_object_commit_get_logmsg(&logmsg0, commit);
4110 if (err)
4111 goto done;
4113 logmsg = logmsg0;
4114 do {
4115 line = strsep(&logmsg, "\n");
4116 if (line)
4117 printf(" %s\n", line);
4118 } while (line);
4119 free(logmsg0);
4121 if (changed_paths) {
4122 struct got_pathlist_entry *pe;
4123 TAILQ_FOREACH(pe, changed_paths, entry) {
4124 struct got_diff_changed_path *cp = pe->data;
4125 printf(" %c %s\n", cp->status, pe->path);
4127 printf("\n");
4129 if (show_patch) {
4130 err = print_patch(commit, id, path, diff_context, repo, stdout);
4131 if (err == 0)
4132 printf("\n");
4135 if (fflush(stdout) != 0 && err == NULL)
4136 err = got_error_from_errno("fflush");
4137 done:
4138 free(id_str);
4139 free(refs_str);
4140 return err;
4143 static const struct got_error *
4144 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4145 struct got_repository *repo, const char *path, int show_changed_paths,
4146 int show_patch, const char *search_pattern, int diff_context, int limit,
4147 int log_branches, int reverse_display_order,
4148 struct got_reflist_object_id_map *refs_idmap, int one_line,
4149 FILE *tmpfile)
4151 const struct got_error *err;
4152 struct got_commit_graph *graph;
4153 regex_t regex;
4154 int have_match;
4155 struct got_object_id_queue reversed_commits;
4156 struct got_object_qid *qid;
4157 struct got_commit_object *commit;
4158 struct got_pathlist_head changed_paths;
4159 struct got_pathlist_entry *pe;
4161 STAILQ_INIT(&reversed_commits);
4162 TAILQ_INIT(&changed_paths);
4164 if (search_pattern && regcomp(&regex, search_pattern,
4165 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4166 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4168 err = got_commit_graph_open(&graph, path, !log_branches);
4169 if (err)
4170 return err;
4171 err = got_commit_graph_iter_start(graph, root_id, repo,
4172 check_cancelled, NULL);
4173 if (err)
4174 goto done;
4175 for (;;) {
4176 struct got_object_id *id;
4178 if (sigint_received || sigpipe_received)
4179 break;
4181 err = got_commit_graph_iter_next(&id, graph, repo,
4182 check_cancelled, NULL);
4183 if (err) {
4184 if (err->code == GOT_ERR_ITER_COMPLETED)
4185 err = NULL;
4186 break;
4188 if (id == NULL)
4189 break;
4191 err = got_object_open_as_commit(&commit, repo, id);
4192 if (err)
4193 break;
4195 if (show_changed_paths && !reverse_display_order) {
4196 err = get_changed_paths(&changed_paths, commit, repo);
4197 if (err)
4198 break;
4201 if (search_pattern) {
4202 err = match_commit(&have_match, id, commit, &regex);
4203 if (err) {
4204 got_object_commit_close(commit);
4205 break;
4207 if (have_match == 0 && show_changed_paths)
4208 match_changed_paths(&have_match,
4209 &changed_paths, &regex);
4210 if (have_match == 0 && show_patch) {
4211 err = match_patch(&have_match, commit, id,
4212 path, diff_context, repo, &regex,
4213 tmpfile);
4214 if (err)
4215 break;
4217 if (have_match == 0) {
4218 got_object_commit_close(commit);
4219 TAILQ_FOREACH(pe, &changed_paths, entry) {
4220 free((char *)pe->path);
4221 free(pe->data);
4223 got_pathlist_free(&changed_paths);
4224 continue;
4228 if (reverse_display_order) {
4229 err = got_object_qid_alloc(&qid, id);
4230 if (err)
4231 break;
4232 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4233 got_object_commit_close(commit);
4234 } else {
4235 if (one_line)
4236 err = print_commit_oneline(commit, id,
4237 repo, refs_idmap);
4238 else
4239 err = print_commit(commit, id, repo, path,
4240 show_changed_paths ? &changed_paths : NULL,
4241 show_patch, diff_context, refs_idmap, NULL);
4242 got_object_commit_close(commit);
4243 if (err)
4244 break;
4246 if ((limit && --limit == 0) ||
4247 (end_id && got_object_id_cmp(id, end_id) == 0))
4248 break;
4250 TAILQ_FOREACH(pe, &changed_paths, entry) {
4251 free((char *)pe->path);
4252 free(pe->data);
4254 got_pathlist_free(&changed_paths);
4256 if (reverse_display_order) {
4257 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4258 err = got_object_open_as_commit(&commit, repo,
4259 &qid->id);
4260 if (err)
4261 break;
4262 if (show_changed_paths) {
4263 err = get_changed_paths(&changed_paths,
4264 commit, repo);
4265 if (err)
4266 break;
4268 if (one_line)
4269 err = print_commit_oneline(commit, &qid->id,
4270 repo, refs_idmap);
4271 else
4272 err = print_commit(commit, &qid->id, repo, path,
4273 show_changed_paths ? &changed_paths : NULL,
4274 show_patch, diff_context, refs_idmap, NULL);
4275 got_object_commit_close(commit);
4276 if (err)
4277 break;
4278 TAILQ_FOREACH(pe, &changed_paths, entry) {
4279 free((char *)pe->path);
4280 free(pe->data);
4282 got_pathlist_free(&changed_paths);
4285 done:
4286 while (!STAILQ_EMPTY(&reversed_commits)) {
4287 qid = STAILQ_FIRST(&reversed_commits);
4288 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4289 got_object_qid_free(qid);
4291 TAILQ_FOREACH(pe, &changed_paths, entry) {
4292 free((char *)pe->path);
4293 free(pe->data);
4295 got_pathlist_free(&changed_paths);
4296 if (search_pattern)
4297 regfree(&regex);
4298 got_commit_graph_close(graph);
4299 return err;
4302 __dead static void
4303 usage_log(void)
4305 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4306 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4307 "[-r repository-path] [-R] [path]\n", getprogname());
4308 exit(1);
4311 static int
4312 get_default_log_limit(void)
4314 const char *got_default_log_limit;
4315 long long n;
4316 const char *errstr;
4318 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4319 if (got_default_log_limit == NULL)
4320 return 0;
4321 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4322 if (errstr != NULL)
4323 return 0;
4324 return n;
4327 static const struct got_error *
4328 cmd_log(int argc, char *argv[])
4330 const struct got_error *error;
4331 struct got_repository *repo = NULL;
4332 struct got_worktree *worktree = NULL;
4333 struct got_object_id *start_id = NULL, *end_id = NULL;
4334 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4335 const char *start_commit = NULL, *end_commit = NULL;
4336 const char *search_pattern = NULL;
4337 int diff_context = -1, ch;
4338 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4339 int reverse_display_order = 0, one_line = 0;
4340 const char *errstr;
4341 struct got_reflist_head refs;
4342 struct got_reflist_object_id_map *refs_idmap = NULL;
4343 FILE *tmpfile = NULL;
4344 int *pack_fds = NULL;
4346 TAILQ_INIT(&refs);
4348 #ifndef PROFILE
4349 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4350 NULL)
4351 == -1)
4352 err(1, "pledge");
4353 #endif
4355 limit = get_default_log_limit();
4357 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4358 switch (ch) {
4359 case 'p':
4360 show_patch = 1;
4361 break;
4362 case 'P':
4363 show_changed_paths = 1;
4364 break;
4365 case 'c':
4366 start_commit = optarg;
4367 break;
4368 case 'C':
4369 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4370 &errstr);
4371 if (errstr != NULL)
4372 errx(1, "number of context lines is %s: %s",
4373 errstr, optarg);
4374 break;
4375 case 'l':
4376 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4377 if (errstr != NULL)
4378 errx(1, "number of commits is %s: %s",
4379 errstr, optarg);
4380 break;
4381 case 'b':
4382 log_branches = 1;
4383 break;
4384 case 'r':
4385 repo_path = realpath(optarg, NULL);
4386 if (repo_path == NULL)
4387 return got_error_from_errno2("realpath",
4388 optarg);
4389 got_path_strip_trailing_slashes(repo_path);
4390 break;
4391 case 'R':
4392 reverse_display_order = 1;
4393 break;
4394 case 's':
4395 one_line = 1;
4396 break;
4397 case 'S':
4398 search_pattern = optarg;
4399 break;
4400 case 'x':
4401 end_commit = optarg;
4402 break;
4403 default:
4404 usage_log();
4405 /* NOTREACHED */
4409 argc -= optind;
4410 argv += optind;
4412 if (diff_context == -1)
4413 diff_context = 3;
4414 else if (!show_patch)
4415 errx(1, "-C requires -p");
4417 if (one_line && (show_patch || show_changed_paths))
4418 errx(1, "cannot use -s with -p or -P");
4420 cwd = getcwd(NULL, 0);
4421 if (cwd == NULL) {
4422 error = got_error_from_errno("getcwd");
4423 goto done;
4426 error = got_repo_pack_fds_open(&pack_fds);
4427 if (error != NULL)
4428 goto done;
4430 if (repo_path == NULL) {
4431 error = got_worktree_open(&worktree, cwd);
4432 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4433 goto done;
4434 error = NULL;
4437 if (argc == 1) {
4438 if (worktree) {
4439 error = got_worktree_resolve_path(&path, worktree,
4440 argv[0]);
4441 if (error)
4442 goto done;
4443 } else {
4444 path = strdup(argv[0]);
4445 if (path == NULL) {
4446 error = got_error_from_errno("strdup");
4447 goto done;
4450 } else if (argc != 0)
4451 usage_log();
4453 if (repo_path == NULL) {
4454 repo_path = worktree ?
4455 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4457 if (repo_path == NULL) {
4458 error = got_error_from_errno("strdup");
4459 goto done;
4462 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4463 if (error != NULL)
4464 goto done;
4466 error = apply_unveil(got_repo_get_path(repo), 1,
4467 worktree ? got_worktree_get_root_path(worktree) : NULL);
4468 if (error)
4469 goto done;
4471 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4472 if (error)
4473 goto done;
4475 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4476 if (error)
4477 goto done;
4479 if (start_commit == NULL) {
4480 struct got_reference *head_ref;
4481 struct got_commit_object *commit = NULL;
4482 error = got_ref_open(&head_ref, repo,
4483 worktree ? got_worktree_get_head_ref_name(worktree)
4484 : GOT_REF_HEAD, 0);
4485 if (error != NULL)
4486 goto done;
4487 error = got_ref_resolve(&start_id, repo, head_ref);
4488 got_ref_close(head_ref);
4489 if (error != NULL)
4490 goto done;
4491 error = got_object_open_as_commit(&commit, repo,
4492 start_id);
4493 if (error != NULL)
4494 goto done;
4495 got_object_commit_close(commit);
4496 } else {
4497 error = got_repo_match_object_id(&start_id, NULL,
4498 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4499 if (error != NULL)
4500 goto done;
4502 if (end_commit != NULL) {
4503 error = got_repo_match_object_id(&end_id, NULL,
4504 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4505 if (error != NULL)
4506 goto done;
4509 if (worktree) {
4511 * If a path was specified on the command line it was resolved
4512 * to a path in the work tree above. Prepend the work tree's
4513 * path prefix to obtain the corresponding in-repository path.
4515 if (path) {
4516 const char *prefix;
4517 prefix = got_worktree_get_path_prefix(worktree);
4518 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4519 (path[0] != '\0') ? "/" : "", path) == -1) {
4520 error = got_error_from_errno("asprintf");
4521 goto done;
4524 } else
4525 error = got_repo_map_path(&in_repo_path, repo,
4526 path ? path : "");
4527 if (error != NULL)
4528 goto done;
4529 if (in_repo_path) {
4530 free(path);
4531 path = in_repo_path;
4534 if (worktree) {
4535 /* Release work tree lock. */
4536 got_worktree_close(worktree);
4537 worktree = NULL;
4540 if (search_pattern && show_patch) {
4541 tmpfile = got_opentemp();
4542 if (tmpfile == NULL) {
4543 error = got_error_from_errno("got_opentemp");
4544 goto done;
4548 error = print_commits(start_id, end_id, repo, path ? path : "",
4549 show_changed_paths, show_patch, search_pattern, diff_context,
4550 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4551 tmpfile);
4552 done:
4553 free(path);
4554 free(repo_path);
4555 free(cwd);
4556 if (worktree)
4557 got_worktree_close(worktree);
4558 if (repo) {
4559 const struct got_error *close_err = got_repo_close(repo);
4560 if (error == NULL)
4561 error = close_err;
4563 if (pack_fds) {
4564 const struct got_error *pack_err =
4565 got_repo_pack_fds_close(pack_fds);
4566 if (error == NULL)
4567 error = pack_err;
4569 if (refs_idmap)
4570 got_reflist_object_id_map_free(refs_idmap);
4571 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4572 error = got_error_from_errno("fclose");
4573 got_ref_list_free(&refs);
4574 return error;
4577 __dead static void
4578 usage_diff(void)
4580 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4581 "[-r repository-path] [-s] [-w] [-P] "
4582 "[object1 object2 | path ...]\n", getprogname());
4583 exit(1);
4586 struct print_diff_arg {
4587 struct got_repository *repo;
4588 struct got_worktree *worktree;
4589 int diff_context;
4590 const char *id_str;
4591 int header_shown;
4592 int diff_staged;
4593 int ignore_whitespace;
4594 int force_text_diff;
4595 FILE *f1;
4596 FILE *f2;
4600 * Create a file which contains the target path of a symlink so we can feed
4601 * it as content to the diff engine.
4603 static const struct got_error *
4604 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4605 const char *abspath)
4607 const struct got_error *err = NULL;
4608 char target_path[PATH_MAX];
4609 ssize_t target_len, outlen;
4611 *fd = -1;
4613 if (dirfd != -1) {
4614 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4615 if (target_len == -1)
4616 return got_error_from_errno2("readlinkat", abspath);
4617 } else {
4618 target_len = readlink(abspath, target_path, PATH_MAX);
4619 if (target_len == -1)
4620 return got_error_from_errno2("readlink", abspath);
4623 *fd = got_opentempfd();
4624 if (*fd == -1)
4625 return got_error_from_errno("got_opentempfd");
4627 outlen = write(*fd, target_path, target_len);
4628 if (outlen == -1) {
4629 err = got_error_from_errno("got_opentempfd");
4630 goto done;
4633 if (lseek(*fd, 0, SEEK_SET) == -1) {
4634 err = got_error_from_errno2("lseek", abspath);
4635 goto done;
4637 done:
4638 if (err) {
4639 close(*fd);
4640 *fd = -1;
4642 return err;
4645 static const struct got_error *
4646 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4647 const char *path, struct got_object_id *blob_id,
4648 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4649 int dirfd, const char *de_name)
4651 struct print_diff_arg *a = arg;
4652 const struct got_error *err = NULL;
4653 struct got_blob_object *blob1 = NULL;
4654 int fd = -1, fd1 = -1, fd2 = -1;
4655 FILE *f2 = NULL;
4656 char *abspath = NULL, *label1 = NULL;
4657 struct stat sb;
4658 off_t size1 = 0;
4659 int f2_exists = 1;
4661 if (a->diff_staged) {
4662 if (staged_status != GOT_STATUS_MODIFY &&
4663 staged_status != GOT_STATUS_ADD &&
4664 staged_status != GOT_STATUS_DELETE)
4665 return NULL;
4666 } else {
4667 if (staged_status == GOT_STATUS_DELETE)
4668 return NULL;
4669 if (status == GOT_STATUS_NONEXISTENT)
4670 return got_error_set_errno(ENOENT, path);
4671 if (status != GOT_STATUS_MODIFY &&
4672 status != GOT_STATUS_ADD &&
4673 status != GOT_STATUS_DELETE &&
4674 status != GOT_STATUS_CONFLICT)
4675 return NULL;
4678 err = got_opentemp_truncate(a->f1);
4679 if (err)
4680 return got_error_from_errno("got_opentemp_truncate");
4681 err = got_opentemp_truncate(a->f2);
4682 if (err)
4683 return got_error_from_errno("got_opentemp_truncate");
4685 if (!a->header_shown) {
4686 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4687 got_worktree_get_root_path(a->worktree));
4688 printf("commit - %s\n", a->id_str);
4689 printf("path + %s%s\n",
4690 got_worktree_get_root_path(a->worktree),
4691 a->diff_staged ? " (staged changes)" : "");
4692 a->header_shown = 1;
4695 if (a->diff_staged) {
4696 const char *label1 = NULL, *label2 = NULL;
4697 switch (staged_status) {
4698 case GOT_STATUS_MODIFY:
4699 label1 = path;
4700 label2 = path;
4701 break;
4702 case GOT_STATUS_ADD:
4703 label2 = path;
4704 break;
4705 case GOT_STATUS_DELETE:
4706 label1 = path;
4707 break;
4708 default:
4709 return got_error(GOT_ERR_FILE_STATUS);
4711 fd1 = got_opentempfd();
4712 if (fd1 == -1) {
4713 err = got_error_from_errno("got_opentempfd");
4714 goto done;
4716 fd2 = got_opentempfd();
4717 if (fd2 == -1) {
4718 err = got_error_from_errno("got_opentempfd");
4719 goto done;
4721 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4722 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4723 a->diff_context, a->ignore_whitespace, a->force_text_diff,
4724 a->repo, stdout);
4725 goto done;
4728 fd1 = got_opentempfd();
4729 if (fd1 == -1) {
4730 err = got_error_from_errno("got_opentempfd");
4731 goto done;
4734 if (staged_status == GOT_STATUS_ADD ||
4735 staged_status == GOT_STATUS_MODIFY) {
4736 char *id_str;
4737 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4738 8192, fd1);
4739 if (err)
4740 goto done;
4741 err = got_object_id_str(&id_str, staged_blob_id);
4742 if (err)
4743 goto done;
4744 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4745 err = got_error_from_errno("asprintf");
4746 free(id_str);
4747 goto done;
4749 free(id_str);
4750 } else if (status != GOT_STATUS_ADD) {
4751 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4752 fd1);
4753 if (err)
4754 goto done;
4757 if (status != GOT_STATUS_DELETE) {
4758 if (asprintf(&abspath, "%s/%s",
4759 got_worktree_get_root_path(a->worktree), path) == -1) {
4760 err = got_error_from_errno("asprintf");
4761 goto done;
4764 if (dirfd != -1) {
4765 fd = openat(dirfd, de_name,
4766 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4767 if (fd == -1) {
4768 if (!got_err_open_nofollow_on_symlink()) {
4769 err = got_error_from_errno2("openat",
4770 abspath);
4771 goto done;
4773 err = get_symlink_target_file(&fd, dirfd,
4774 de_name, abspath);
4775 if (err)
4776 goto done;
4778 } else {
4779 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4780 if (fd == -1) {
4781 if (!got_err_open_nofollow_on_symlink()) {
4782 err = got_error_from_errno2("open",
4783 abspath);
4784 goto done;
4786 err = get_symlink_target_file(&fd, dirfd,
4787 de_name, abspath);
4788 if (err)
4789 goto done;
4792 if (fstat(fd, &sb) == -1) {
4793 err = got_error_from_errno2("fstat", abspath);
4794 goto done;
4796 f2 = fdopen(fd, "r");
4797 if (f2 == NULL) {
4798 err = got_error_from_errno2("fdopen", abspath);
4799 goto done;
4801 fd = -1;
4802 } else {
4803 sb.st_size = 0;
4804 f2_exists = 0;
4807 if (blob1) {
4808 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4809 a->f1, blob1);
4810 if (err)
4811 goto done;
4814 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4815 f2_exists, sb.st_size, path, a->diff_context, a->ignore_whitespace,
4816 a->force_text_diff, stdout);
4817 done:
4818 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4819 err = got_error_from_errno("close");
4820 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4821 err = got_error_from_errno("close");
4822 if (blob1)
4823 got_object_blob_close(blob1);
4824 if (fd != -1 && close(fd) == -1 && err == NULL)
4825 err = got_error_from_errno("close");
4826 if (f2 && fclose(f2) == EOF && err == NULL)
4827 err = got_error_from_errno("fclose");
4828 free(abspath);
4829 return err;
4832 static const struct got_error *
4833 cmd_diff(int argc, char *argv[])
4835 const struct got_error *error;
4836 struct got_repository *repo = NULL;
4837 struct got_worktree *worktree = NULL;
4838 char *cwd = NULL, *repo_path = NULL;
4839 const char *commit_args[2] = { NULL, NULL };
4840 int ncommit_args = 0;
4841 struct got_object_id *ids[2] = { NULL, NULL };
4842 char *labels[2] = { NULL, NULL };
4843 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4844 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4845 int force_text_diff = 0, force_path = 0, rflag = 0;
4846 const char *errstr;
4847 struct got_reflist_head refs;
4848 struct got_pathlist_head paths;
4849 struct got_pathlist_entry *pe;
4850 FILE *f1 = NULL, *f2 = NULL;
4851 int fd1 = -1, fd2 = -1;
4852 int *pack_fds = NULL;
4854 TAILQ_INIT(&refs);
4855 TAILQ_INIT(&paths);
4857 #ifndef PROFILE
4858 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4859 NULL) == -1)
4860 err(1, "pledge");
4861 #endif
4863 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4864 switch (ch) {
4865 case 'a':
4866 force_text_diff = 1;
4867 break;
4868 case 'c':
4869 if (ncommit_args >= 2)
4870 errx(1, "too many -c options used");
4871 commit_args[ncommit_args++] = optarg;
4872 break;
4873 case 'C':
4874 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4875 &errstr);
4876 if (errstr != NULL)
4877 errx(1, "number of context lines is %s: %s",
4878 errstr, optarg);
4879 break;
4880 case 'r':
4881 repo_path = realpath(optarg, NULL);
4882 if (repo_path == NULL)
4883 return got_error_from_errno2("realpath",
4884 optarg);
4885 got_path_strip_trailing_slashes(repo_path);
4886 rflag = 1;
4887 break;
4888 case 's':
4889 diff_staged = 1;
4890 break;
4891 case 'w':
4892 ignore_whitespace = 1;
4893 break;
4894 case 'P':
4895 force_path = 1;
4896 break;
4897 default:
4898 usage_diff();
4899 /* NOTREACHED */
4903 argc -= optind;
4904 argv += optind;
4906 cwd = getcwd(NULL, 0);
4907 if (cwd == NULL) {
4908 error = got_error_from_errno("getcwd");
4909 goto done;
4912 error = got_repo_pack_fds_open(&pack_fds);
4913 if (error != NULL)
4914 goto done;
4916 if (repo_path == NULL) {
4917 error = got_worktree_open(&worktree, cwd);
4918 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4919 goto done;
4920 else
4921 error = NULL;
4922 if (worktree) {
4923 repo_path =
4924 strdup(got_worktree_get_repo_path(worktree));
4925 if (repo_path == NULL) {
4926 error = got_error_from_errno("strdup");
4927 goto done;
4929 } else {
4930 repo_path = strdup(cwd);
4931 if (repo_path == NULL) {
4932 error = got_error_from_errno("strdup");
4933 goto done;
4938 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4939 free(repo_path);
4940 if (error != NULL)
4941 goto done;
4943 if (rflag || worktree == NULL || ncommit_args > 0) {
4944 if (force_path) {
4945 error = got_error_msg(GOT_ERR_NOT_IMPL,
4946 "-P option can only be used when diffing "
4947 "a work tree");
4948 goto done;
4950 if (diff_staged) {
4951 error = got_error_msg(GOT_ERR_NOT_IMPL,
4952 "-s option can only be used when diffing "
4953 "a work tree");
4954 goto done;
4958 error = apply_unveil(got_repo_get_path(repo), 1,
4959 worktree ? got_worktree_get_root_path(worktree) : NULL);
4960 if (error)
4961 goto done;
4963 if ((!force_path && argc == 2) || ncommit_args > 0) {
4964 int obj_type = (ncommit_args > 0 ?
4965 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4966 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4967 NULL);
4968 if (error)
4969 goto done;
4970 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4971 const char *arg;
4972 if (ncommit_args > 0)
4973 arg = commit_args[i];
4974 else
4975 arg = argv[i];
4976 error = got_repo_match_object_id(&ids[i], &labels[i],
4977 arg, obj_type, &refs, repo);
4978 if (error) {
4979 if (error->code != GOT_ERR_NOT_REF &&
4980 error->code != GOT_ERR_NO_OBJ)
4981 goto done;
4982 if (ncommit_args > 0)
4983 goto done;
4984 error = NULL;
4985 break;
4990 f1 = got_opentemp();
4991 if (f1 == NULL) {
4992 error = got_error_from_errno("got_opentemp");
4993 goto done;
4996 f2 = got_opentemp();
4997 if (f2 == NULL) {
4998 error = got_error_from_errno("got_opentemp");
4999 goto done;
5002 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5003 struct print_diff_arg arg;
5004 char *id_str;
5006 if (worktree == NULL) {
5007 if (argc == 2 && ids[0] == NULL) {
5008 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5009 goto done;
5010 } else if (argc == 2 && ids[1] == NULL) {
5011 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5012 goto done;
5013 } else if (argc > 0) {
5014 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5015 "%s", "specified paths cannot be resolved");
5016 goto done;
5017 } else {
5018 error = got_error(GOT_ERR_NOT_WORKTREE);
5019 goto done;
5023 error = get_worktree_paths_from_argv(&paths, argc, argv,
5024 worktree);
5025 if (error)
5026 goto done;
5028 error = got_object_id_str(&id_str,
5029 got_worktree_get_base_commit_id(worktree));
5030 if (error)
5031 goto done;
5032 arg.repo = repo;
5033 arg.worktree = worktree;
5034 arg.diff_context = diff_context;
5035 arg.id_str = id_str;
5036 arg.header_shown = 0;
5037 arg.diff_staged = diff_staged;
5038 arg.ignore_whitespace = ignore_whitespace;
5039 arg.force_text_diff = force_text_diff;
5040 arg.f1 = f1;
5041 arg.f2 = f2;
5043 error = got_worktree_status(worktree, &paths, repo, 0,
5044 print_diff, &arg, check_cancelled, NULL);
5045 free(id_str);
5046 goto done;
5049 if (ncommit_args == 1) {
5050 struct got_commit_object *commit;
5051 error = got_object_open_as_commit(&commit, repo, ids[0]);
5052 if (error)
5053 goto done;
5055 labels[1] = labels[0];
5056 ids[1] = ids[0];
5057 if (got_object_commit_get_nparents(commit) > 0) {
5058 const struct got_object_id_queue *pids;
5059 struct got_object_qid *pid;
5060 pids = got_object_commit_get_parent_ids(commit);
5061 pid = STAILQ_FIRST(pids);
5062 ids[0] = got_object_id_dup(&pid->id);
5063 if (ids[0] == NULL) {
5064 error = got_error_from_errno(
5065 "got_object_id_dup");
5066 got_object_commit_close(commit);
5067 goto done;
5069 error = got_object_id_str(&labels[0], ids[0]);
5070 if (error) {
5071 got_object_commit_close(commit);
5072 goto done;
5074 } else {
5075 ids[0] = NULL;
5076 labels[0] = strdup("/dev/null");
5077 if (labels[0] == NULL) {
5078 error = got_error_from_errno("strdup");
5079 got_object_commit_close(commit);
5080 goto done;
5084 got_object_commit_close(commit);
5087 if (ncommit_args == 0 && argc > 2) {
5088 error = got_error_msg(GOT_ERR_BAD_PATH,
5089 "path arguments cannot be used when diffing two objects");
5090 goto done;
5093 if (ids[0]) {
5094 error = got_object_get_type(&type1, repo, ids[0]);
5095 if (error)
5096 goto done;
5099 error = got_object_get_type(&type2, repo, ids[1]);
5100 if (error)
5101 goto done;
5102 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5103 error = got_error(GOT_ERR_OBJ_TYPE);
5104 goto done;
5106 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5107 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5108 "path arguments cannot be used when diffing blobs");
5109 goto done;
5112 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5113 char *in_repo_path;
5114 struct got_pathlist_entry *new;
5115 if (worktree) {
5116 const char *prefix;
5117 char *p;
5118 error = got_worktree_resolve_path(&p, worktree,
5119 argv[i]);
5120 if (error)
5121 goto done;
5122 prefix = got_worktree_get_path_prefix(worktree);
5123 while (prefix[0] == '/')
5124 prefix++;
5125 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5126 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5127 p) == -1) {
5128 error = got_error_from_errno("asprintf");
5129 free(p);
5130 goto done;
5132 free(p);
5133 } else {
5134 char *mapped_path, *s;
5135 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5136 if (error)
5137 goto done;
5138 s = mapped_path;
5139 while (s[0] == '/')
5140 s++;
5141 in_repo_path = strdup(s);
5142 if (in_repo_path == NULL) {
5143 error = got_error_from_errno("asprintf");
5144 free(mapped_path);
5145 goto done;
5147 free(mapped_path);
5150 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5151 if (error || new == NULL /* duplicate */)
5152 free(in_repo_path);
5153 if (error)
5154 goto done;
5157 if (worktree) {
5158 /* Release work tree lock. */
5159 got_worktree_close(worktree);
5160 worktree = NULL;
5163 fd1 = got_opentempfd();
5164 if (fd1 == -1) {
5165 error = got_error_from_errno("got_opentempfd");
5166 goto done;
5169 fd2 = got_opentempfd();
5170 if (fd2 == -1) {
5171 error = got_error_from_errno("got_opentempfd");
5172 goto done;
5175 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5176 case GOT_OBJ_TYPE_BLOB:
5177 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5178 fd1, fd2, ids[0], ids[1], NULL, NULL, diff_context,
5179 ignore_whitespace, force_text_diff, repo, stdout);
5180 break;
5181 case GOT_OBJ_TYPE_TREE:
5182 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5183 ids[0], ids[1], &paths, "", "", diff_context,
5184 ignore_whitespace, force_text_diff, repo, stdout);
5185 break;
5186 case GOT_OBJ_TYPE_COMMIT:
5187 printf("diff %s %s\n", labels[0], labels[1]);
5188 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5189 fd1, fd2, ids[0], ids[1], &paths, diff_context,
5190 ignore_whitespace, force_text_diff, repo, stdout);
5191 break;
5192 default:
5193 error = got_error(GOT_ERR_OBJ_TYPE);
5195 done:
5196 free(labels[0]);
5197 free(labels[1]);
5198 free(ids[0]);
5199 free(ids[1]);
5200 if (worktree)
5201 got_worktree_close(worktree);
5202 if (repo) {
5203 const struct got_error *close_err = got_repo_close(repo);
5204 if (error == NULL)
5205 error = close_err;
5207 if (pack_fds) {
5208 const struct got_error *pack_err =
5209 got_repo_pack_fds_close(pack_fds);
5210 if (error == NULL)
5211 error = pack_err;
5213 TAILQ_FOREACH(pe, &paths, entry)
5214 free((char *)pe->path);
5215 got_pathlist_free(&paths);
5216 got_ref_list_free(&refs);
5217 if (f1 && fclose(f1) == EOF && error == NULL)
5218 error = got_error_from_errno("fclose");
5219 if (f2 && fclose(f2) == EOF && error == NULL)
5220 error = got_error_from_errno("fclose");
5221 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5222 error = got_error_from_errno("close");
5223 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5224 error = got_error_from_errno("close");
5225 return error;
5228 __dead static void
5229 usage_blame(void)
5231 fprintf(stderr,
5232 "usage: %s blame [-c commit] [-r repository-path] path\n",
5233 getprogname());
5234 exit(1);
5237 struct blame_line {
5238 int annotated;
5239 char *id_str;
5240 char *committer;
5241 char datebuf[11]; /* YYYY-MM-DD + NUL */
5244 struct blame_cb_args {
5245 struct blame_line *lines;
5246 int nlines;
5247 int nlines_prec;
5248 int lineno_cur;
5249 off_t *line_offsets;
5250 FILE *f;
5251 struct got_repository *repo;
5254 static const struct got_error *
5255 blame_cb(void *arg, int nlines, int lineno,
5256 struct got_commit_object *commit, struct got_object_id *id)
5258 const struct got_error *err = NULL;
5259 struct blame_cb_args *a = arg;
5260 struct blame_line *bline;
5261 char *line = NULL;
5262 size_t linesize = 0;
5263 off_t offset;
5264 struct tm tm;
5265 time_t committer_time;
5267 if (nlines != a->nlines ||
5268 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5269 return got_error(GOT_ERR_RANGE);
5271 if (sigint_received)
5272 return got_error(GOT_ERR_ITER_COMPLETED);
5274 if (lineno == -1)
5275 return NULL; /* no change in this commit */
5277 /* Annotate this line. */
5278 bline = &a->lines[lineno - 1];
5279 if (bline->annotated)
5280 return NULL;
5281 err = got_object_id_str(&bline->id_str, id);
5282 if (err)
5283 return err;
5285 bline->committer = strdup(got_object_commit_get_committer(commit));
5286 if (bline->committer == NULL) {
5287 err = got_error_from_errno("strdup");
5288 goto done;
5291 committer_time = got_object_commit_get_committer_time(commit);
5292 if (gmtime_r(&committer_time, &tm) == NULL)
5293 return got_error_from_errno("gmtime_r");
5294 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5295 &tm) == 0) {
5296 err = got_error(GOT_ERR_NO_SPACE);
5297 goto done;
5299 bline->annotated = 1;
5301 /* Print lines annotated so far. */
5302 bline = &a->lines[a->lineno_cur - 1];
5303 if (!bline->annotated)
5304 goto done;
5306 offset = a->line_offsets[a->lineno_cur - 1];
5307 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5308 err = got_error_from_errno("fseeko");
5309 goto done;
5312 while (bline->annotated) {
5313 char *smallerthan, *at, *nl, *committer;
5314 size_t len;
5316 if (getline(&line, &linesize, a->f) == -1) {
5317 if (ferror(a->f))
5318 err = got_error_from_errno("getline");
5319 break;
5322 committer = bline->committer;
5323 smallerthan = strchr(committer, '<');
5324 if (smallerthan && smallerthan[1] != '\0')
5325 committer = smallerthan + 1;
5326 at = strchr(committer, '@');
5327 if (at)
5328 *at = '\0';
5329 len = strlen(committer);
5330 if (len >= 9)
5331 committer[8] = '\0';
5333 nl = strchr(line, '\n');
5334 if (nl)
5335 *nl = '\0';
5336 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5337 bline->id_str, bline->datebuf, committer, line);
5339 a->lineno_cur++;
5340 bline = &a->lines[a->lineno_cur - 1];
5342 done:
5343 free(line);
5344 return err;
5347 static const struct got_error *
5348 cmd_blame(int argc, char *argv[])
5350 const struct got_error *error;
5351 struct got_repository *repo = NULL;
5352 struct got_worktree *worktree = NULL;
5353 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5354 char *link_target = NULL;
5355 struct got_object_id *obj_id = NULL;
5356 struct got_object_id *commit_id = NULL;
5357 struct got_commit_object *commit = NULL;
5358 struct got_blob_object *blob = NULL;
5359 char *commit_id_str = NULL;
5360 struct blame_cb_args bca;
5361 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5362 off_t filesize;
5363 int *pack_fds = NULL;
5364 FILE *f1 = NULL, *f2 = NULL;
5366 fd1 = got_opentempfd();
5367 if (fd1 == -1)
5368 return got_error_from_errno("got_opentempfd");
5370 memset(&bca, 0, sizeof(bca));
5372 #ifndef PROFILE
5373 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5374 NULL) == -1)
5375 err(1, "pledge");
5376 #endif
5378 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5379 switch (ch) {
5380 case 'c':
5381 commit_id_str = optarg;
5382 break;
5383 case 'r':
5384 repo_path = realpath(optarg, NULL);
5385 if (repo_path == NULL)
5386 return got_error_from_errno2("realpath",
5387 optarg);
5388 got_path_strip_trailing_slashes(repo_path);
5389 break;
5390 default:
5391 usage_blame();
5392 /* NOTREACHED */
5396 argc -= optind;
5397 argv += optind;
5399 if (argc == 1)
5400 path = argv[0];
5401 else
5402 usage_blame();
5404 cwd = getcwd(NULL, 0);
5405 if (cwd == NULL) {
5406 error = got_error_from_errno("getcwd");
5407 goto done;
5410 error = got_repo_pack_fds_open(&pack_fds);
5411 if (error != NULL)
5412 goto done;
5414 if (repo_path == NULL) {
5415 error = got_worktree_open(&worktree, cwd);
5416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5417 goto done;
5418 else
5419 error = NULL;
5420 if (worktree) {
5421 repo_path =
5422 strdup(got_worktree_get_repo_path(worktree));
5423 if (repo_path == NULL) {
5424 error = got_error_from_errno("strdup");
5425 if (error)
5426 goto done;
5428 } else {
5429 repo_path = strdup(cwd);
5430 if (repo_path == NULL) {
5431 error = got_error_from_errno("strdup");
5432 goto done;
5437 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5438 if (error != NULL)
5439 goto done;
5441 if (worktree) {
5442 const char *prefix = got_worktree_get_path_prefix(worktree);
5443 char *p;
5445 error = got_worktree_resolve_path(&p, worktree, path);
5446 if (error)
5447 goto done;
5448 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5449 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5450 p) == -1) {
5451 error = got_error_from_errno("asprintf");
5452 free(p);
5453 goto done;
5455 free(p);
5456 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5457 } else {
5458 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5459 if (error)
5460 goto done;
5461 error = got_repo_map_path(&in_repo_path, repo, path);
5463 if (error)
5464 goto done;
5466 if (commit_id_str == NULL) {
5467 struct got_reference *head_ref;
5468 error = got_ref_open(&head_ref, repo, worktree ?
5469 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5470 if (error != NULL)
5471 goto done;
5472 error = got_ref_resolve(&commit_id, repo, head_ref);
5473 got_ref_close(head_ref);
5474 if (error != NULL)
5475 goto done;
5476 } else {
5477 struct got_reflist_head refs;
5478 TAILQ_INIT(&refs);
5479 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5480 NULL);
5481 if (error)
5482 goto done;
5483 error = got_repo_match_object_id(&commit_id, NULL,
5484 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5485 got_ref_list_free(&refs);
5486 if (error)
5487 goto done;
5490 if (worktree) {
5491 /* Release work tree lock. */
5492 got_worktree_close(worktree);
5493 worktree = NULL;
5496 error = got_object_open_as_commit(&commit, repo, commit_id);
5497 if (error)
5498 goto done;
5500 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5501 commit, repo);
5502 if (error)
5503 goto done;
5505 error = got_object_id_by_path(&obj_id, repo, commit,
5506 link_target ? link_target : in_repo_path);
5507 if (error)
5508 goto done;
5510 error = got_object_get_type(&obj_type, repo, obj_id);
5511 if (error)
5512 goto done;
5514 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5515 error = got_error_path(link_target ? link_target : in_repo_path,
5516 GOT_ERR_OBJ_TYPE);
5517 goto done;
5520 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5521 if (error)
5522 goto done;
5523 bca.f = got_opentemp();
5524 if (bca.f == NULL) {
5525 error = got_error_from_errno("got_opentemp");
5526 goto done;
5528 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5529 &bca.line_offsets, bca.f, blob);
5530 if (error || bca.nlines == 0)
5531 goto done;
5533 /* Don't include \n at EOF in the blame line count. */
5534 if (bca.line_offsets[bca.nlines - 1] == filesize)
5535 bca.nlines--;
5537 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5538 if (bca.lines == NULL) {
5539 error = got_error_from_errno("calloc");
5540 goto done;
5542 bca.lineno_cur = 1;
5543 bca.nlines_prec = 0;
5544 i = bca.nlines;
5545 while (i > 0) {
5546 i /= 10;
5547 bca.nlines_prec++;
5549 bca.repo = repo;
5551 fd2 = got_opentempfd();
5552 if (fd2 == -1) {
5553 error = got_error_from_errno("got_opentempfd");
5554 goto done;
5556 fd3 = got_opentempfd();
5557 if (fd3 == -1) {
5558 error = got_error_from_errno("got_opentempfd");
5559 goto done;
5561 f1 = got_opentemp();
5562 if (f1 == NULL) {
5563 error = got_error_from_errno("got_opentemp");
5564 goto done;
5566 f2 = got_opentemp();
5567 if (f2 == NULL) {
5568 error = got_error_from_errno("got_opentemp");
5569 goto done;
5571 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5572 repo, blame_cb, &bca, check_cancelled, NULL, fd2, fd3, f1, f2);
5573 done:
5574 free(in_repo_path);
5575 free(link_target);
5576 free(repo_path);
5577 free(cwd);
5578 free(commit_id);
5579 free(obj_id);
5580 if (commit)
5581 got_object_commit_close(commit);
5583 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5584 error = got_error_from_errno("close");
5585 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5586 error = got_error_from_errno("close");
5587 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5588 error = got_error_from_errno("close");
5589 if (f1 && fclose(f1) == EOF && error == NULL)
5590 error = got_error_from_errno("fclose");
5591 if (f2 && fclose(f2) == EOF && error == NULL)
5592 error = got_error_from_errno("fclose");
5594 if (blob)
5595 got_object_blob_close(blob);
5596 if (worktree)
5597 got_worktree_close(worktree);
5598 if (repo) {
5599 const struct got_error *close_err = got_repo_close(repo);
5600 if (error == NULL)
5601 error = close_err;
5603 if (pack_fds) {
5604 const struct got_error *pack_err =
5605 got_repo_pack_fds_close(pack_fds);
5606 if (error == NULL)
5607 error = pack_err;
5609 if (bca.lines) {
5610 for (i = 0; i < bca.nlines; i++) {
5611 struct blame_line *bline = &bca.lines[i];
5612 free(bline->id_str);
5613 free(bline->committer);
5615 free(bca.lines);
5617 free(bca.line_offsets);
5618 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5619 error = got_error_from_errno("fclose");
5620 return error;
5623 __dead static void
5624 usage_tree(void)
5626 fprintf(stderr,
5627 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5628 getprogname());
5629 exit(1);
5632 static const struct got_error *
5633 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5634 const char *root_path, struct got_repository *repo)
5636 const struct got_error *err = NULL;
5637 int is_root_path = (strcmp(path, root_path) == 0);
5638 const char *modestr = "";
5639 mode_t mode = got_tree_entry_get_mode(te);
5640 char *link_target = NULL;
5642 path += strlen(root_path);
5643 while (path[0] == '/')
5644 path++;
5646 if (got_object_tree_entry_is_submodule(te))
5647 modestr = "$";
5648 else if (S_ISLNK(mode)) {
5649 int i;
5651 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5652 if (err)
5653 return err;
5654 for (i = 0; i < strlen(link_target); i++) {
5655 if (!isprint((unsigned char)link_target[i]))
5656 link_target[i] = '?';
5659 modestr = "@";
5661 else if (S_ISDIR(mode))
5662 modestr = "/";
5663 else if (mode & S_IXUSR)
5664 modestr = "*";
5666 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5667 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5668 link_target ? " -> ": "", link_target ? link_target : "");
5670 free(link_target);
5671 return NULL;
5674 static const struct got_error *
5675 print_tree(const char *path, struct got_commit_object *commit,
5676 int show_ids, int recurse, const char *root_path,
5677 struct got_repository *repo)
5679 const struct got_error *err = NULL;
5680 struct got_object_id *tree_id = NULL;
5681 struct got_tree_object *tree = NULL;
5682 int nentries, i;
5684 err = got_object_id_by_path(&tree_id, repo, commit, path);
5685 if (err)
5686 goto done;
5688 err = got_object_open_as_tree(&tree, repo, tree_id);
5689 if (err)
5690 goto done;
5691 nentries = got_object_tree_get_nentries(tree);
5692 for (i = 0; i < nentries; i++) {
5693 struct got_tree_entry *te;
5694 char *id = NULL;
5696 if (sigint_received || sigpipe_received)
5697 break;
5699 te = got_object_tree_get_entry(tree, i);
5700 if (show_ids) {
5701 char *id_str;
5702 err = got_object_id_str(&id_str,
5703 got_tree_entry_get_id(te));
5704 if (err)
5705 goto done;
5706 if (asprintf(&id, "%s ", id_str) == -1) {
5707 err = got_error_from_errno("asprintf");
5708 free(id_str);
5709 goto done;
5711 free(id_str);
5713 err = print_entry(te, id, path, root_path, repo);
5714 free(id);
5715 if (err)
5716 goto done;
5718 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5719 char *child_path;
5720 if (asprintf(&child_path, "%s%s%s", path,
5721 path[0] == '/' && path[1] == '\0' ? "" : "/",
5722 got_tree_entry_get_name(te)) == -1) {
5723 err = got_error_from_errno("asprintf");
5724 goto done;
5726 err = print_tree(child_path, commit, show_ids, 1,
5727 root_path, repo);
5728 free(child_path);
5729 if (err)
5730 goto done;
5733 done:
5734 if (tree)
5735 got_object_tree_close(tree);
5736 free(tree_id);
5737 return err;
5740 static const struct got_error *
5741 cmd_tree(int argc, char *argv[])
5743 const struct got_error *error;
5744 struct got_repository *repo = NULL;
5745 struct got_worktree *worktree = NULL;
5746 const char *path, *refname = NULL;
5747 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5748 struct got_object_id *commit_id = NULL;
5749 struct got_commit_object *commit = NULL;
5750 char *commit_id_str = NULL;
5751 int show_ids = 0, recurse = 0;
5752 int ch;
5753 int *pack_fds = NULL;
5755 #ifndef PROFILE
5756 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5757 NULL) == -1)
5758 err(1, "pledge");
5759 #endif
5761 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5762 switch (ch) {
5763 case 'c':
5764 commit_id_str = optarg;
5765 break;
5766 case 'r':
5767 repo_path = realpath(optarg, NULL);
5768 if (repo_path == NULL)
5769 return got_error_from_errno2("realpath",
5770 optarg);
5771 got_path_strip_trailing_slashes(repo_path);
5772 break;
5773 case 'i':
5774 show_ids = 1;
5775 break;
5776 case 'R':
5777 recurse = 1;
5778 break;
5779 default:
5780 usage_tree();
5781 /* NOTREACHED */
5785 argc -= optind;
5786 argv += optind;
5788 if (argc == 1)
5789 path = argv[0];
5790 else if (argc > 1)
5791 usage_tree();
5792 else
5793 path = NULL;
5795 cwd = getcwd(NULL, 0);
5796 if (cwd == NULL) {
5797 error = got_error_from_errno("getcwd");
5798 goto done;
5801 error = got_repo_pack_fds_open(&pack_fds);
5802 if (error != NULL)
5803 goto done;
5805 if (repo_path == NULL) {
5806 error = got_worktree_open(&worktree, cwd);
5807 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5808 goto done;
5809 else
5810 error = NULL;
5811 if (worktree) {
5812 repo_path =
5813 strdup(got_worktree_get_repo_path(worktree));
5814 if (repo_path == NULL)
5815 error = got_error_from_errno("strdup");
5816 if (error)
5817 goto done;
5818 } else {
5819 repo_path = strdup(cwd);
5820 if (repo_path == NULL) {
5821 error = got_error_from_errno("strdup");
5822 goto done;
5827 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5828 if (error != NULL)
5829 goto done;
5831 if (worktree) {
5832 const char *prefix = got_worktree_get_path_prefix(worktree);
5833 char *p;
5835 if (path == NULL)
5836 path = "";
5837 error = got_worktree_resolve_path(&p, worktree, path);
5838 if (error)
5839 goto done;
5840 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5841 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5842 p) == -1) {
5843 error = got_error_from_errno("asprintf");
5844 free(p);
5845 goto done;
5847 free(p);
5848 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5849 if (error)
5850 goto done;
5851 } else {
5852 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5853 if (error)
5854 goto done;
5855 if (path == NULL)
5856 path = "/";
5857 error = got_repo_map_path(&in_repo_path, repo, path);
5858 if (error != NULL)
5859 goto done;
5862 if (commit_id_str == NULL) {
5863 struct got_reference *head_ref;
5864 if (worktree)
5865 refname = got_worktree_get_head_ref_name(worktree);
5866 else
5867 refname = GOT_REF_HEAD;
5868 error = got_ref_open(&head_ref, repo, refname, 0);
5869 if (error != NULL)
5870 goto done;
5871 error = got_ref_resolve(&commit_id, repo, head_ref);
5872 got_ref_close(head_ref);
5873 if (error != NULL)
5874 goto done;
5875 } else {
5876 struct got_reflist_head refs;
5877 TAILQ_INIT(&refs);
5878 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5879 NULL);
5880 if (error)
5881 goto done;
5882 error = got_repo_match_object_id(&commit_id, NULL,
5883 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5884 got_ref_list_free(&refs);
5885 if (error)
5886 goto done;
5889 if (worktree) {
5890 /* Release work tree lock. */
5891 got_worktree_close(worktree);
5892 worktree = NULL;
5895 error = got_object_open_as_commit(&commit, repo, commit_id);
5896 if (error)
5897 goto done;
5899 error = print_tree(in_repo_path, commit, show_ids, recurse,
5900 in_repo_path, repo);
5901 done:
5902 free(in_repo_path);
5903 free(repo_path);
5904 free(cwd);
5905 free(commit_id);
5906 if (commit)
5907 got_object_commit_close(commit);
5908 if (worktree)
5909 got_worktree_close(worktree);
5910 if (repo) {
5911 const struct got_error *close_err = got_repo_close(repo);
5912 if (error == NULL)
5913 error = close_err;
5915 if (pack_fds) {
5916 const struct got_error *pack_err =
5917 got_repo_pack_fds_close(pack_fds);
5918 if (error == NULL)
5919 error = pack_err;
5921 return error;
5924 __dead static void
5925 usage_status(void)
5927 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5928 "[-S status-codes] [path ...]\n", getprogname());
5929 exit(1);
5932 struct got_status_arg {
5933 char *status_codes;
5934 int suppress;
5937 static const struct got_error *
5938 print_status(void *arg, unsigned char status, unsigned char staged_status,
5939 const char *path, struct got_object_id *blob_id,
5940 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5941 int dirfd, const char *de_name)
5943 struct got_status_arg *st = arg;
5945 if (status == staged_status && (status == GOT_STATUS_DELETE))
5946 status = GOT_STATUS_NO_CHANGE;
5947 if (st != NULL && st->status_codes) {
5948 size_t ncodes = strlen(st->status_codes);
5949 int i, j = 0;
5951 for (i = 0; i < ncodes ; i++) {
5952 if (st->suppress) {
5953 if (status == st->status_codes[i] ||
5954 staged_status == st->status_codes[i]) {
5955 j++;
5956 continue;
5958 } else {
5959 if (status == st->status_codes[i] ||
5960 staged_status == st->status_codes[i])
5961 break;
5965 if (st->suppress && j == 0)
5966 goto print;
5968 if (i == ncodes)
5969 return NULL;
5971 print:
5972 printf("%c%c %s\n", status, staged_status, path);
5973 return NULL;
5976 static const struct got_error *
5977 cmd_status(int argc, char *argv[])
5979 const struct got_error *error = NULL;
5980 struct got_repository *repo = NULL;
5981 struct got_worktree *worktree = NULL;
5982 struct got_status_arg st;
5983 char *cwd = NULL;
5984 struct got_pathlist_head paths;
5985 struct got_pathlist_entry *pe;
5986 int ch, i, no_ignores = 0;
5987 int *pack_fds = NULL;
5989 TAILQ_INIT(&paths);
5991 memset(&st, 0, sizeof(st));
5992 st.status_codes = NULL;
5993 st.suppress = 0;
5995 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5996 switch (ch) {
5997 case 'I':
5998 no_ignores = 1;
5999 break;
6000 case 'S':
6001 if (st.status_codes != NULL && st.suppress == 0)
6002 option_conflict('S', 's');
6003 st.suppress = 1;
6004 /* fallthrough */
6005 case 's':
6006 for (i = 0; i < strlen(optarg); i++) {
6007 switch (optarg[i]) {
6008 case GOT_STATUS_MODIFY:
6009 case GOT_STATUS_ADD:
6010 case GOT_STATUS_DELETE:
6011 case GOT_STATUS_CONFLICT:
6012 case GOT_STATUS_MISSING:
6013 case GOT_STATUS_OBSTRUCTED:
6014 case GOT_STATUS_UNVERSIONED:
6015 case GOT_STATUS_MODE_CHANGE:
6016 case GOT_STATUS_NONEXISTENT:
6017 break;
6018 default:
6019 errx(1, "invalid status code '%c'",
6020 optarg[i]);
6023 if (ch == 's' && st.suppress)
6024 option_conflict('s', 'S');
6025 st.status_codes = optarg;
6026 break;
6027 default:
6028 usage_status();
6029 /* NOTREACHED */
6033 argc -= optind;
6034 argv += optind;
6036 #ifndef PROFILE
6037 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6038 NULL) == -1)
6039 err(1, "pledge");
6040 #endif
6041 cwd = getcwd(NULL, 0);
6042 if (cwd == NULL) {
6043 error = got_error_from_errno("getcwd");
6044 goto done;
6047 error = got_repo_pack_fds_open(&pack_fds);
6048 if (error != NULL)
6049 goto done;
6051 error = got_worktree_open(&worktree, cwd);
6052 if (error) {
6053 if (error->code == GOT_ERR_NOT_WORKTREE)
6054 error = wrap_not_worktree_error(error, "status", cwd);
6055 goto done;
6058 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6059 NULL, pack_fds);
6060 if (error != NULL)
6061 goto done;
6063 error = apply_unveil(got_repo_get_path(repo), 1,
6064 got_worktree_get_root_path(worktree));
6065 if (error)
6066 goto done;
6068 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6069 if (error)
6070 goto done;
6072 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6073 print_status, &st, check_cancelled, NULL);
6074 done:
6075 if (pack_fds) {
6076 const struct got_error *pack_err =
6077 got_repo_pack_fds_close(pack_fds);
6078 if (error == NULL)
6079 error = pack_err;
6082 TAILQ_FOREACH(pe, &paths, entry)
6083 free((char *)pe->path);
6084 got_pathlist_free(&paths);
6085 free(cwd);
6086 return error;
6089 __dead static void
6090 usage_ref(void)
6092 fprintf(stderr,
6093 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6094 "[-s reference] [-d] [name]\n",
6095 getprogname());
6096 exit(1);
6099 static const struct got_error *
6100 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6102 static const struct got_error *err = NULL;
6103 struct got_reflist_head refs;
6104 struct got_reflist_entry *re;
6106 TAILQ_INIT(&refs);
6107 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6108 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6109 repo);
6110 if (err)
6111 return err;
6113 TAILQ_FOREACH(re, &refs, entry) {
6114 char *refstr;
6115 refstr = got_ref_to_str(re->ref);
6116 if (refstr == NULL) {
6117 err = got_error_from_errno("got_ref_to_str");
6118 break;
6120 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6121 free(refstr);
6124 got_ref_list_free(&refs);
6125 return err;
6128 static const struct got_error *
6129 delete_ref_by_name(struct got_repository *repo, const char *refname)
6131 const struct got_error *err;
6132 struct got_reference *ref;
6134 err = got_ref_open(&ref, repo, refname, 0);
6135 if (err)
6136 return err;
6138 err = delete_ref(repo, ref);
6139 got_ref_close(ref);
6140 return err;
6143 static const struct got_error *
6144 add_ref(struct got_repository *repo, const char *refname, const char *target)
6146 const struct got_error *err = NULL;
6147 struct got_object_id *id = NULL;
6148 struct got_reference *ref = NULL;
6149 struct got_reflist_head refs;
6152 * Don't let the user create a reference name with a leading '-'.
6153 * While technically a valid reference name, this case is usually
6154 * an unintended typo.
6156 if (refname[0] == '-')
6157 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6159 TAILQ_INIT(&refs);
6160 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6161 if (err)
6162 goto done;
6163 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6164 &refs, repo);
6165 got_ref_list_free(&refs);
6166 if (err)
6167 goto done;
6169 err = got_ref_alloc(&ref, refname, id);
6170 if (err)
6171 goto done;
6173 err = got_ref_write(ref, repo);
6174 done:
6175 if (ref)
6176 got_ref_close(ref);
6177 free(id);
6178 return err;
6181 static const struct got_error *
6182 add_symref(struct got_repository *repo, const char *refname, const char *target)
6184 const struct got_error *err = NULL;
6185 struct got_reference *ref = NULL;
6186 struct got_reference *target_ref = NULL;
6189 * Don't let the user create a reference name with a leading '-'.
6190 * While technically a valid reference name, this case is usually
6191 * an unintended typo.
6193 if (refname[0] == '-')
6194 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6196 err = got_ref_open(&target_ref, repo, target, 0);
6197 if (err)
6198 return err;
6200 err = got_ref_alloc_symref(&ref, refname, target_ref);
6201 if (err)
6202 goto done;
6204 err = got_ref_write(ref, repo);
6205 done:
6206 if (target_ref)
6207 got_ref_close(target_ref);
6208 if (ref)
6209 got_ref_close(ref);
6210 return err;
6213 static const struct got_error *
6214 cmd_ref(int argc, char *argv[])
6216 const struct got_error *error = NULL;
6217 struct got_repository *repo = NULL;
6218 struct got_worktree *worktree = NULL;
6219 char *cwd = NULL, *repo_path = NULL;
6220 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6221 const char *obj_arg = NULL, *symref_target= NULL;
6222 char *refname = NULL;
6223 int *pack_fds = NULL;
6225 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6226 switch (ch) {
6227 case 'c':
6228 obj_arg = optarg;
6229 break;
6230 case 'd':
6231 do_delete = 1;
6232 break;
6233 case 'r':
6234 repo_path = realpath(optarg, NULL);
6235 if (repo_path == NULL)
6236 return got_error_from_errno2("realpath",
6237 optarg);
6238 got_path_strip_trailing_slashes(repo_path);
6239 break;
6240 case 'l':
6241 do_list = 1;
6242 break;
6243 case 's':
6244 symref_target = optarg;
6245 break;
6246 case 't':
6247 sort_by_time = 1;
6248 break;
6249 default:
6250 usage_ref();
6251 /* NOTREACHED */
6255 if (obj_arg && do_list)
6256 option_conflict('c', 'l');
6257 if (obj_arg && do_delete)
6258 option_conflict('c', 'd');
6259 if (obj_arg && symref_target)
6260 option_conflict('c', 's');
6261 if (symref_target && do_delete)
6262 option_conflict('s', 'd');
6263 if (symref_target && do_list)
6264 option_conflict('s', 'l');
6265 if (do_delete && do_list)
6266 option_conflict('d', 'l');
6267 if (sort_by_time && !do_list)
6268 errx(1, "-t option requires -l option");
6270 argc -= optind;
6271 argv += optind;
6273 if (do_list) {
6274 if (argc != 0 && argc != 1)
6275 usage_ref();
6276 if (argc == 1) {
6277 refname = strdup(argv[0]);
6278 if (refname == NULL) {
6279 error = got_error_from_errno("strdup");
6280 goto done;
6283 } else {
6284 if (argc != 1)
6285 usage_ref();
6286 refname = strdup(argv[0]);
6287 if (refname == NULL) {
6288 error = got_error_from_errno("strdup");
6289 goto done;
6293 if (refname)
6294 got_path_strip_trailing_slashes(refname);
6296 #ifndef PROFILE
6297 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6298 "sendfd unveil", NULL) == -1)
6299 err(1, "pledge");
6300 #endif
6301 cwd = getcwd(NULL, 0);
6302 if (cwd == NULL) {
6303 error = got_error_from_errno("getcwd");
6304 goto done;
6307 error = got_repo_pack_fds_open(&pack_fds);
6308 if (error != NULL)
6309 goto done;
6311 if (repo_path == NULL) {
6312 error = got_worktree_open(&worktree, cwd);
6313 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6314 goto done;
6315 else
6316 error = NULL;
6317 if (worktree) {
6318 repo_path =
6319 strdup(got_worktree_get_repo_path(worktree));
6320 if (repo_path == NULL)
6321 error = got_error_from_errno("strdup");
6322 if (error)
6323 goto done;
6324 } else {
6325 repo_path = strdup(cwd);
6326 if (repo_path == NULL) {
6327 error = got_error_from_errno("strdup");
6328 goto done;
6333 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6334 if (error != NULL)
6335 goto done;
6337 #ifndef PROFILE
6338 if (do_list) {
6339 /* Remove "cpath" promise. */
6340 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6341 NULL) == -1)
6342 err(1, "pledge");
6344 #endif
6346 error = apply_unveil(got_repo_get_path(repo), do_list,
6347 worktree ? got_worktree_get_root_path(worktree) : NULL);
6348 if (error)
6349 goto done;
6351 if (do_list)
6352 error = list_refs(repo, refname, sort_by_time);
6353 else if (do_delete)
6354 error = delete_ref_by_name(repo, refname);
6355 else if (symref_target)
6356 error = add_symref(repo, refname, symref_target);
6357 else {
6358 if (obj_arg == NULL)
6359 usage_ref();
6360 error = add_ref(repo, refname, obj_arg);
6362 done:
6363 free(refname);
6364 if (repo) {
6365 const struct got_error *close_err = got_repo_close(repo);
6366 if (error == NULL)
6367 error = close_err;
6369 if (worktree)
6370 got_worktree_close(worktree);
6371 if (pack_fds) {
6372 const struct got_error *pack_err =
6373 got_repo_pack_fds_close(pack_fds);
6374 if (error == NULL)
6375 error = pack_err;
6377 free(cwd);
6378 free(repo_path);
6379 return error;
6382 __dead static void
6383 usage_branch(void)
6385 fprintf(stderr,
6386 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6387 "[-n] [name]\n", getprogname());
6388 exit(1);
6391 static const struct got_error *
6392 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6393 struct got_reference *ref)
6395 const struct got_error *err = NULL;
6396 const char *refname, *marker = " ";
6397 char *refstr;
6399 refname = got_ref_get_name(ref);
6400 if (worktree && strcmp(refname,
6401 got_worktree_get_head_ref_name(worktree)) == 0) {
6402 struct got_object_id *id = NULL;
6404 err = got_ref_resolve(&id, repo, ref);
6405 if (err)
6406 return err;
6407 if (got_object_id_cmp(id,
6408 got_worktree_get_base_commit_id(worktree)) == 0)
6409 marker = "* ";
6410 else
6411 marker = "~ ";
6412 free(id);
6415 if (strncmp(refname, "refs/heads/", 11) == 0)
6416 refname += 11;
6417 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6418 refname += 18;
6419 if (strncmp(refname, "refs/remotes/", 13) == 0)
6420 refname += 13;
6422 refstr = got_ref_to_str(ref);
6423 if (refstr == NULL)
6424 return got_error_from_errno("got_ref_to_str");
6426 printf("%s%s: %s\n", marker, refname, refstr);
6427 free(refstr);
6428 return NULL;
6431 static const struct got_error *
6432 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6434 const char *refname;
6436 if (worktree == NULL)
6437 return got_error(GOT_ERR_NOT_WORKTREE);
6439 refname = got_worktree_get_head_ref_name(worktree);
6441 if (strncmp(refname, "refs/heads/", 11) == 0)
6442 refname += 11;
6443 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6444 refname += 18;
6446 printf("%s\n", refname);
6448 return NULL;
6451 static const struct got_error *
6452 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6453 int sort_by_time)
6455 static const struct got_error *err = NULL;
6456 struct got_reflist_head refs;
6457 struct got_reflist_entry *re;
6458 struct got_reference *temp_ref = NULL;
6459 int rebase_in_progress, histedit_in_progress;
6461 TAILQ_INIT(&refs);
6463 if (worktree) {
6464 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6465 worktree);
6466 if (err)
6467 return err;
6469 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6470 worktree);
6471 if (err)
6472 return err;
6474 if (rebase_in_progress || histedit_in_progress) {
6475 err = got_ref_open(&temp_ref, repo,
6476 got_worktree_get_head_ref_name(worktree), 0);
6477 if (err)
6478 return err;
6479 list_branch(repo, worktree, temp_ref);
6480 got_ref_close(temp_ref);
6484 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6485 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6486 repo);
6487 if (err)
6488 return err;
6490 TAILQ_FOREACH(re, &refs, entry)
6491 list_branch(repo, worktree, re->ref);
6493 got_ref_list_free(&refs);
6495 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6496 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6497 repo);
6498 if (err)
6499 return err;
6501 TAILQ_FOREACH(re, &refs, entry)
6502 list_branch(repo, worktree, re->ref);
6504 got_ref_list_free(&refs);
6506 return NULL;
6509 static const struct got_error *
6510 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6511 const char *branch_name)
6513 const struct got_error *err = NULL;
6514 struct got_reference *ref = NULL;
6515 char *refname, *remote_refname = NULL;
6517 if (strncmp(branch_name, "refs/", 5) == 0)
6518 branch_name += 5;
6519 if (strncmp(branch_name, "heads/", 6) == 0)
6520 branch_name += 6;
6521 else if (strncmp(branch_name, "remotes/", 8) == 0)
6522 branch_name += 8;
6524 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6525 return got_error_from_errno("asprintf");
6527 if (asprintf(&remote_refname, "refs/remotes/%s",
6528 branch_name) == -1) {
6529 err = got_error_from_errno("asprintf");
6530 goto done;
6533 err = got_ref_open(&ref, repo, refname, 0);
6534 if (err) {
6535 const struct got_error *err2;
6536 if (err->code != GOT_ERR_NOT_REF)
6537 goto done;
6539 * Keep 'err' intact such that if neither branch exists
6540 * we report "refs/heads" rather than "refs/remotes" in
6541 * our error message.
6543 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6544 if (err2)
6545 goto done;
6546 err = NULL;
6549 if (worktree &&
6550 strcmp(got_worktree_get_head_ref_name(worktree),
6551 got_ref_get_name(ref)) == 0) {
6552 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6553 "will not delete this work tree's current branch");
6554 goto done;
6557 err = delete_ref(repo, ref);
6558 done:
6559 if (ref)
6560 got_ref_close(ref);
6561 free(refname);
6562 free(remote_refname);
6563 return err;
6566 static const struct got_error *
6567 add_branch(struct got_repository *repo, const char *branch_name,
6568 struct got_object_id *base_commit_id)
6570 const struct got_error *err = NULL;
6571 struct got_reference *ref = NULL;
6572 char *base_refname = NULL, *refname = NULL;
6575 * Don't let the user create a branch name with a leading '-'.
6576 * While technically a valid reference name, this case is usually
6577 * an unintended typo.
6579 if (branch_name[0] == '-')
6580 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6582 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6583 branch_name += 11;
6585 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6586 err = got_error_from_errno("asprintf");
6587 goto done;
6590 err = got_ref_open(&ref, repo, refname, 0);
6591 if (err == NULL) {
6592 err = got_error(GOT_ERR_BRANCH_EXISTS);
6593 goto done;
6594 } else if (err->code != GOT_ERR_NOT_REF)
6595 goto done;
6597 err = got_ref_alloc(&ref, refname, base_commit_id);
6598 if (err)
6599 goto done;
6601 err = got_ref_write(ref, repo);
6602 done:
6603 if (ref)
6604 got_ref_close(ref);
6605 free(base_refname);
6606 free(refname);
6607 return err;
6610 static const struct got_error *
6611 cmd_branch(int argc, char *argv[])
6613 const struct got_error *error = NULL;
6614 struct got_repository *repo = NULL;
6615 struct got_worktree *worktree = NULL;
6616 char *cwd = NULL, *repo_path = NULL;
6617 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6618 const char *delref = NULL, *commit_id_arg = NULL;
6619 struct got_reference *ref = NULL;
6620 struct got_pathlist_head paths;
6621 struct got_pathlist_entry *pe;
6622 struct got_object_id *commit_id = NULL;
6623 char *commit_id_str = NULL;
6624 int *pack_fds = NULL;
6626 TAILQ_INIT(&paths);
6628 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6629 switch (ch) {
6630 case 'c':
6631 commit_id_arg = optarg;
6632 break;
6633 case 'd':
6634 delref = optarg;
6635 break;
6636 case 'r':
6637 repo_path = realpath(optarg, NULL);
6638 if (repo_path == NULL)
6639 return got_error_from_errno2("realpath",
6640 optarg);
6641 got_path_strip_trailing_slashes(repo_path);
6642 break;
6643 case 'l':
6644 do_list = 1;
6645 break;
6646 case 'n':
6647 do_update = 0;
6648 break;
6649 case 't':
6650 sort_by_time = 1;
6651 break;
6652 default:
6653 usage_branch();
6654 /* NOTREACHED */
6658 if (do_list && delref)
6659 option_conflict('l', 'd');
6660 if (sort_by_time && !do_list)
6661 errx(1, "-t option requires -l option");
6663 argc -= optind;
6664 argv += optind;
6666 if (!do_list && !delref && argc == 0)
6667 do_show = 1;
6669 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6670 errx(1, "-c option can only be used when creating a branch");
6672 if (do_list || delref) {
6673 if (argc > 0)
6674 usage_branch();
6675 } else if (!do_show && argc != 1)
6676 usage_branch();
6678 #ifndef PROFILE
6679 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6680 "sendfd unveil", NULL) == -1)
6681 err(1, "pledge");
6682 #endif
6683 cwd = getcwd(NULL, 0);
6684 if (cwd == NULL) {
6685 error = got_error_from_errno("getcwd");
6686 goto done;
6689 error = got_repo_pack_fds_open(&pack_fds);
6690 if (error != NULL)
6691 goto done;
6693 if (repo_path == NULL) {
6694 error = got_worktree_open(&worktree, cwd);
6695 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6696 goto done;
6697 else
6698 error = NULL;
6699 if (worktree) {
6700 repo_path =
6701 strdup(got_worktree_get_repo_path(worktree));
6702 if (repo_path == NULL)
6703 error = got_error_from_errno("strdup");
6704 if (error)
6705 goto done;
6706 } else {
6707 repo_path = strdup(cwd);
6708 if (repo_path == NULL) {
6709 error = got_error_from_errno("strdup");
6710 goto done;
6715 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6716 if (error != NULL)
6717 goto done;
6719 #ifndef PROFILE
6720 if (do_list || do_show) {
6721 /* Remove "cpath" promise. */
6722 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6723 NULL) == -1)
6724 err(1, "pledge");
6726 #endif
6728 error = apply_unveil(got_repo_get_path(repo), do_list,
6729 worktree ? got_worktree_get_root_path(worktree) : NULL);
6730 if (error)
6731 goto done;
6733 if (do_show)
6734 error = show_current_branch(repo, worktree);
6735 else if (do_list)
6736 error = list_branches(repo, worktree, sort_by_time);
6737 else if (delref)
6738 error = delete_branch(repo, worktree, delref);
6739 else {
6740 struct got_reflist_head refs;
6741 TAILQ_INIT(&refs);
6742 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6743 NULL);
6744 if (error)
6745 goto done;
6746 if (commit_id_arg == NULL)
6747 commit_id_arg = worktree ?
6748 got_worktree_get_head_ref_name(worktree) :
6749 GOT_REF_HEAD;
6750 error = got_repo_match_object_id(&commit_id, NULL,
6751 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6752 got_ref_list_free(&refs);
6753 if (error)
6754 goto done;
6755 error = add_branch(repo, argv[0], commit_id);
6756 if (error)
6757 goto done;
6758 if (worktree && do_update) {
6759 struct got_update_progress_arg upa;
6760 char *branch_refname = NULL;
6762 error = got_object_id_str(&commit_id_str, commit_id);
6763 if (error)
6764 goto done;
6765 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6766 worktree);
6767 if (error)
6768 goto done;
6769 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6770 == -1) {
6771 error = got_error_from_errno("asprintf");
6772 goto done;
6774 error = got_ref_open(&ref, repo, branch_refname, 0);
6775 free(branch_refname);
6776 if (error)
6777 goto done;
6778 error = switch_head_ref(ref, commit_id, worktree,
6779 repo);
6780 if (error)
6781 goto done;
6782 error = got_worktree_set_base_commit_id(worktree, repo,
6783 commit_id);
6784 if (error)
6785 goto done;
6786 memset(&upa, 0, sizeof(upa));
6787 error = got_worktree_checkout_files(worktree, &paths,
6788 repo, update_progress, &upa, check_cancelled,
6789 NULL);
6790 if (error)
6791 goto done;
6792 if (upa.did_something) {
6793 printf("Updated to %s: %s\n",
6794 got_worktree_get_head_ref_name(worktree),
6795 commit_id_str);
6797 print_update_progress_stats(&upa);
6800 done:
6801 if (ref)
6802 got_ref_close(ref);
6803 if (repo) {
6804 const struct got_error *close_err = got_repo_close(repo);
6805 if (error == NULL)
6806 error = close_err;
6808 if (worktree)
6809 got_worktree_close(worktree);
6810 if (pack_fds) {
6811 const struct got_error *pack_err =
6812 got_repo_pack_fds_close(pack_fds);
6813 if (error == NULL)
6814 error = pack_err;
6816 free(cwd);
6817 free(repo_path);
6818 free(commit_id);
6819 free(commit_id_str);
6820 TAILQ_FOREACH(pe, &paths, entry)
6821 free((char *)pe->path);
6822 got_pathlist_free(&paths);
6823 return error;
6827 __dead static void
6828 usage_tag(void)
6830 fprintf(stderr,
6831 "usage: %s tag [-c commit] [-r repository] [-l] "
6832 "[-m message] name\n", getprogname());
6833 exit(1);
6836 #if 0
6837 static const struct got_error *
6838 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6840 const struct got_error *err = NULL;
6841 struct got_reflist_entry *re, *se, *new;
6842 struct got_object_id *re_id, *se_id;
6843 struct got_tag_object *re_tag, *se_tag;
6844 time_t re_time, se_time;
6846 STAILQ_FOREACH(re, tags, entry) {
6847 se = STAILQ_FIRST(sorted);
6848 if (se == NULL) {
6849 err = got_reflist_entry_dup(&new, re);
6850 if (err)
6851 return err;
6852 STAILQ_INSERT_HEAD(sorted, new, entry);
6853 continue;
6854 } else {
6855 err = got_ref_resolve(&re_id, repo, re->ref);
6856 if (err)
6857 break;
6858 err = got_object_open_as_tag(&re_tag, repo, re_id);
6859 free(re_id);
6860 if (err)
6861 break;
6862 re_time = got_object_tag_get_tagger_time(re_tag);
6863 got_object_tag_close(re_tag);
6866 while (se) {
6867 err = got_ref_resolve(&se_id, repo, re->ref);
6868 if (err)
6869 break;
6870 err = got_object_open_as_tag(&se_tag, repo, se_id);
6871 free(se_id);
6872 if (err)
6873 break;
6874 se_time = got_object_tag_get_tagger_time(se_tag);
6875 got_object_tag_close(se_tag);
6877 if (se_time > re_time) {
6878 err = got_reflist_entry_dup(&new, re);
6879 if (err)
6880 return err;
6881 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6882 break;
6884 se = STAILQ_NEXT(se, entry);
6885 continue;
6888 done:
6889 return err;
6891 #endif
6893 static const struct got_error *
6894 get_tag_refname(char **refname, const char *tag_name)
6896 const struct got_error *err;
6898 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6899 *refname = strdup(tag_name);
6900 if (*refname == NULL)
6901 return got_error_from_errno("strdup");
6902 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6903 err = got_error_from_errno("asprintf");
6904 *refname = NULL;
6905 return err;
6908 return NULL;
6911 static const struct got_error *
6912 list_tags(struct got_repository *repo, const char *tag_name)
6914 static const struct got_error *err = NULL;
6915 struct got_reflist_head refs;
6916 struct got_reflist_entry *re;
6917 char *wanted_refname = NULL;
6919 TAILQ_INIT(&refs);
6921 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6922 if (err)
6923 return err;
6925 if (tag_name) {
6926 struct got_reference *ref;
6927 err = get_tag_refname(&wanted_refname, tag_name);
6928 if (err)
6929 goto done;
6930 /* Wanted tag reference should exist. */
6931 err = got_ref_open(&ref, repo, wanted_refname, 0);
6932 if (err)
6933 goto done;
6934 got_ref_close(ref);
6937 TAILQ_FOREACH(re, &refs, entry) {
6938 const char *refname;
6939 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6940 char datebuf[26];
6941 const char *tagger;
6942 time_t tagger_time;
6943 struct got_object_id *id;
6944 struct got_tag_object *tag;
6945 struct got_commit_object *commit = NULL;
6947 refname = got_ref_get_name(re->ref);
6948 if (strncmp(refname, "refs/tags/", 10) != 0 ||
6949 (wanted_refname && strcmp(refname, wanted_refname) != 0))
6950 continue;
6951 refname += 10;
6952 refstr = got_ref_to_str(re->ref);
6953 if (refstr == NULL) {
6954 err = got_error_from_errno("got_ref_to_str");
6955 break;
6957 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6958 free(refstr);
6960 err = got_ref_resolve(&id, repo, re->ref);
6961 if (err)
6962 break;
6963 err = got_object_open_as_tag(&tag, repo, id);
6964 if (err) {
6965 if (err->code != GOT_ERR_OBJ_TYPE) {
6966 free(id);
6967 break;
6969 /* "lightweight" tag */
6970 err = got_object_open_as_commit(&commit, repo, id);
6971 if (err) {
6972 free(id);
6973 break;
6975 tagger = got_object_commit_get_committer(commit);
6976 tagger_time =
6977 got_object_commit_get_committer_time(commit);
6978 err = got_object_id_str(&id_str, id);
6979 free(id);
6980 if (err)
6981 break;
6982 } else {
6983 free(id);
6984 tagger = got_object_tag_get_tagger(tag);
6985 tagger_time = got_object_tag_get_tagger_time(tag);
6986 err = got_object_id_str(&id_str,
6987 got_object_tag_get_object_id(tag));
6988 if (err)
6989 break;
6991 printf("from: %s\n", tagger);
6992 datestr = get_datestr(&tagger_time, datebuf);
6993 if (datestr)
6994 printf("date: %s UTC\n", datestr);
6995 if (commit)
6996 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6997 else {
6998 switch (got_object_tag_get_object_type(tag)) {
6999 case GOT_OBJ_TYPE_BLOB:
7000 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7001 id_str);
7002 break;
7003 case GOT_OBJ_TYPE_TREE:
7004 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7005 id_str);
7006 break;
7007 case GOT_OBJ_TYPE_COMMIT:
7008 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7009 id_str);
7010 break;
7011 case GOT_OBJ_TYPE_TAG:
7012 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7013 id_str);
7014 break;
7015 default:
7016 break;
7019 free(id_str);
7020 if (commit) {
7021 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7022 if (err)
7023 break;
7024 got_object_commit_close(commit);
7025 } else {
7026 tagmsg0 = strdup(got_object_tag_get_message(tag));
7027 got_object_tag_close(tag);
7028 if (tagmsg0 == NULL) {
7029 err = got_error_from_errno("strdup");
7030 break;
7034 tagmsg = tagmsg0;
7035 do {
7036 line = strsep(&tagmsg, "\n");
7037 if (line)
7038 printf(" %s\n", line);
7039 } while (line);
7040 free(tagmsg0);
7042 done:
7043 got_ref_list_free(&refs);
7044 free(wanted_refname);
7045 return err;
7048 static const struct got_error *
7049 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7050 const char *tag_name, const char *repo_path)
7052 const struct got_error *err = NULL;
7053 char *template = NULL, *initial_content = NULL;
7054 char *editor = NULL;
7055 int initial_content_len;
7056 int fd = -1;
7058 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7059 err = got_error_from_errno("asprintf");
7060 goto done;
7063 initial_content_len = asprintf(&initial_content,
7064 "\n# tagging commit %s as %s\n",
7065 commit_id_str, tag_name);
7066 if (initial_content_len == -1) {
7067 err = got_error_from_errno("asprintf");
7068 goto done;
7071 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7072 if (err)
7073 goto done;
7075 if (write(fd, initial_content, initial_content_len) == -1) {
7076 err = got_error_from_errno2("write", *tagmsg_path);
7077 goto done;
7080 err = get_editor(&editor);
7081 if (err)
7082 goto done;
7083 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7084 initial_content_len, 1);
7085 done:
7086 free(initial_content);
7087 free(template);
7088 free(editor);
7090 if (fd != -1 && close(fd) == -1 && err == NULL)
7091 err = got_error_from_errno2("close", *tagmsg_path);
7093 /* Editor is done; we can now apply unveil(2) */
7094 if (err == NULL)
7095 err = apply_unveil(repo_path, 0, NULL);
7096 if (err) {
7097 free(*tagmsg);
7098 *tagmsg = NULL;
7100 return err;
7103 static const struct got_error *
7104 add_tag(struct got_repository *repo, const char *tagger,
7105 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
7107 const struct got_error *err = NULL;
7108 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7109 char *label = NULL, *commit_id_str = NULL;
7110 struct got_reference *ref = NULL;
7111 char *refname = NULL, *tagmsg = NULL;
7112 char *tagmsg_path = NULL, *tag_id_str = NULL;
7113 int preserve_tagmsg = 0;
7114 struct got_reflist_head refs;
7116 TAILQ_INIT(&refs);
7119 * Don't let the user create a tag name with a leading '-'.
7120 * While technically a valid reference name, this case is usually
7121 * an unintended typo.
7123 if (tag_name[0] == '-')
7124 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7126 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7127 if (err)
7128 goto done;
7130 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7131 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7132 if (err)
7133 goto done;
7135 err = got_object_id_str(&commit_id_str, commit_id);
7136 if (err)
7137 goto done;
7139 err = get_tag_refname(&refname, tag_name);
7140 if (err)
7141 goto done;
7142 if (strncmp("refs/tags/", tag_name, 10) == 0)
7143 tag_name += 10;
7145 err = got_ref_open(&ref, repo, refname, 0);
7146 if (err == NULL) {
7147 err = got_error(GOT_ERR_TAG_EXISTS);
7148 goto done;
7149 } else if (err->code != GOT_ERR_NOT_REF)
7150 goto done;
7152 if (tagmsg_arg == NULL) {
7153 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7154 tag_name, got_repo_get_path(repo));
7155 if (err) {
7156 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7157 tagmsg_path != NULL)
7158 preserve_tagmsg = 1;
7159 goto done;
7163 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7164 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7165 if (err) {
7166 if (tagmsg_path)
7167 preserve_tagmsg = 1;
7168 goto done;
7171 err = got_ref_alloc(&ref, refname, tag_id);
7172 if (err) {
7173 if (tagmsg_path)
7174 preserve_tagmsg = 1;
7175 goto done;
7178 err = got_ref_write(ref, repo);
7179 if (err) {
7180 if (tagmsg_path)
7181 preserve_tagmsg = 1;
7182 goto done;
7185 err = got_object_id_str(&tag_id_str, tag_id);
7186 if (err) {
7187 if (tagmsg_path)
7188 preserve_tagmsg = 1;
7189 goto done;
7191 printf("Created tag %s\n", tag_id_str);
7192 done:
7193 if (preserve_tagmsg) {
7194 fprintf(stderr, "%s: tag message preserved in %s\n",
7195 getprogname(), tagmsg_path);
7196 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7197 err = got_error_from_errno2("unlink", tagmsg_path);
7198 free(tag_id_str);
7199 if (ref)
7200 got_ref_close(ref);
7201 free(commit_id);
7202 free(commit_id_str);
7203 free(refname);
7204 free(tagmsg);
7205 free(tagmsg_path);
7206 got_ref_list_free(&refs);
7207 return err;
7210 static const struct got_error *
7211 cmd_tag(int argc, char *argv[])
7213 const struct got_error *error = NULL;
7214 struct got_repository *repo = NULL;
7215 struct got_worktree *worktree = NULL;
7216 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7217 char *gitconfig_path = NULL, *tagger = NULL;
7218 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7219 int ch, do_list = 0;
7220 int *pack_fds = NULL;
7222 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7223 switch (ch) {
7224 case 'c':
7225 commit_id_arg = optarg;
7226 break;
7227 case 'm':
7228 tagmsg = optarg;
7229 break;
7230 case 'r':
7231 repo_path = realpath(optarg, NULL);
7232 if (repo_path == NULL)
7233 return got_error_from_errno2("realpath",
7234 optarg);
7235 got_path_strip_trailing_slashes(repo_path);
7236 break;
7237 case 'l':
7238 do_list = 1;
7239 break;
7240 default:
7241 usage_tag();
7242 /* NOTREACHED */
7246 argc -= optind;
7247 argv += optind;
7249 if (do_list) {
7250 if (commit_id_arg != NULL)
7251 errx(1,
7252 "-c option can only be used when creating a tag");
7253 if (tagmsg)
7254 option_conflict('l', 'm');
7255 if (argc > 1)
7256 usage_tag();
7257 } else if (argc != 1)
7258 usage_tag();
7260 if (argc == 1)
7261 tag_name = argv[0];
7263 #ifndef PROFILE
7264 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7265 "sendfd unveil", NULL) == -1)
7266 err(1, "pledge");
7267 #endif
7268 cwd = getcwd(NULL, 0);
7269 if (cwd == NULL) {
7270 error = got_error_from_errno("getcwd");
7271 goto done;
7274 error = got_repo_pack_fds_open(&pack_fds);
7275 if (error != NULL)
7276 goto done;
7278 if (repo_path == NULL) {
7279 error = got_worktree_open(&worktree, cwd);
7280 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7281 goto done;
7282 else
7283 error = NULL;
7284 if (worktree) {
7285 repo_path =
7286 strdup(got_worktree_get_repo_path(worktree));
7287 if (repo_path == NULL)
7288 error = got_error_from_errno("strdup");
7289 if (error)
7290 goto done;
7291 } else {
7292 repo_path = strdup(cwd);
7293 if (repo_path == NULL) {
7294 error = got_error_from_errno("strdup");
7295 goto done;
7300 if (do_list) {
7301 if (worktree) {
7302 /* Release work tree lock. */
7303 got_worktree_close(worktree);
7304 worktree = NULL;
7306 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7307 if (error != NULL)
7308 goto done;
7310 #ifndef PROFILE
7311 /* Remove "cpath" promise. */
7312 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7313 NULL) == -1)
7314 err(1, "pledge");
7315 #endif
7316 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7317 if (error)
7318 goto done;
7319 error = list_tags(repo, tag_name);
7320 } else {
7321 error = get_gitconfig_path(&gitconfig_path);
7322 if (error)
7323 goto done;
7324 error = got_repo_open(&repo, repo_path, gitconfig_path,
7325 pack_fds);
7326 if (error != NULL)
7327 goto done;
7329 error = get_author(&tagger, repo, worktree);
7330 if (error)
7331 goto done;
7332 if (worktree) {
7333 /* Release work tree lock. */
7334 got_worktree_close(worktree);
7335 worktree = NULL;
7338 if (tagmsg) {
7339 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7340 if (error)
7341 goto done;
7344 if (commit_id_arg == NULL) {
7345 struct got_reference *head_ref;
7346 struct got_object_id *commit_id;
7347 error = got_ref_open(&head_ref, repo,
7348 worktree ? got_worktree_get_head_ref_name(worktree)
7349 : GOT_REF_HEAD, 0);
7350 if (error)
7351 goto done;
7352 error = got_ref_resolve(&commit_id, repo, head_ref);
7353 got_ref_close(head_ref);
7354 if (error)
7355 goto done;
7356 error = got_object_id_str(&commit_id_str, commit_id);
7357 free(commit_id);
7358 if (error)
7359 goto done;
7362 error = add_tag(repo, tagger, tag_name,
7363 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7365 done:
7366 if (repo) {
7367 const struct got_error *close_err = got_repo_close(repo);
7368 if (error == NULL)
7369 error = close_err;
7371 if (worktree)
7372 got_worktree_close(worktree);
7373 if (pack_fds) {
7374 const struct got_error *pack_err =
7375 got_repo_pack_fds_close(pack_fds);
7376 if (error == NULL)
7377 error = pack_err;
7379 free(cwd);
7380 free(repo_path);
7381 free(gitconfig_path);
7382 free(commit_id_str);
7383 free(tagger);
7384 return error;
7387 __dead static void
7388 usage_add(void)
7390 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7391 getprogname());
7392 exit(1);
7395 static const struct got_error *
7396 add_progress(void *arg, unsigned char status, const char *path)
7398 while (path[0] == '/')
7399 path++;
7400 printf("%c %s\n", status, path);
7401 return NULL;
7404 static const struct got_error *
7405 cmd_add(int argc, char *argv[])
7407 const struct got_error *error = NULL;
7408 struct got_repository *repo = NULL;
7409 struct got_worktree *worktree = NULL;
7410 char *cwd = NULL;
7411 struct got_pathlist_head paths;
7412 struct got_pathlist_entry *pe;
7413 int ch, can_recurse = 0, no_ignores = 0;
7414 int *pack_fds = NULL;
7416 TAILQ_INIT(&paths);
7418 while ((ch = getopt(argc, argv, "IR")) != -1) {
7419 switch (ch) {
7420 case 'I':
7421 no_ignores = 1;
7422 break;
7423 case 'R':
7424 can_recurse = 1;
7425 break;
7426 default:
7427 usage_add();
7428 /* NOTREACHED */
7432 argc -= optind;
7433 argv += optind;
7435 #ifndef PROFILE
7436 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7437 NULL) == -1)
7438 err(1, "pledge");
7439 #endif
7440 if (argc < 1)
7441 usage_add();
7443 cwd = getcwd(NULL, 0);
7444 if (cwd == NULL) {
7445 error = got_error_from_errno("getcwd");
7446 goto done;
7449 error = got_repo_pack_fds_open(&pack_fds);
7450 if (error != NULL)
7451 goto done;
7453 error = got_worktree_open(&worktree, cwd);
7454 if (error) {
7455 if (error->code == GOT_ERR_NOT_WORKTREE)
7456 error = wrap_not_worktree_error(error, "add", cwd);
7457 goto done;
7460 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7461 NULL, pack_fds);
7462 if (error != NULL)
7463 goto done;
7465 error = apply_unveil(got_repo_get_path(repo), 1,
7466 got_worktree_get_root_path(worktree));
7467 if (error)
7468 goto done;
7470 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7471 if (error)
7472 goto done;
7474 if (!can_recurse) {
7475 char *ondisk_path;
7476 struct stat sb;
7477 TAILQ_FOREACH(pe, &paths, entry) {
7478 if (asprintf(&ondisk_path, "%s/%s",
7479 got_worktree_get_root_path(worktree),
7480 pe->path) == -1) {
7481 error = got_error_from_errno("asprintf");
7482 goto done;
7484 if (lstat(ondisk_path, &sb) == -1) {
7485 if (errno == ENOENT) {
7486 free(ondisk_path);
7487 continue;
7489 error = got_error_from_errno2("lstat",
7490 ondisk_path);
7491 free(ondisk_path);
7492 goto done;
7494 free(ondisk_path);
7495 if (S_ISDIR(sb.st_mode)) {
7496 error = got_error_msg(GOT_ERR_BAD_PATH,
7497 "adding directories requires -R option");
7498 goto done;
7503 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7504 NULL, repo, no_ignores);
7505 done:
7506 if (repo) {
7507 const struct got_error *close_err = got_repo_close(repo);
7508 if (error == NULL)
7509 error = close_err;
7511 if (worktree)
7512 got_worktree_close(worktree);
7513 if (pack_fds) {
7514 const struct got_error *pack_err =
7515 got_repo_pack_fds_close(pack_fds);
7516 if (error == NULL)
7517 error = pack_err;
7519 TAILQ_FOREACH(pe, &paths, entry)
7520 free((char *)pe->path);
7521 got_pathlist_free(&paths);
7522 free(cwd);
7523 return error;
7526 __dead static void
7527 usage_remove(void)
7529 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7530 "path ...\n", getprogname());
7531 exit(1);
7534 static const struct got_error *
7535 print_remove_status(void *arg, unsigned char status,
7536 unsigned char staged_status, const char *path)
7538 while (path[0] == '/')
7539 path++;
7540 if (status == GOT_STATUS_NONEXISTENT)
7541 return NULL;
7542 if (status == staged_status && (status == GOT_STATUS_DELETE))
7543 status = GOT_STATUS_NO_CHANGE;
7544 printf("%c%c %s\n", status, staged_status, path);
7545 return NULL;
7548 static const struct got_error *
7549 cmd_remove(int argc, char *argv[])
7551 const struct got_error *error = NULL;
7552 struct got_worktree *worktree = NULL;
7553 struct got_repository *repo = NULL;
7554 const char *status_codes = NULL;
7555 char *cwd = NULL;
7556 struct got_pathlist_head paths;
7557 struct got_pathlist_entry *pe;
7558 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7559 int ignore_missing_paths = 0;
7560 int *pack_fds = NULL;
7562 TAILQ_INIT(&paths);
7564 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7565 switch (ch) {
7566 case 'f':
7567 delete_local_mods = 1;
7568 ignore_missing_paths = 1;
7569 break;
7570 case 'k':
7571 keep_on_disk = 1;
7572 break;
7573 case 'R':
7574 can_recurse = 1;
7575 break;
7576 case 's':
7577 for (i = 0; i < strlen(optarg); i++) {
7578 switch (optarg[i]) {
7579 case GOT_STATUS_MODIFY:
7580 delete_local_mods = 1;
7581 break;
7582 case GOT_STATUS_MISSING:
7583 ignore_missing_paths = 1;
7584 break;
7585 default:
7586 errx(1, "invalid status code '%c'",
7587 optarg[i]);
7590 status_codes = optarg;
7591 break;
7592 default:
7593 usage_remove();
7594 /* NOTREACHED */
7598 argc -= optind;
7599 argv += optind;
7601 #ifndef PROFILE
7602 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7603 NULL) == -1)
7604 err(1, "pledge");
7605 #endif
7606 if (argc < 1)
7607 usage_remove();
7609 cwd = getcwd(NULL, 0);
7610 if (cwd == NULL) {
7611 error = got_error_from_errno("getcwd");
7612 goto done;
7615 error = got_repo_pack_fds_open(&pack_fds);
7616 if (error != NULL)
7617 goto done;
7619 error = got_worktree_open(&worktree, cwd);
7620 if (error) {
7621 if (error->code == GOT_ERR_NOT_WORKTREE)
7622 error = wrap_not_worktree_error(error, "remove", cwd);
7623 goto done;
7626 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7627 NULL, pack_fds);
7628 if (error)
7629 goto done;
7631 error = apply_unveil(got_repo_get_path(repo), 1,
7632 got_worktree_get_root_path(worktree));
7633 if (error)
7634 goto done;
7636 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7637 if (error)
7638 goto done;
7640 if (!can_recurse) {
7641 char *ondisk_path;
7642 struct stat sb;
7643 TAILQ_FOREACH(pe, &paths, entry) {
7644 if (asprintf(&ondisk_path, "%s/%s",
7645 got_worktree_get_root_path(worktree),
7646 pe->path) == -1) {
7647 error = got_error_from_errno("asprintf");
7648 goto done;
7650 if (lstat(ondisk_path, &sb) == -1) {
7651 if (errno == ENOENT) {
7652 free(ondisk_path);
7653 continue;
7655 error = got_error_from_errno2("lstat",
7656 ondisk_path);
7657 free(ondisk_path);
7658 goto done;
7660 free(ondisk_path);
7661 if (S_ISDIR(sb.st_mode)) {
7662 error = got_error_msg(GOT_ERR_BAD_PATH,
7663 "removing directories requires -R option");
7664 goto done;
7669 error = got_worktree_schedule_delete(worktree, &paths,
7670 delete_local_mods, status_codes, print_remove_status, NULL,
7671 repo, keep_on_disk, ignore_missing_paths);
7672 done:
7673 if (repo) {
7674 const struct got_error *close_err = got_repo_close(repo);
7675 if (error == NULL)
7676 error = close_err;
7678 if (worktree)
7679 got_worktree_close(worktree);
7680 if (pack_fds) {
7681 const struct got_error *pack_err =
7682 got_repo_pack_fds_close(pack_fds);
7683 if (error == NULL)
7684 error = pack_err;
7686 TAILQ_FOREACH(pe, &paths, entry)
7687 free((char *)pe->path);
7688 got_pathlist_free(&paths);
7689 free(cwd);
7690 return error;
7693 __dead static void
7694 usage_patch(void)
7696 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7697 "[-R] [patchfile]\n", getprogname());
7698 exit(1);
7701 static const struct got_error *
7702 patch_from_stdin(int *patchfd)
7704 const struct got_error *err = NULL;
7705 ssize_t r;
7706 char *path, buf[BUFSIZ];
7707 sig_t sighup, sigint, sigquit;
7709 err = got_opentemp_named_fd(&path, patchfd,
7710 GOT_TMPDIR_STR "/got-patch");
7711 if (err)
7712 return err;
7713 unlink(path);
7714 free(path);
7716 sighup = signal(SIGHUP, SIG_DFL);
7717 sigint = signal(SIGINT, SIG_DFL);
7718 sigquit = signal(SIGQUIT, SIG_DFL);
7720 for (;;) {
7721 r = read(0, buf, sizeof(buf));
7722 if (r == -1) {
7723 err = got_error_from_errno("read");
7724 break;
7726 if (r == 0)
7727 break;
7728 if (write(*patchfd, buf, r) == -1) {
7729 err = got_error_from_errno("write");
7730 break;
7734 signal(SIGHUP, sighup);
7735 signal(SIGINT, sigint);
7736 signal(SIGQUIT, sigquit);
7738 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7739 err = got_error_from_errno("lseek");
7741 if (err != NULL) {
7742 close(*patchfd);
7743 *patchfd = -1;
7746 return err;
7749 static const struct got_error *
7750 patch_progress(void *arg, const char *old, const char *new,
7751 unsigned char status, const struct got_error *error, long old_from,
7752 long old_lines, long new_from, long new_lines, long offset,
7753 const struct got_error *hunk_err)
7755 const char *path = new == NULL ? old : new;
7757 while (*path == '/')
7758 path++;
7760 if (status != 0)
7761 printf("%c %s\n", status, path);
7763 if (error != NULL)
7764 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7766 if (offset != 0 || hunk_err != NULL) {
7767 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7768 old_lines, new_from, new_lines);
7769 if (hunk_err != NULL)
7770 printf("%s\n", hunk_err->msg);
7771 else
7772 printf("applied with offset %ld\n", offset);
7775 return NULL;
7778 static const struct got_error *
7779 cmd_patch(int argc, char *argv[])
7781 const struct got_error *error = NULL, *close_error = NULL;
7782 struct got_worktree *worktree = NULL;
7783 struct got_repository *repo = NULL;
7784 const char *errstr;
7785 char *cwd = NULL;
7786 int ch, nop = 0, strip = -1, reverse = 0;
7787 int patchfd;
7788 int *pack_fds = NULL;
7790 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7791 switch (ch) {
7792 case 'n':
7793 nop = 1;
7794 break;
7795 case 'p':
7796 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7797 if (errstr != NULL)
7798 errx(1, "pathname strip count is %s: %s",
7799 errstr, optarg);
7800 break;
7801 case 'R':
7802 reverse = 1;
7803 break;
7804 default:
7805 usage_patch();
7806 /* NOTREACHED */
7810 argc -= optind;
7811 argv += optind;
7813 if (argc == 0) {
7814 error = patch_from_stdin(&patchfd);
7815 if (error)
7816 return error;
7817 } else if (argc == 1) {
7818 patchfd = open(argv[0], O_RDONLY);
7819 if (patchfd == -1) {
7820 error = got_error_from_errno2("open", argv[0]);
7821 return error;
7823 } else
7824 usage_patch();
7826 if ((cwd = getcwd(NULL, 0)) == NULL) {
7827 error = got_error_from_errno("getcwd");
7828 goto done;
7831 error = got_repo_pack_fds_open(&pack_fds);
7832 if (error != NULL)
7833 goto done;
7835 error = got_worktree_open(&worktree, cwd);
7836 if (error != NULL)
7837 goto done;
7839 const char *repo_path = got_worktree_get_repo_path(worktree);
7840 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7841 if (error != NULL)
7842 goto done;
7844 error = apply_unveil(got_repo_get_path(repo), 0,
7845 got_worktree_get_root_path(worktree));
7846 if (error != NULL)
7847 goto done;
7849 #ifndef PROFILE
7850 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7851 NULL) == -1)
7852 err(1, "pledge");
7853 #endif
7855 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7856 &patch_progress, NULL, check_cancelled, NULL);
7858 done:
7859 if (repo) {
7860 close_error = got_repo_close(repo);
7861 if (error == NULL)
7862 error = close_error;
7864 if (worktree != NULL) {
7865 close_error = got_worktree_close(worktree);
7866 if (error == NULL)
7867 error = close_error;
7869 if (pack_fds) {
7870 const struct got_error *pack_err =
7871 got_repo_pack_fds_close(pack_fds);
7872 if (error == NULL)
7873 error = pack_err;
7875 free(cwd);
7876 return error;
7879 __dead static void
7880 usage_revert(void)
7882 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7883 "path ...\n", getprogname());
7884 exit(1);
7887 static const struct got_error *
7888 revert_progress(void *arg, unsigned char status, const char *path)
7890 if (status == GOT_STATUS_UNVERSIONED)
7891 return NULL;
7893 while (path[0] == '/')
7894 path++;
7895 printf("%c %s\n", status, path);
7896 return NULL;
7899 struct choose_patch_arg {
7900 FILE *patch_script_file;
7901 const char *action;
7904 static const struct got_error *
7905 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7906 int nchanges, const char *action)
7908 const struct got_error *err;
7909 char *line = NULL;
7910 size_t linesize = 0;
7911 ssize_t linelen;
7913 switch (status) {
7914 case GOT_STATUS_ADD:
7915 printf("A %s\n%s this addition? [y/n] ", path, action);
7916 break;
7917 case GOT_STATUS_DELETE:
7918 printf("D %s\n%s this deletion? [y/n] ", path, action);
7919 break;
7920 case GOT_STATUS_MODIFY:
7921 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7922 return got_error_from_errno("fseek");
7923 printf(GOT_COMMIT_SEP_STR);
7924 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7925 printf("%s", line);
7926 if (linelen == -1 && ferror(patch_file)) {
7927 err = got_error_from_errno("getline");
7928 free(line);
7929 return err;
7931 free(line);
7932 printf(GOT_COMMIT_SEP_STR);
7933 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7934 path, n, nchanges, action);
7935 break;
7936 default:
7937 return got_error_path(path, GOT_ERR_FILE_STATUS);
7940 return NULL;
7943 static const struct got_error *
7944 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7945 FILE *patch_file, int n, int nchanges)
7947 const struct got_error *err = NULL;
7948 char *line = NULL;
7949 size_t linesize = 0;
7950 ssize_t linelen;
7951 int resp = ' ';
7952 struct choose_patch_arg *a = arg;
7954 *choice = GOT_PATCH_CHOICE_NONE;
7956 if (a->patch_script_file) {
7957 char *nl;
7958 err = show_change(status, path, patch_file, n, nchanges,
7959 a->action);
7960 if (err)
7961 return err;
7962 linelen = getline(&line, &linesize, a->patch_script_file);
7963 if (linelen == -1) {
7964 if (ferror(a->patch_script_file))
7965 return got_error_from_errno("getline");
7966 return NULL;
7968 nl = strchr(line, '\n');
7969 if (nl)
7970 *nl = '\0';
7971 if (strcmp(line, "y") == 0) {
7972 *choice = GOT_PATCH_CHOICE_YES;
7973 printf("y\n");
7974 } else if (strcmp(line, "n") == 0) {
7975 *choice = GOT_PATCH_CHOICE_NO;
7976 printf("n\n");
7977 } else if (strcmp(line, "q") == 0 &&
7978 status == GOT_STATUS_MODIFY) {
7979 *choice = GOT_PATCH_CHOICE_QUIT;
7980 printf("q\n");
7981 } else
7982 printf("invalid response '%s'\n", line);
7983 free(line);
7984 return NULL;
7987 while (resp != 'y' && resp != 'n' && resp != 'q') {
7988 err = show_change(status, path, patch_file, n, nchanges,
7989 a->action);
7990 if (err)
7991 return err;
7992 resp = getchar();
7993 if (resp == '\n')
7994 resp = getchar();
7995 if (status == GOT_STATUS_MODIFY) {
7996 if (resp != 'y' && resp != 'n' && resp != 'q') {
7997 printf("invalid response '%c'\n", resp);
7998 resp = ' ';
8000 } else if (resp != 'y' && resp != 'n') {
8001 printf("invalid response '%c'\n", resp);
8002 resp = ' ';
8006 if (resp == 'y')
8007 *choice = GOT_PATCH_CHOICE_YES;
8008 else if (resp == 'n')
8009 *choice = GOT_PATCH_CHOICE_NO;
8010 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8011 *choice = GOT_PATCH_CHOICE_QUIT;
8013 return NULL;
8016 static const struct got_error *
8017 cmd_revert(int argc, char *argv[])
8019 const struct got_error *error = NULL;
8020 struct got_worktree *worktree = NULL;
8021 struct got_repository *repo = NULL;
8022 char *cwd = NULL, *path = NULL;
8023 struct got_pathlist_head paths;
8024 struct got_pathlist_entry *pe;
8025 int ch, can_recurse = 0, pflag = 0;
8026 FILE *patch_script_file = NULL;
8027 const char *patch_script_path = NULL;
8028 struct choose_patch_arg cpa;
8029 int *pack_fds = NULL;
8031 TAILQ_INIT(&paths);
8033 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8034 switch (ch) {
8035 case 'p':
8036 pflag = 1;
8037 break;
8038 case 'F':
8039 patch_script_path = optarg;
8040 break;
8041 case 'R':
8042 can_recurse = 1;
8043 break;
8044 default:
8045 usage_revert();
8046 /* NOTREACHED */
8050 argc -= optind;
8051 argv += optind;
8053 #ifndef PROFILE
8054 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8055 "unveil", NULL) == -1)
8056 err(1, "pledge");
8057 #endif
8058 if (argc < 1)
8059 usage_revert();
8060 if (patch_script_path && !pflag)
8061 errx(1, "-F option can only be used together with -p option");
8063 cwd = getcwd(NULL, 0);
8064 if (cwd == NULL) {
8065 error = got_error_from_errno("getcwd");
8066 goto done;
8069 error = got_repo_pack_fds_open(&pack_fds);
8070 if (error != NULL)
8071 goto done;
8073 error = got_worktree_open(&worktree, cwd);
8074 if (error) {
8075 if (error->code == GOT_ERR_NOT_WORKTREE)
8076 error = wrap_not_worktree_error(error, "revert", cwd);
8077 goto done;
8080 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8081 NULL, pack_fds);
8082 if (error != NULL)
8083 goto done;
8085 if (patch_script_path) {
8086 patch_script_file = fopen(patch_script_path, "re");
8087 if (patch_script_file == NULL) {
8088 error = got_error_from_errno2("fopen",
8089 patch_script_path);
8090 goto done;
8093 error = apply_unveil(got_repo_get_path(repo), 1,
8094 got_worktree_get_root_path(worktree));
8095 if (error)
8096 goto done;
8098 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8099 if (error)
8100 goto done;
8102 if (!can_recurse) {
8103 char *ondisk_path;
8104 struct stat sb;
8105 TAILQ_FOREACH(pe, &paths, entry) {
8106 if (asprintf(&ondisk_path, "%s/%s",
8107 got_worktree_get_root_path(worktree),
8108 pe->path) == -1) {
8109 error = got_error_from_errno("asprintf");
8110 goto done;
8112 if (lstat(ondisk_path, &sb) == -1) {
8113 if (errno == ENOENT) {
8114 free(ondisk_path);
8115 continue;
8117 error = got_error_from_errno2("lstat",
8118 ondisk_path);
8119 free(ondisk_path);
8120 goto done;
8122 free(ondisk_path);
8123 if (S_ISDIR(sb.st_mode)) {
8124 error = got_error_msg(GOT_ERR_BAD_PATH,
8125 "reverting directories requires -R option");
8126 goto done;
8131 cpa.patch_script_file = patch_script_file;
8132 cpa.action = "revert";
8133 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8134 pflag ? choose_patch : NULL, &cpa, repo);
8135 done:
8136 if (patch_script_file && fclose(patch_script_file) == EOF &&
8137 error == NULL)
8138 error = got_error_from_errno2("fclose", patch_script_path);
8139 if (repo) {
8140 const struct got_error *close_err = got_repo_close(repo);
8141 if (error == NULL)
8142 error = close_err;
8144 if (worktree)
8145 got_worktree_close(worktree);
8146 if (pack_fds) {
8147 const struct got_error *pack_err =
8148 got_repo_pack_fds_close(pack_fds);
8149 if (error == NULL)
8150 error = pack_err;
8152 free(path);
8153 free(cwd);
8154 return error;
8157 __dead static void
8158 usage_commit(void)
8160 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8161 "[path ...]\n", getprogname());
8162 exit(1);
8165 struct collect_commit_logmsg_arg {
8166 const char *cmdline_log;
8167 const char *prepared_log;
8168 int non_interactive;
8169 const char *editor;
8170 const char *worktree_path;
8171 const char *branch_name;
8172 const char *repo_path;
8173 char *logmsg_path;
8177 static const struct got_error *
8178 read_prepared_logmsg(char **logmsg, const char *path)
8180 const struct got_error *err = NULL;
8181 FILE *f = NULL;
8182 struct stat sb;
8183 size_t r;
8185 *logmsg = NULL;
8186 memset(&sb, 0, sizeof(sb));
8188 f = fopen(path, "re");
8189 if (f == NULL)
8190 return got_error_from_errno2("fopen", path);
8192 if (fstat(fileno(f), &sb) == -1) {
8193 err = got_error_from_errno2("fstat", path);
8194 goto done;
8196 if (sb.st_size == 0) {
8197 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8198 goto done;
8201 *logmsg = malloc(sb.st_size + 1);
8202 if (*logmsg == NULL) {
8203 err = got_error_from_errno("malloc");
8204 goto done;
8207 r = fread(*logmsg, 1, sb.st_size, f);
8208 if (r != sb.st_size) {
8209 if (ferror(f))
8210 err = got_error_from_errno2("fread", path);
8211 else
8212 err = got_error(GOT_ERR_IO);
8213 goto done;
8215 (*logmsg)[sb.st_size] = '\0';
8216 done:
8217 if (fclose(f) == EOF && err == NULL)
8218 err = got_error_from_errno2("fclose", path);
8219 if (err) {
8220 free(*logmsg);
8221 *logmsg = NULL;
8223 return err;
8227 static const struct got_error *
8228 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8229 void *arg)
8231 char *initial_content = NULL;
8232 struct got_pathlist_entry *pe;
8233 const struct got_error *err = NULL;
8234 char *template = NULL;
8235 struct collect_commit_logmsg_arg *a = arg;
8236 int initial_content_len;
8237 int fd = -1;
8238 size_t len;
8240 /* if a message was specified on the command line, just use it */
8241 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8242 len = strlen(a->cmdline_log) + 1;
8243 *logmsg = malloc(len + 1);
8244 if (*logmsg == NULL)
8245 return got_error_from_errno("malloc");
8246 strlcpy(*logmsg, a->cmdline_log, len);
8247 return NULL;
8248 } else if (a->prepared_log != NULL && a->non_interactive)
8249 return read_prepared_logmsg(logmsg, a->prepared_log);
8251 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8252 return got_error_from_errno("asprintf");
8254 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8255 if (err)
8256 goto done;
8258 if (a->prepared_log) {
8259 char *msg;
8260 err = read_prepared_logmsg(&msg, a->prepared_log);
8261 if (err)
8262 goto done;
8263 if (write(fd, msg, strlen(msg)) == -1) {
8264 err = got_error_from_errno2("write", a->logmsg_path);
8265 free(msg);
8266 goto done;
8268 free(msg);
8271 initial_content_len = asprintf(&initial_content,
8272 "\n# changes to be committed on branch %s:\n",
8273 a->branch_name);
8274 if (initial_content_len == -1) {
8275 err = got_error_from_errno("asprintf");
8276 goto done;
8279 if (write(fd, initial_content, initial_content_len) == -1) {
8280 err = got_error_from_errno2("write", a->logmsg_path);
8281 goto done;
8284 TAILQ_FOREACH(pe, commitable_paths, entry) {
8285 struct got_commitable *ct = pe->data;
8286 dprintf(fd, "# %c %s\n",
8287 got_commitable_get_status(ct),
8288 got_commitable_get_path(ct));
8291 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8292 initial_content_len, a->prepared_log ? 0 : 1);
8293 done:
8294 free(initial_content);
8295 free(template);
8297 if (fd != -1 && close(fd) == -1 && err == NULL)
8298 err = got_error_from_errno2("close", a->logmsg_path);
8300 /* Editor is done; we can now apply unveil(2) */
8301 if (err == NULL)
8302 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8303 if (err) {
8304 free(*logmsg);
8305 *logmsg = NULL;
8307 return err;
8310 static const struct got_error *
8311 cmd_commit(int argc, char *argv[])
8313 const struct got_error *error = NULL;
8314 struct got_worktree *worktree = NULL;
8315 struct got_repository *repo = NULL;
8316 char *cwd = NULL, *id_str = NULL;
8317 struct got_object_id *id = NULL;
8318 const char *logmsg = NULL;
8319 char *prepared_logmsg = NULL;
8320 struct collect_commit_logmsg_arg cl_arg;
8321 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8322 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8323 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8324 struct got_pathlist_head paths;
8325 int *pack_fds = NULL;
8327 TAILQ_INIT(&paths);
8328 cl_arg.logmsg_path = NULL;
8330 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8331 switch (ch) {
8332 case 'F':
8333 if (logmsg != NULL)
8334 option_conflict('F', 'm');
8335 prepared_logmsg = realpath(optarg, NULL);
8336 if (prepared_logmsg == NULL)
8337 return got_error_from_errno2("realpath",
8338 optarg);
8339 break;
8340 case 'm':
8341 if (prepared_logmsg)
8342 option_conflict('m', 'F');
8343 logmsg = optarg;
8344 break;
8345 case 'N':
8346 non_interactive = 1;
8347 break;
8348 case 'S':
8349 allow_bad_symlinks = 1;
8350 break;
8351 default:
8352 usage_commit();
8353 /* NOTREACHED */
8357 argc -= optind;
8358 argv += optind;
8360 #ifndef PROFILE
8361 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8362 "unveil", NULL) == -1)
8363 err(1, "pledge");
8364 #endif
8365 cwd = getcwd(NULL, 0);
8366 if (cwd == NULL) {
8367 error = got_error_from_errno("getcwd");
8368 goto done;
8371 error = got_repo_pack_fds_open(&pack_fds);
8372 if (error != NULL)
8373 goto done;
8375 error = got_worktree_open(&worktree, cwd);
8376 if (error) {
8377 if (error->code == GOT_ERR_NOT_WORKTREE)
8378 error = wrap_not_worktree_error(error, "commit", cwd);
8379 goto done;
8382 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8383 if (error)
8384 goto done;
8385 if (rebase_in_progress) {
8386 error = got_error(GOT_ERR_REBASING);
8387 goto done;
8390 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8391 worktree);
8392 if (error)
8393 goto done;
8395 error = get_gitconfig_path(&gitconfig_path);
8396 if (error)
8397 goto done;
8398 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8399 gitconfig_path, pack_fds);
8400 if (error != NULL)
8401 goto done;
8403 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8404 if (error)
8405 goto done;
8406 if (merge_in_progress) {
8407 error = got_error(GOT_ERR_MERGE_BUSY);
8408 goto done;
8411 error = get_author(&author, repo, worktree);
8412 if (error)
8413 return error;
8416 * unveil(2) traverses exec(2); if an editor is used we have
8417 * to apply unveil after the log message has been written.
8419 if (logmsg == NULL || strlen(logmsg) == 0)
8420 error = get_editor(&editor);
8421 else
8422 error = apply_unveil(got_repo_get_path(repo), 0,
8423 got_worktree_get_root_path(worktree));
8424 if (error)
8425 goto done;
8427 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8428 if (error)
8429 goto done;
8431 cl_arg.editor = editor;
8432 cl_arg.cmdline_log = logmsg;
8433 cl_arg.prepared_log = prepared_logmsg;
8434 cl_arg.non_interactive = non_interactive;
8435 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8436 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8437 if (!histedit_in_progress) {
8438 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8439 error = got_error(GOT_ERR_COMMIT_BRANCH);
8440 goto done;
8442 cl_arg.branch_name += 11;
8444 cl_arg.repo_path = got_repo_get_path(repo);
8445 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8446 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8447 print_status, NULL, repo);
8448 if (error) {
8449 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8450 cl_arg.logmsg_path != NULL)
8451 preserve_logmsg = 1;
8452 goto done;
8455 error = got_object_id_str(&id_str, id);
8456 if (error)
8457 goto done;
8458 printf("Created commit %s\n", id_str);
8459 done:
8460 if (preserve_logmsg) {
8461 fprintf(stderr, "%s: log message preserved in %s\n",
8462 getprogname(), cl_arg.logmsg_path);
8463 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8464 error == NULL)
8465 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8466 free(cl_arg.logmsg_path);
8467 if (repo) {
8468 const struct got_error *close_err = got_repo_close(repo);
8469 if (error == NULL)
8470 error = close_err;
8472 if (worktree)
8473 got_worktree_close(worktree);
8474 if (pack_fds) {
8475 const struct got_error *pack_err =
8476 got_repo_pack_fds_close(pack_fds);
8477 if (error == NULL)
8478 error = pack_err;
8480 free(cwd);
8481 free(id_str);
8482 free(gitconfig_path);
8483 free(editor);
8484 free(author);
8485 free(prepared_logmsg);
8486 return error;
8489 __dead static void
8490 usage_send(void)
8492 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8493 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8494 "[remote-repository]\n", getprogname());
8495 exit(1);
8498 static void
8499 print_load_info(int print_colored, int print_found, int print_trees,
8500 int ncolored, int nfound, int ntrees)
8502 if (print_colored) {
8503 printf("%d commit%s colored", ncolored,
8504 ncolored == 1 ? "" : "s");
8506 if (print_found) {
8507 printf("%s%d object%s found",
8508 ncolored > 0 ? "; " : "",
8509 nfound, nfound == 1 ? "" : "s");
8511 if (print_trees) {
8512 printf("; %d tree%s scanned", ntrees,
8513 ntrees == 1 ? "" : "s");
8517 struct got_send_progress_arg {
8518 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8519 int verbosity;
8520 int last_ncolored;
8521 int last_nfound;
8522 int last_ntrees;
8523 int loading_done;
8524 int last_ncommits;
8525 int last_nobj_total;
8526 int last_p_deltify;
8527 int last_p_written;
8528 int last_p_sent;
8529 int printed_something;
8530 int sent_something;
8531 struct got_pathlist_head *delete_branches;
8534 static const struct got_error *
8535 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8536 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8537 int nobj_written, off_t bytes_sent, const char *refname, int success)
8539 struct got_send_progress_arg *a = arg;
8540 char scaled_packsize[FMT_SCALED_STRSIZE];
8541 char scaled_sent[FMT_SCALED_STRSIZE];
8542 int p_deltify = 0, p_written = 0, p_sent = 0;
8543 int print_colored = 0, print_found = 0, print_trees = 0;
8544 int print_searching = 0, print_total = 0;
8545 int print_deltify = 0, print_written = 0, print_sent = 0;
8547 if (a->verbosity < 0)
8548 return NULL;
8550 if (refname) {
8551 const char *status = success ? "accepted" : "rejected";
8553 if (success) {
8554 struct got_pathlist_entry *pe;
8555 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8556 const char *branchname = pe->path;
8557 if (got_path_cmp(branchname, refname,
8558 strlen(branchname), strlen(refname)) == 0) {
8559 status = "deleted";
8560 a->sent_something = 1;
8561 break;
8566 if (a->printed_something)
8567 putchar('\n');
8568 printf("Server has %s %s", status, refname);
8569 a->printed_something = 1;
8570 return NULL;
8573 if (a->last_ncolored != ncolored) {
8574 print_colored = 1;
8575 a->last_ncolored = ncolored;
8578 if (a->last_nfound != nfound) {
8579 print_colored = 1;
8580 print_found = 1;
8581 a->last_nfound = nfound;
8584 if (a->last_ntrees != ntrees) {
8585 print_colored = 1;
8586 print_found = 1;
8587 print_trees = 1;
8588 a->last_ntrees = ntrees;
8591 if ((print_colored || print_found || print_trees) &&
8592 !a->loading_done) {
8593 printf("\r");
8594 print_load_info(print_colored, print_found, print_trees,
8595 ncolored, nfound, ntrees);
8596 a->printed_something = 1;
8597 fflush(stdout);
8598 return NULL;
8599 } else if (!a->loading_done) {
8600 printf("\r");
8601 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8602 printf("\n");
8603 a->loading_done = 1;
8606 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8607 return got_error_from_errno("fmt_scaled");
8608 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8609 return got_error_from_errno("fmt_scaled");
8611 if (a->last_ncommits != ncommits) {
8612 print_searching = 1;
8613 a->last_ncommits = ncommits;
8616 if (a->last_nobj_total != nobj_total) {
8617 print_searching = 1;
8618 print_total = 1;
8619 a->last_nobj_total = nobj_total;
8622 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8623 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8624 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8625 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8626 return got_error(GOT_ERR_NO_SPACE);
8629 if (nobj_deltify > 0 || nobj_written > 0) {
8630 if (nobj_deltify > 0) {
8631 p_deltify = (nobj_deltify * 100) / nobj_total;
8632 if (p_deltify != a->last_p_deltify) {
8633 a->last_p_deltify = p_deltify;
8634 print_searching = 1;
8635 print_total = 1;
8636 print_deltify = 1;
8639 if (nobj_written > 0) {
8640 p_written = (nobj_written * 100) / nobj_total;
8641 if (p_written != a->last_p_written) {
8642 a->last_p_written = p_written;
8643 print_searching = 1;
8644 print_total = 1;
8645 print_deltify = 1;
8646 print_written = 1;
8651 if (bytes_sent > 0) {
8652 p_sent = (bytes_sent * 100) / packfile_size;
8653 if (p_sent != a->last_p_sent) {
8654 a->last_p_sent = p_sent;
8655 print_searching = 1;
8656 print_total = 1;
8657 print_deltify = 1;
8658 print_written = 1;
8659 print_sent = 1;
8661 a->sent_something = 1;
8664 if (print_searching || print_total || print_deltify || print_written ||
8665 print_sent)
8666 printf("\r");
8667 if (print_searching)
8668 printf("packing %d reference%s", ncommits,
8669 ncommits == 1 ? "" : "s");
8670 if (print_total)
8671 printf("; %d object%s", nobj_total,
8672 nobj_total == 1 ? "" : "s");
8673 if (print_deltify)
8674 printf("; deltify: %d%%", p_deltify);
8675 if (print_sent)
8676 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8677 scaled_packsize, p_sent);
8678 else if (print_written)
8679 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8680 scaled_packsize, p_written);
8681 if (print_searching || print_total || print_deltify ||
8682 print_written || print_sent) {
8683 a->printed_something = 1;
8684 fflush(stdout);
8686 return NULL;
8689 static const struct got_error *
8690 cmd_send(int argc, char *argv[])
8692 const struct got_error *error = NULL;
8693 char *cwd = NULL, *repo_path = NULL;
8694 const char *remote_name;
8695 char *proto = NULL, *host = NULL, *port = NULL;
8696 char *repo_name = NULL, *server_path = NULL;
8697 const struct got_remote_repo *remotes, *remote = NULL;
8698 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8699 struct got_repository *repo = NULL;
8700 struct got_worktree *worktree = NULL;
8701 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8702 struct got_pathlist_head branches;
8703 struct got_pathlist_head tags;
8704 struct got_reflist_head all_branches;
8705 struct got_reflist_head all_tags;
8706 struct got_pathlist_head delete_args;
8707 struct got_pathlist_head delete_branches;
8708 struct got_reflist_entry *re;
8709 struct got_pathlist_entry *pe;
8710 int i, ch, sendfd = -1, sendstatus;
8711 pid_t sendpid = -1;
8712 struct got_send_progress_arg spa;
8713 int verbosity = 0, overwrite_refs = 0;
8714 int send_all_branches = 0, send_all_tags = 0;
8715 struct got_reference *ref = NULL;
8716 int *pack_fds = NULL;
8718 TAILQ_INIT(&branches);
8719 TAILQ_INIT(&tags);
8720 TAILQ_INIT(&all_branches);
8721 TAILQ_INIT(&all_tags);
8722 TAILQ_INIT(&delete_args);
8723 TAILQ_INIT(&delete_branches);
8725 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8726 switch (ch) {
8727 case 'a':
8728 send_all_branches = 1;
8729 break;
8730 case 'b':
8731 error = got_pathlist_append(&branches, optarg, NULL);
8732 if (error)
8733 return error;
8734 nbranches++;
8735 break;
8736 case 'd':
8737 error = got_pathlist_append(&delete_args, optarg, NULL);
8738 if (error)
8739 return error;
8740 break;
8741 case 'f':
8742 overwrite_refs = 1;
8743 break;
8744 case 'r':
8745 repo_path = realpath(optarg, NULL);
8746 if (repo_path == NULL)
8747 return got_error_from_errno2("realpath",
8748 optarg);
8749 got_path_strip_trailing_slashes(repo_path);
8750 break;
8751 case 't':
8752 error = got_pathlist_append(&tags, optarg, NULL);
8753 if (error)
8754 return error;
8755 ntags++;
8756 break;
8757 case 'T':
8758 send_all_tags = 1;
8759 break;
8760 case 'v':
8761 if (verbosity < 0)
8762 verbosity = 0;
8763 else if (verbosity < 3)
8764 verbosity++;
8765 break;
8766 case 'q':
8767 verbosity = -1;
8768 break;
8769 default:
8770 usage_send();
8771 /* NOTREACHED */
8774 argc -= optind;
8775 argv += optind;
8777 if (send_all_branches && !TAILQ_EMPTY(&branches))
8778 option_conflict('a', 'b');
8779 if (send_all_tags && !TAILQ_EMPTY(&tags))
8780 option_conflict('T', 't');
8783 if (argc == 0)
8784 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8785 else if (argc == 1)
8786 remote_name = argv[0];
8787 else
8788 usage_send();
8790 cwd = getcwd(NULL, 0);
8791 if (cwd == NULL) {
8792 error = got_error_from_errno("getcwd");
8793 goto done;
8796 error = got_repo_pack_fds_open(&pack_fds);
8797 if (error != NULL)
8798 goto done;
8800 if (repo_path == NULL) {
8801 error = got_worktree_open(&worktree, cwd);
8802 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8803 goto done;
8804 else
8805 error = NULL;
8806 if (worktree) {
8807 repo_path =
8808 strdup(got_worktree_get_repo_path(worktree));
8809 if (repo_path == NULL)
8810 error = got_error_from_errno("strdup");
8811 if (error)
8812 goto done;
8813 } else {
8814 repo_path = strdup(cwd);
8815 if (repo_path == NULL) {
8816 error = got_error_from_errno("strdup");
8817 goto done;
8822 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8823 if (error)
8824 goto done;
8826 if (worktree) {
8827 worktree_conf = got_worktree_get_gotconfig(worktree);
8828 if (worktree_conf) {
8829 got_gotconfig_get_remotes(&nremotes, &remotes,
8830 worktree_conf);
8831 for (i = 0; i < nremotes; i++) {
8832 if (strcmp(remotes[i].name, remote_name) == 0) {
8833 remote = &remotes[i];
8834 break;
8839 if (remote == NULL) {
8840 repo_conf = got_repo_get_gotconfig(repo);
8841 if (repo_conf) {
8842 got_gotconfig_get_remotes(&nremotes, &remotes,
8843 repo_conf);
8844 for (i = 0; i < nremotes; i++) {
8845 if (strcmp(remotes[i].name, remote_name) == 0) {
8846 remote = &remotes[i];
8847 break;
8852 if (remote == NULL) {
8853 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8854 for (i = 0; i < nremotes; i++) {
8855 if (strcmp(remotes[i].name, remote_name) == 0) {
8856 remote = &remotes[i];
8857 break;
8861 if (remote == NULL) {
8862 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8863 goto done;
8866 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8867 &repo_name, remote->send_url);
8868 if (error)
8869 goto done;
8871 if (strcmp(proto, "git") == 0) {
8872 #ifndef PROFILE
8873 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8874 "sendfd dns inet unveil", NULL) == -1)
8875 err(1, "pledge");
8876 #endif
8877 } else if (strcmp(proto, "git+ssh") == 0 ||
8878 strcmp(proto, "ssh") == 0) {
8879 #ifndef PROFILE
8880 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8881 "sendfd unveil", NULL) == -1)
8882 err(1, "pledge");
8883 #endif
8884 } else if (strcmp(proto, "http") == 0 ||
8885 strcmp(proto, "git+http") == 0) {
8886 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8887 goto done;
8888 } else {
8889 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8890 goto done;
8893 error = got_dial_apply_unveil(proto);
8894 if (error)
8895 goto done;
8897 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8898 if (error)
8899 goto done;
8901 if (send_all_branches) {
8902 error = got_ref_list(&all_branches, repo, "refs/heads",
8903 got_ref_cmp_by_name, NULL);
8904 if (error)
8905 goto done;
8906 TAILQ_FOREACH(re, &all_branches, entry) {
8907 const char *branchname = got_ref_get_name(re->ref);
8908 error = got_pathlist_append(&branches,
8909 branchname, NULL);
8910 if (error)
8911 goto done;
8912 nbranches++;
8914 } else if (nbranches == 0) {
8915 for (i = 0; i < remote->nsend_branches; i++) {
8916 got_pathlist_append(&branches,
8917 remote->send_branches[i], NULL);
8921 if (send_all_tags) {
8922 error = got_ref_list(&all_tags, repo, "refs/tags",
8923 got_ref_cmp_by_name, NULL);
8924 if (error)
8925 goto done;
8926 TAILQ_FOREACH(re, &all_tags, entry) {
8927 const char *tagname = got_ref_get_name(re->ref);
8928 error = got_pathlist_append(&tags,
8929 tagname, NULL);
8930 if (error)
8931 goto done;
8932 ntags++;
8937 * To prevent accidents only branches in refs/heads/ can be deleted
8938 * with 'got send -d'.
8939 * Deleting anything else requires local repository access or Git.
8941 TAILQ_FOREACH(pe, &delete_args, entry) {
8942 const char *branchname = pe->path;
8943 char *s;
8944 struct got_pathlist_entry *new;
8945 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8946 s = strdup(branchname);
8947 if (s == NULL) {
8948 error = got_error_from_errno("strdup");
8949 goto done;
8951 } else {
8952 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8953 error = got_error_from_errno("asprintf");
8954 goto done;
8957 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8958 if (error || new == NULL /* duplicate */)
8959 free(s);
8960 if (error)
8961 goto done;
8962 ndelete_branches++;
8965 if (nbranches == 0 && ndelete_branches == 0) {
8966 struct got_reference *head_ref;
8967 if (worktree)
8968 error = got_ref_open(&head_ref, repo,
8969 got_worktree_get_head_ref_name(worktree), 0);
8970 else
8971 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8972 if (error)
8973 goto done;
8974 if (got_ref_is_symbolic(head_ref)) {
8975 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8976 got_ref_close(head_ref);
8977 if (error)
8978 goto done;
8979 } else
8980 ref = head_ref;
8981 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8982 NULL);
8983 if (error)
8984 goto done;
8985 nbranches++;
8988 if (verbosity >= 0)
8989 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8990 port ? ":" : "", port ? port : "");
8992 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8993 server_path, verbosity);
8994 if (error)
8995 goto done;
8997 memset(&spa, 0, sizeof(spa));
8998 spa.last_scaled_packsize[0] = '\0';
8999 spa.last_p_deltify = -1;
9000 spa.last_p_written = -1;
9001 spa.verbosity = verbosity;
9002 spa.delete_branches = &delete_branches;
9003 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9004 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9005 check_cancelled, NULL);
9006 if (spa.printed_something)
9007 putchar('\n');
9008 if (error)
9009 goto done;
9010 if (!spa.sent_something && verbosity >= 0)
9011 printf("Already up-to-date\n");
9012 done:
9013 if (sendpid > 0) {
9014 if (kill(sendpid, SIGTERM) == -1)
9015 error = got_error_from_errno("kill");
9016 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9017 error = got_error_from_errno("waitpid");
9019 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9020 error = got_error_from_errno("close");
9021 if (repo) {
9022 const struct got_error *close_err = got_repo_close(repo);
9023 if (error == NULL)
9024 error = close_err;
9026 if (worktree)
9027 got_worktree_close(worktree);
9028 if (pack_fds) {
9029 const struct got_error *pack_err =
9030 got_repo_pack_fds_close(pack_fds);
9031 if (error == NULL)
9032 error = pack_err;
9034 if (ref)
9035 got_ref_close(ref);
9036 got_pathlist_free(&branches);
9037 got_pathlist_free(&tags);
9038 got_ref_list_free(&all_branches);
9039 got_ref_list_free(&all_tags);
9040 got_pathlist_free(&delete_args);
9041 TAILQ_FOREACH(pe, &delete_branches, entry)
9042 free((char *)pe->path);
9043 got_pathlist_free(&delete_branches);
9044 free(cwd);
9045 free(repo_path);
9046 free(proto);
9047 free(host);
9048 free(port);
9049 free(server_path);
9050 free(repo_name);
9051 return error;
9054 __dead static void
9055 usage_cherrypick(void)
9057 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9058 exit(1);
9061 static const struct got_error *
9062 cmd_cherrypick(int argc, char *argv[])
9064 const struct got_error *error = NULL;
9065 struct got_worktree *worktree = NULL;
9066 struct got_repository *repo = NULL;
9067 char *cwd = NULL, *commit_id_str = NULL;
9068 struct got_object_id *commit_id = NULL;
9069 struct got_commit_object *commit = NULL;
9070 struct got_object_qid *pid;
9071 int ch;
9072 struct got_update_progress_arg upa;
9073 int *pack_fds = NULL;
9075 while ((ch = getopt(argc, argv, "")) != -1) {
9076 switch (ch) {
9077 default:
9078 usage_cherrypick();
9079 /* NOTREACHED */
9083 argc -= optind;
9084 argv += optind;
9086 #ifndef PROFILE
9087 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9088 "unveil", NULL) == -1)
9089 err(1, "pledge");
9090 #endif
9091 if (argc != 1)
9092 usage_cherrypick();
9094 cwd = getcwd(NULL, 0);
9095 if (cwd == NULL) {
9096 error = got_error_from_errno("getcwd");
9097 goto done;
9100 error = got_repo_pack_fds_open(&pack_fds);
9101 if (error != NULL)
9102 goto done;
9104 error = got_worktree_open(&worktree, cwd);
9105 if (error) {
9106 if (error->code == GOT_ERR_NOT_WORKTREE)
9107 error = wrap_not_worktree_error(error, "cherrypick",
9108 cwd);
9109 goto done;
9112 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9113 NULL, pack_fds);
9114 if (error != NULL)
9115 goto done;
9117 error = apply_unveil(got_repo_get_path(repo), 0,
9118 got_worktree_get_root_path(worktree));
9119 if (error)
9120 goto done;
9122 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9123 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9124 if (error)
9125 goto done;
9126 error = got_object_id_str(&commit_id_str, commit_id);
9127 if (error)
9128 goto done;
9130 error = got_object_open_as_commit(&commit, repo, commit_id);
9131 if (error)
9132 goto done;
9133 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9134 memset(&upa, 0, sizeof(upa));
9135 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9136 commit_id, repo, update_progress, &upa, check_cancelled,
9137 NULL);
9138 if (error != NULL)
9139 goto done;
9141 if (upa.did_something)
9142 printf("Merged commit %s\n", commit_id_str);
9143 print_merge_progress_stats(&upa);
9144 done:
9145 if (commit)
9146 got_object_commit_close(commit);
9147 free(commit_id_str);
9148 if (worktree)
9149 got_worktree_close(worktree);
9150 if (repo) {
9151 const struct got_error *close_err = got_repo_close(repo);
9152 if (error == NULL)
9153 error = close_err;
9155 if (pack_fds) {
9156 const struct got_error *pack_err =
9157 got_repo_pack_fds_close(pack_fds);
9158 if (error == NULL)
9159 error = pack_err;
9162 return error;
9165 __dead static void
9166 usage_backout(void)
9168 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9169 exit(1);
9172 static const struct got_error *
9173 cmd_backout(int argc, char *argv[])
9175 const struct got_error *error = NULL;
9176 struct got_worktree *worktree = NULL;
9177 struct got_repository *repo = NULL;
9178 char *cwd = NULL, *commit_id_str = NULL;
9179 struct got_object_id *commit_id = NULL;
9180 struct got_commit_object *commit = NULL;
9181 struct got_object_qid *pid;
9182 int ch;
9183 struct got_update_progress_arg upa;
9184 int *pack_fds = NULL;
9186 while ((ch = getopt(argc, argv, "")) != -1) {
9187 switch (ch) {
9188 default:
9189 usage_backout();
9190 /* NOTREACHED */
9194 argc -= optind;
9195 argv += optind;
9197 #ifndef PROFILE
9198 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9199 "unveil", NULL) == -1)
9200 err(1, "pledge");
9201 #endif
9202 if (argc != 1)
9203 usage_backout();
9205 cwd = getcwd(NULL, 0);
9206 if (cwd == NULL) {
9207 error = got_error_from_errno("getcwd");
9208 goto done;
9211 error = got_repo_pack_fds_open(&pack_fds);
9212 if (error != NULL)
9213 goto done;
9215 error = got_worktree_open(&worktree, cwd);
9216 if (error) {
9217 if (error->code == GOT_ERR_NOT_WORKTREE)
9218 error = wrap_not_worktree_error(error, "backout", cwd);
9219 goto done;
9222 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9223 NULL, pack_fds);
9224 if (error != NULL)
9225 goto done;
9227 error = apply_unveil(got_repo_get_path(repo), 0,
9228 got_worktree_get_root_path(worktree));
9229 if (error)
9230 goto done;
9232 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9233 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9234 if (error)
9235 goto done;
9236 error = got_object_id_str(&commit_id_str, commit_id);
9237 if (error)
9238 goto done;
9240 error = got_object_open_as_commit(&commit, repo, commit_id);
9241 if (error)
9242 goto done;
9243 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9244 if (pid == NULL) {
9245 error = got_error(GOT_ERR_ROOT_COMMIT);
9246 goto done;
9249 memset(&upa, 0, sizeof(upa));
9250 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9251 repo, update_progress, &upa, check_cancelled, NULL);
9252 if (error != NULL)
9253 goto done;
9255 if (upa.did_something)
9256 printf("Backed out commit %s\n", commit_id_str);
9257 print_merge_progress_stats(&upa);
9258 done:
9259 if (commit)
9260 got_object_commit_close(commit);
9261 free(commit_id_str);
9262 if (worktree)
9263 got_worktree_close(worktree);
9264 if (repo) {
9265 const struct got_error *close_err = got_repo_close(repo);
9266 if (error == NULL)
9267 error = close_err;
9269 if (pack_fds) {
9270 const struct got_error *pack_err =
9271 got_repo_pack_fds_close(pack_fds);
9272 if (error == NULL)
9273 error = pack_err;
9275 return error;
9278 __dead static void
9279 usage_rebase(void)
9281 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9282 getprogname());
9283 exit(1);
9286 static void
9287 trim_logmsg(char *logmsg, int limit)
9289 char *nl;
9290 size_t len;
9292 len = strlen(logmsg);
9293 if (len > limit)
9294 len = limit;
9295 logmsg[len] = '\0';
9296 nl = strchr(logmsg, '\n');
9297 if (nl)
9298 *nl = '\0';
9301 static const struct got_error *
9302 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9304 const struct got_error *err;
9305 char *logmsg0 = NULL;
9306 const char *s;
9308 err = got_object_commit_get_logmsg(&logmsg0, commit);
9309 if (err)
9310 return err;
9312 s = logmsg0;
9313 while (isspace((unsigned char)s[0]))
9314 s++;
9316 *logmsg = strdup(s);
9317 if (*logmsg == NULL) {
9318 err = got_error_from_errno("strdup");
9319 goto done;
9322 trim_logmsg(*logmsg, limit);
9323 done:
9324 free(logmsg0);
9325 return err;
9328 static const struct got_error *
9329 show_rebase_merge_conflict(struct got_object_id *id,
9330 struct got_repository *repo)
9332 const struct got_error *err;
9333 struct got_commit_object *commit = NULL;
9334 char *id_str = NULL, *logmsg = NULL;
9336 err = got_object_open_as_commit(&commit, repo, id);
9337 if (err)
9338 return err;
9340 err = got_object_id_str(&id_str, id);
9341 if (err)
9342 goto done;
9344 id_str[12] = '\0';
9346 err = get_short_logmsg(&logmsg, 42, commit);
9347 if (err)
9348 goto done;
9350 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9351 done:
9352 free(id_str);
9353 got_object_commit_close(commit);
9354 free(logmsg);
9355 return err;
9358 static const struct got_error *
9359 show_rebase_progress(struct got_commit_object *commit,
9360 struct got_object_id *old_id, struct got_object_id *new_id)
9362 const struct got_error *err;
9363 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9365 err = got_object_id_str(&old_id_str, old_id);
9366 if (err)
9367 goto done;
9369 if (new_id) {
9370 err = got_object_id_str(&new_id_str, new_id);
9371 if (err)
9372 goto done;
9375 old_id_str[12] = '\0';
9376 if (new_id_str)
9377 new_id_str[12] = '\0';
9379 err = get_short_logmsg(&logmsg, 42, commit);
9380 if (err)
9381 goto done;
9383 printf("%s -> %s: %s\n", old_id_str,
9384 new_id_str ? new_id_str : "no-op change", logmsg);
9385 done:
9386 free(old_id_str);
9387 free(new_id_str);
9388 free(logmsg);
9389 return err;
9392 static const struct got_error *
9393 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9394 struct got_reference *branch, struct got_reference *new_base_branch,
9395 struct got_reference *tmp_branch, struct got_repository *repo,
9396 int create_backup)
9398 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9399 return got_worktree_rebase_complete(worktree, fileindex,
9400 new_base_branch, tmp_branch, branch, repo, create_backup);
9403 static const struct got_error *
9404 rebase_commit(struct got_pathlist_head *merged_paths,
9405 struct got_worktree *worktree, struct got_fileindex *fileindex,
9406 struct got_reference *tmp_branch,
9407 struct got_object_id *commit_id, struct got_repository *repo)
9409 const struct got_error *error;
9410 struct got_commit_object *commit;
9411 struct got_object_id *new_commit_id;
9413 error = got_object_open_as_commit(&commit, repo, commit_id);
9414 if (error)
9415 return error;
9417 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9418 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9419 if (error) {
9420 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9421 goto done;
9422 error = show_rebase_progress(commit, commit_id, NULL);
9423 } else {
9424 error = show_rebase_progress(commit, commit_id, new_commit_id);
9425 free(new_commit_id);
9427 done:
9428 got_object_commit_close(commit);
9429 return error;
9432 struct check_path_prefix_arg {
9433 const char *path_prefix;
9434 size_t len;
9435 int errcode;
9438 static const struct got_error *
9439 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9440 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9441 struct got_object_id *id1, struct got_object_id *id2,
9442 const char *path1, const char *path2,
9443 mode_t mode1, mode_t mode2, struct got_repository *repo)
9445 struct check_path_prefix_arg *a = arg;
9447 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9448 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9449 return got_error(a->errcode);
9451 return NULL;
9454 static const struct got_error *
9455 check_path_prefix(struct got_object_id *parent_id,
9456 struct got_object_id *commit_id, const char *path_prefix,
9457 int errcode, struct got_repository *repo)
9459 const struct got_error *err;
9460 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9461 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9462 struct check_path_prefix_arg cpp_arg;
9464 if (got_path_is_root_dir(path_prefix))
9465 return NULL;
9467 err = got_object_open_as_commit(&commit, repo, commit_id);
9468 if (err)
9469 goto done;
9471 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9472 if (err)
9473 goto done;
9475 err = got_object_open_as_tree(&tree1, repo,
9476 got_object_commit_get_tree_id(parent_commit));
9477 if (err)
9478 goto done;
9480 err = got_object_open_as_tree(&tree2, repo,
9481 got_object_commit_get_tree_id(commit));
9482 if (err)
9483 goto done;
9485 cpp_arg.path_prefix = path_prefix;
9486 while (cpp_arg.path_prefix[0] == '/')
9487 cpp_arg.path_prefix++;
9488 cpp_arg.len = strlen(cpp_arg.path_prefix);
9489 cpp_arg.errcode = errcode;
9490 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9491 check_path_prefix_in_diff, &cpp_arg, 0);
9492 done:
9493 if (tree1)
9494 got_object_tree_close(tree1);
9495 if (tree2)
9496 got_object_tree_close(tree2);
9497 if (commit)
9498 got_object_commit_close(commit);
9499 if (parent_commit)
9500 got_object_commit_close(parent_commit);
9501 return err;
9504 static const struct got_error *
9505 collect_commits(struct got_object_id_queue *commits,
9506 struct got_object_id *initial_commit_id,
9507 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9508 const char *path_prefix, int path_prefix_errcode,
9509 struct got_repository *repo)
9511 const struct got_error *err = NULL;
9512 struct got_commit_graph *graph = NULL;
9513 struct got_object_id *parent_id = NULL;
9514 struct got_object_qid *qid;
9515 struct got_object_id *commit_id = initial_commit_id;
9517 err = got_commit_graph_open(&graph, "/", 1);
9518 if (err)
9519 return err;
9521 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9522 check_cancelled, NULL);
9523 if (err)
9524 goto done;
9525 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9526 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9527 check_cancelled, NULL);
9528 if (err) {
9529 if (err->code == GOT_ERR_ITER_COMPLETED) {
9530 err = got_error_msg(GOT_ERR_ANCESTRY,
9531 "ran out of commits to rebase before "
9532 "youngest common ancestor commit has "
9533 "been reached?!?");
9535 goto done;
9536 } else {
9537 err = check_path_prefix(parent_id, commit_id,
9538 path_prefix, path_prefix_errcode, repo);
9539 if (err)
9540 goto done;
9542 err = got_object_qid_alloc(&qid, commit_id);
9543 if (err)
9544 goto done;
9545 STAILQ_INSERT_HEAD(commits, qid, entry);
9546 commit_id = parent_id;
9549 done:
9550 got_commit_graph_close(graph);
9551 return err;
9554 static const struct got_error *
9555 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9557 const struct got_error *err = NULL;
9558 time_t committer_time;
9559 struct tm tm;
9560 char datebuf[11]; /* YYYY-MM-DD + NUL */
9561 char *author0 = NULL, *author, *smallerthan;
9562 char *logmsg0 = NULL, *logmsg, *newline;
9564 committer_time = got_object_commit_get_committer_time(commit);
9565 if (gmtime_r(&committer_time, &tm) == NULL)
9566 return got_error_from_errno("gmtime_r");
9567 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9568 return got_error(GOT_ERR_NO_SPACE);
9570 author0 = strdup(got_object_commit_get_author(commit));
9571 if (author0 == NULL)
9572 return got_error_from_errno("strdup");
9573 author = author0;
9574 smallerthan = strchr(author, '<');
9575 if (smallerthan && smallerthan[1] != '\0')
9576 author = smallerthan + 1;
9577 author[strcspn(author, "@>")] = '\0';
9579 err = got_object_commit_get_logmsg(&logmsg0, commit);
9580 if (err)
9581 goto done;
9582 logmsg = logmsg0;
9583 while (*logmsg == '\n')
9584 logmsg++;
9585 newline = strchr(logmsg, '\n');
9586 if (newline)
9587 *newline = '\0';
9589 if (asprintf(brief_str, "%s %s %s",
9590 datebuf, author, logmsg) == -1)
9591 err = got_error_from_errno("asprintf");
9592 done:
9593 free(author0);
9594 free(logmsg0);
9595 return err;
9598 static const struct got_error *
9599 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9600 struct got_repository *repo)
9602 const struct got_error *err;
9603 char *id_str;
9605 err = got_object_id_str(&id_str, id);
9606 if (err)
9607 return err;
9609 err = got_ref_delete(ref, repo);
9610 if (err)
9611 goto done;
9613 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9614 done:
9615 free(id_str);
9616 return err;
9619 static const struct got_error *
9620 print_backup_ref(const char *branch_name, const char *new_id_str,
9621 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9622 struct got_reflist_object_id_map *refs_idmap,
9623 struct got_repository *repo)
9625 const struct got_error *err = NULL;
9626 struct got_reflist_head *refs;
9627 char *refs_str = NULL;
9628 struct got_object_id *new_commit_id = NULL;
9629 struct got_commit_object *new_commit = NULL;
9630 char *new_commit_brief_str = NULL;
9631 struct got_object_id *yca_id = NULL;
9632 struct got_commit_object *yca_commit = NULL;
9633 char *yca_id_str = NULL, *yca_brief_str = NULL;
9634 char *custom_refs_str;
9636 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9637 return got_error_from_errno("asprintf");
9639 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9640 0, 0, refs_idmap, custom_refs_str);
9641 if (err)
9642 goto done;
9644 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9645 if (err)
9646 goto done;
9648 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9649 if (refs) {
9650 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9651 if (err)
9652 goto done;
9655 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9656 if (err)
9657 goto done;
9659 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9660 if (err)
9661 goto done;
9663 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9664 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9665 if (err)
9666 goto done;
9668 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9669 refs_str ? " (" : "", refs_str ? refs_str : "",
9670 refs_str ? ")" : "", new_commit_brief_str);
9671 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9672 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9673 free(refs_str);
9674 refs_str = NULL;
9676 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9677 if (err)
9678 goto done;
9680 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9681 if (err)
9682 goto done;
9684 err = got_object_id_str(&yca_id_str, yca_id);
9685 if (err)
9686 goto done;
9688 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9689 if (refs) {
9690 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9691 if (err)
9692 goto done;
9694 printf("history forked at %s%s%s%s\n %s\n",
9695 yca_id_str,
9696 refs_str ? " (" : "", refs_str ? refs_str : "",
9697 refs_str ? ")" : "", yca_brief_str);
9699 done:
9700 free(custom_refs_str);
9701 free(new_commit_id);
9702 free(refs_str);
9703 free(yca_id);
9704 free(yca_id_str);
9705 free(yca_brief_str);
9706 if (new_commit)
9707 got_object_commit_close(new_commit);
9708 if (yca_commit)
9709 got_object_commit_close(yca_commit);
9711 return NULL;
9714 static const struct got_error *
9715 process_backup_refs(const char *backup_ref_prefix,
9716 const char *wanted_branch_name,
9717 int delete, struct got_repository *repo)
9719 const struct got_error *err;
9720 struct got_reflist_head refs, backup_refs;
9721 struct got_reflist_entry *re;
9722 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9723 struct got_object_id *old_commit_id = NULL;
9724 char *branch_name = NULL;
9725 struct got_commit_object *old_commit = NULL;
9726 struct got_reflist_object_id_map *refs_idmap = NULL;
9727 int wanted_branch_found = 0;
9729 TAILQ_INIT(&refs);
9730 TAILQ_INIT(&backup_refs);
9732 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9733 if (err)
9734 return err;
9736 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9737 if (err)
9738 goto done;
9740 if (wanted_branch_name) {
9741 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9742 wanted_branch_name += 11;
9745 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9746 got_ref_cmp_by_commit_timestamp_descending, repo);
9747 if (err)
9748 goto done;
9750 TAILQ_FOREACH(re, &backup_refs, entry) {
9751 const char *refname = got_ref_get_name(re->ref);
9752 char *slash;
9754 err = check_cancelled(NULL);
9755 if (err)
9756 break;
9758 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9759 if (err)
9760 break;
9762 err = got_object_open_as_commit(&old_commit, repo,
9763 old_commit_id);
9764 if (err)
9765 break;
9767 if (strncmp(backup_ref_prefix, refname,
9768 backup_ref_prefix_len) == 0)
9769 refname += backup_ref_prefix_len;
9771 while (refname[0] == '/')
9772 refname++;
9774 branch_name = strdup(refname);
9775 if (branch_name == NULL) {
9776 err = got_error_from_errno("strdup");
9777 break;
9779 slash = strrchr(branch_name, '/');
9780 if (slash) {
9781 *slash = '\0';
9782 refname += strlen(branch_name) + 1;
9785 if (wanted_branch_name == NULL ||
9786 strcmp(wanted_branch_name, branch_name) == 0) {
9787 wanted_branch_found = 1;
9788 if (delete) {
9789 err = delete_backup_ref(re->ref,
9790 old_commit_id, repo);
9791 } else {
9792 err = print_backup_ref(branch_name, refname,
9793 old_commit_id, old_commit, refs_idmap,
9794 repo);
9796 if (err)
9797 break;
9800 free(old_commit_id);
9801 old_commit_id = NULL;
9802 free(branch_name);
9803 branch_name = NULL;
9804 got_object_commit_close(old_commit);
9805 old_commit = NULL;
9808 if (wanted_branch_name && !wanted_branch_found) {
9809 err = got_error_fmt(GOT_ERR_NOT_REF,
9810 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9812 done:
9813 if (refs_idmap)
9814 got_reflist_object_id_map_free(refs_idmap);
9815 got_ref_list_free(&refs);
9816 got_ref_list_free(&backup_refs);
9817 free(old_commit_id);
9818 free(branch_name);
9819 if (old_commit)
9820 got_object_commit_close(old_commit);
9821 return err;
9824 static const struct got_error *
9825 abort_progress(void *arg, unsigned char status, const char *path)
9828 * Unversioned files should not clutter progress output when
9829 * an operation is aborted.
9831 if (status == GOT_STATUS_UNVERSIONED)
9832 return NULL;
9834 return update_progress(arg, status, path);
9837 static const struct got_error *
9838 cmd_rebase(int argc, char *argv[])
9840 const struct got_error *error = NULL;
9841 struct got_worktree *worktree = NULL;
9842 struct got_repository *repo = NULL;
9843 struct got_fileindex *fileindex = NULL;
9844 char *cwd = NULL;
9845 struct got_reference *branch = NULL;
9846 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9847 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9848 struct got_object_id *resume_commit_id = NULL;
9849 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9850 struct got_commit_object *commit = NULL;
9851 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9852 int histedit_in_progress = 0, merge_in_progress = 0;
9853 int create_backup = 1, list_backups = 0, delete_backups = 0;
9854 struct got_object_id_queue commits;
9855 struct got_pathlist_head merged_paths;
9856 const struct got_object_id_queue *parent_ids;
9857 struct got_object_qid *qid, *pid;
9858 struct got_update_progress_arg upa;
9859 int *pack_fds = NULL;
9861 STAILQ_INIT(&commits);
9862 TAILQ_INIT(&merged_paths);
9863 memset(&upa, 0, sizeof(upa));
9865 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9866 switch (ch) {
9867 case 'a':
9868 abort_rebase = 1;
9869 break;
9870 case 'c':
9871 continue_rebase = 1;
9872 break;
9873 case 'l':
9874 list_backups = 1;
9875 break;
9876 case 'X':
9877 delete_backups = 1;
9878 break;
9879 default:
9880 usage_rebase();
9881 /* NOTREACHED */
9885 argc -= optind;
9886 argv += optind;
9888 #ifndef PROFILE
9889 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9890 "unveil", NULL) == -1)
9891 err(1, "pledge");
9892 #endif
9893 if (list_backups) {
9894 if (abort_rebase)
9895 option_conflict('l', 'a');
9896 if (continue_rebase)
9897 option_conflict('l', 'c');
9898 if (delete_backups)
9899 option_conflict('l', 'X');
9900 if (argc != 0 && argc != 1)
9901 usage_rebase();
9902 } else if (delete_backups) {
9903 if (abort_rebase)
9904 option_conflict('X', 'a');
9905 if (continue_rebase)
9906 option_conflict('X', 'c');
9907 if (list_backups)
9908 option_conflict('l', 'X');
9909 if (argc != 0 && argc != 1)
9910 usage_rebase();
9911 } else {
9912 if (abort_rebase && continue_rebase)
9913 usage_rebase();
9914 else if (abort_rebase || continue_rebase) {
9915 if (argc != 0)
9916 usage_rebase();
9917 } else if (argc != 1)
9918 usage_rebase();
9921 cwd = getcwd(NULL, 0);
9922 if (cwd == NULL) {
9923 error = got_error_from_errno("getcwd");
9924 goto done;
9927 error = got_repo_pack_fds_open(&pack_fds);
9928 if (error != NULL)
9929 goto done;
9931 error = got_worktree_open(&worktree, cwd);
9932 if (error) {
9933 if (list_backups || delete_backups) {
9934 if (error->code != GOT_ERR_NOT_WORKTREE)
9935 goto done;
9936 } else {
9937 if (error->code == GOT_ERR_NOT_WORKTREE)
9938 error = wrap_not_worktree_error(error,
9939 "rebase", cwd);
9940 goto done;
9944 error = got_repo_open(&repo,
9945 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9946 pack_fds);
9947 if (error != NULL)
9948 goto done;
9950 error = apply_unveil(got_repo_get_path(repo), 0,
9951 worktree ? got_worktree_get_root_path(worktree) : NULL);
9952 if (error)
9953 goto done;
9955 if (list_backups || delete_backups) {
9956 error = process_backup_refs(
9957 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9958 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9959 goto done; /* nothing else to do */
9962 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9963 worktree);
9964 if (error)
9965 goto done;
9966 if (histedit_in_progress) {
9967 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9968 goto done;
9971 error = got_worktree_merge_in_progress(&merge_in_progress,
9972 worktree, repo);
9973 if (error)
9974 goto done;
9975 if (merge_in_progress) {
9976 error = got_error(GOT_ERR_MERGE_BUSY);
9977 goto done;
9980 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9981 if (error)
9982 goto done;
9984 if (abort_rebase) {
9985 if (!rebase_in_progress) {
9986 error = got_error(GOT_ERR_NOT_REBASING);
9987 goto done;
9989 error = got_worktree_rebase_continue(&resume_commit_id,
9990 &new_base_branch, &tmp_branch, &branch, &fileindex,
9991 worktree, repo);
9992 if (error)
9993 goto done;
9994 printf("Switching work tree to %s\n",
9995 got_ref_get_symref_target(new_base_branch));
9996 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9997 new_base_branch, abort_progress, &upa);
9998 if (error)
9999 goto done;
10000 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10001 print_merge_progress_stats(&upa);
10002 goto done; /* nothing else to do */
10005 if (continue_rebase) {
10006 if (!rebase_in_progress) {
10007 error = got_error(GOT_ERR_NOT_REBASING);
10008 goto done;
10010 error = got_worktree_rebase_continue(&resume_commit_id,
10011 &new_base_branch, &tmp_branch, &branch, &fileindex,
10012 worktree, repo);
10013 if (error)
10014 goto done;
10016 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10017 resume_commit_id, repo);
10018 if (error)
10019 goto done;
10021 yca_id = got_object_id_dup(resume_commit_id);
10022 if (yca_id == NULL) {
10023 error = got_error_from_errno("got_object_id_dup");
10024 goto done;
10026 } else {
10027 error = got_ref_open(&branch, repo, argv[0], 0);
10028 if (error != NULL)
10029 goto done;
10032 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10033 if (error)
10034 goto done;
10036 if (!continue_rebase) {
10037 struct got_object_id *base_commit_id;
10039 base_commit_id = got_worktree_get_base_commit_id(worktree);
10040 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10041 base_commit_id, branch_head_commit_id, 1, repo,
10042 check_cancelled, NULL);
10043 if (error)
10044 goto done;
10045 if (yca_id == NULL) {
10046 error = got_error_msg(GOT_ERR_ANCESTRY,
10047 "specified branch shares no common ancestry "
10048 "with work tree's branch");
10049 goto done;
10052 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10053 if (error) {
10054 if (error->code != GOT_ERR_ANCESTRY)
10055 goto done;
10056 error = NULL;
10057 } else {
10058 struct got_pathlist_head paths;
10059 printf("%s is already based on %s\n",
10060 got_ref_get_name(branch),
10061 got_worktree_get_head_ref_name(worktree));
10062 error = switch_head_ref(branch, branch_head_commit_id,
10063 worktree, repo);
10064 if (error)
10065 goto done;
10066 error = got_worktree_set_base_commit_id(worktree, repo,
10067 branch_head_commit_id);
10068 if (error)
10069 goto done;
10070 TAILQ_INIT(&paths);
10071 error = got_pathlist_append(&paths, "", NULL);
10072 if (error)
10073 goto done;
10074 error = got_worktree_checkout_files(worktree,
10075 &paths, repo, update_progress, &upa,
10076 check_cancelled, NULL);
10077 got_pathlist_free(&paths);
10078 if (error)
10079 goto done;
10080 if (upa.did_something) {
10081 char *id_str;
10082 error = got_object_id_str(&id_str,
10083 branch_head_commit_id);
10084 if (error)
10085 goto done;
10086 printf("Updated to %s: %s\n",
10087 got_worktree_get_head_ref_name(worktree),
10088 id_str);
10089 free(id_str);
10090 } else
10091 printf("Already up-to-date\n");
10092 print_update_progress_stats(&upa);
10093 goto done;
10097 commit_id = branch_head_commit_id;
10098 error = got_object_open_as_commit(&commit, repo, commit_id);
10099 if (error)
10100 goto done;
10102 parent_ids = got_object_commit_get_parent_ids(commit);
10103 pid = STAILQ_FIRST(parent_ids);
10104 if (pid == NULL) {
10105 error = got_error(GOT_ERR_EMPTY_REBASE);
10106 goto done;
10108 error = collect_commits(&commits, commit_id, &pid->id,
10109 yca_id, got_worktree_get_path_prefix(worktree),
10110 GOT_ERR_REBASE_PATH, repo);
10111 got_object_commit_close(commit);
10112 commit = NULL;
10113 if (error)
10114 goto done;
10116 if (!continue_rebase) {
10117 error = got_worktree_rebase_prepare(&new_base_branch,
10118 &tmp_branch, &fileindex, worktree, branch, repo);
10119 if (error)
10120 goto done;
10123 if (STAILQ_EMPTY(&commits)) {
10124 if (continue_rebase) {
10125 error = rebase_complete(worktree, fileindex,
10126 branch, new_base_branch, tmp_branch, repo,
10127 create_backup);
10128 goto done;
10129 } else {
10130 /* Fast-forward the reference of the branch. */
10131 struct got_object_id *new_head_commit_id;
10132 char *id_str;
10133 error = got_ref_resolve(&new_head_commit_id, repo,
10134 new_base_branch);
10135 if (error)
10136 goto done;
10137 error = got_object_id_str(&id_str, new_head_commit_id);
10138 printf("Forwarding %s to commit %s\n",
10139 got_ref_get_name(branch), id_str);
10140 free(id_str);
10141 error = got_ref_change_ref(branch,
10142 new_head_commit_id);
10143 if (error)
10144 goto done;
10145 /* No backup needed since objects did not change. */
10146 create_backup = 0;
10150 pid = NULL;
10151 STAILQ_FOREACH(qid, &commits, entry) {
10153 commit_id = &qid->id;
10154 parent_id = pid ? &pid->id : yca_id;
10155 pid = qid;
10157 memset(&upa, 0, sizeof(upa));
10158 error = got_worktree_rebase_merge_files(&merged_paths,
10159 worktree, fileindex, parent_id, commit_id, repo,
10160 update_progress, &upa, check_cancelled, NULL);
10161 if (error)
10162 goto done;
10164 print_merge_progress_stats(&upa);
10165 if (upa.conflicts > 0 || upa.missing > 0 ||
10166 upa.not_deleted > 0 || upa.unversioned > 0) {
10167 if (upa.conflicts > 0) {
10168 error = show_rebase_merge_conflict(&qid->id,
10169 repo);
10170 if (error)
10171 goto done;
10173 got_worktree_rebase_pathlist_free(&merged_paths);
10174 break;
10177 error = rebase_commit(&merged_paths, worktree, fileindex,
10178 tmp_branch, commit_id, repo);
10179 got_worktree_rebase_pathlist_free(&merged_paths);
10180 if (error)
10181 goto done;
10184 if (upa.conflicts > 0 || upa.missing > 0 ||
10185 upa.not_deleted > 0 || upa.unversioned > 0) {
10186 error = got_worktree_rebase_postpone(worktree, fileindex);
10187 if (error)
10188 goto done;
10189 if (upa.conflicts > 0 && upa.missing == 0 &&
10190 upa.not_deleted == 0 && upa.unversioned == 0) {
10191 error = got_error_msg(GOT_ERR_CONFLICTS,
10192 "conflicts must be resolved before rebasing "
10193 "can continue");
10194 } else if (upa.conflicts > 0) {
10195 error = got_error_msg(GOT_ERR_CONFLICTS,
10196 "conflicts must be resolved before rebasing "
10197 "can continue; changes destined for some "
10198 "files were not yet merged and should be "
10199 "merged manually if required before the "
10200 "rebase operation is continued");
10201 } else {
10202 error = got_error_msg(GOT_ERR_CONFLICTS,
10203 "changes destined for some files were not "
10204 "yet merged and should be merged manually "
10205 "if required before the rebase operation "
10206 "is continued");
10208 } else
10209 error = rebase_complete(worktree, fileindex, branch,
10210 new_base_branch, tmp_branch, repo, create_backup);
10211 done:
10212 got_object_id_queue_free(&commits);
10213 free(branch_head_commit_id);
10214 free(resume_commit_id);
10215 free(yca_id);
10216 if (commit)
10217 got_object_commit_close(commit);
10218 if (branch)
10219 got_ref_close(branch);
10220 if (new_base_branch)
10221 got_ref_close(new_base_branch);
10222 if (tmp_branch)
10223 got_ref_close(tmp_branch);
10224 if (worktree)
10225 got_worktree_close(worktree);
10226 if (repo) {
10227 const struct got_error *close_err = got_repo_close(repo);
10228 if (error == NULL)
10229 error = close_err;
10231 if (pack_fds) {
10232 const struct got_error *pack_err =
10233 got_repo_pack_fds_close(pack_fds);
10234 if (error == NULL)
10235 error = pack_err;
10237 return error;
10240 __dead static void
10241 usage_histedit(void)
10243 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10244 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10245 getprogname());
10246 exit(1);
10249 #define GOT_HISTEDIT_PICK 'p'
10250 #define GOT_HISTEDIT_EDIT 'e'
10251 #define GOT_HISTEDIT_FOLD 'f'
10252 #define GOT_HISTEDIT_DROP 'd'
10253 #define GOT_HISTEDIT_MESG 'm'
10255 static const struct got_histedit_cmd {
10256 unsigned char code;
10257 const char *name;
10258 const char *desc;
10259 } got_histedit_cmds[] = {
10260 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10261 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10262 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10263 "be used" },
10264 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10265 { GOT_HISTEDIT_MESG, "mesg",
10266 "single-line log message for commit above (open editor if empty)" },
10269 struct got_histedit_list_entry {
10270 TAILQ_ENTRY(got_histedit_list_entry) entry;
10271 struct got_object_id *commit_id;
10272 const struct got_histedit_cmd *cmd;
10273 char *logmsg;
10275 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10277 static const struct got_error *
10278 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10279 FILE *f, struct got_repository *repo)
10281 const struct got_error *err = NULL;
10282 char *logmsg = NULL, *id_str = NULL;
10283 struct got_commit_object *commit = NULL;
10284 int n;
10286 err = got_object_open_as_commit(&commit, repo, commit_id);
10287 if (err)
10288 goto done;
10290 err = get_short_logmsg(&logmsg, 34, commit);
10291 if (err)
10292 goto done;
10294 err = got_object_id_str(&id_str, commit_id);
10295 if (err)
10296 goto done;
10298 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10299 if (n < 0)
10300 err = got_ferror(f, GOT_ERR_IO);
10301 done:
10302 if (commit)
10303 got_object_commit_close(commit);
10304 free(id_str);
10305 free(logmsg);
10306 return err;
10309 static const struct got_error *
10310 histedit_write_commit_list(struct got_object_id_queue *commits,
10311 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10312 struct got_repository *repo)
10314 const struct got_error *err = NULL;
10315 struct got_object_qid *qid;
10316 const char *histedit_cmd = NULL;
10318 if (STAILQ_EMPTY(commits))
10319 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10321 STAILQ_FOREACH(qid, commits, entry) {
10322 histedit_cmd = got_histedit_cmds[0].name;
10323 if (edit_only)
10324 histedit_cmd = "edit";
10325 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10326 histedit_cmd = "fold";
10327 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10328 if (err)
10329 break;
10330 if (edit_logmsg_only) {
10331 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10332 if (n < 0) {
10333 err = got_ferror(f, GOT_ERR_IO);
10334 break;
10339 return err;
10342 static const struct got_error *
10343 write_cmd_list(FILE *f, const char *branch_name,
10344 struct got_object_id_queue *commits)
10346 const struct got_error *err = NULL;
10347 size_t i;
10348 int n;
10349 char *id_str;
10350 struct got_object_qid *qid;
10352 qid = STAILQ_FIRST(commits);
10353 err = got_object_id_str(&id_str, &qid->id);
10354 if (err)
10355 return err;
10357 n = fprintf(f,
10358 "# Editing the history of branch '%s' starting at\n"
10359 "# commit %s\n"
10360 "# Commits will be processed in order from top to "
10361 "bottom of this file.\n", branch_name, id_str);
10362 if (n < 0) {
10363 err = got_ferror(f, GOT_ERR_IO);
10364 goto done;
10367 n = fprintf(f, "# Available histedit commands:\n");
10368 if (n < 0) {
10369 err = got_ferror(f, GOT_ERR_IO);
10370 goto done;
10373 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10374 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10375 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10376 cmd->desc);
10377 if (n < 0) {
10378 err = got_ferror(f, GOT_ERR_IO);
10379 break;
10382 done:
10383 free(id_str);
10384 return err;
10387 static const struct got_error *
10388 histedit_syntax_error(int lineno)
10390 static char msg[42];
10391 int ret;
10393 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10394 lineno);
10395 if (ret == -1 || ret >= sizeof(msg))
10396 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10398 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10401 static const struct got_error *
10402 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10403 char *logmsg, struct got_repository *repo)
10405 const struct got_error *err;
10406 struct got_commit_object *folded_commit = NULL;
10407 char *id_str, *folded_logmsg = NULL;
10409 err = got_object_id_str(&id_str, hle->commit_id);
10410 if (err)
10411 return err;
10413 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10414 if (err)
10415 goto done;
10417 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10418 if (err)
10419 goto done;
10420 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10421 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10422 folded_logmsg) == -1) {
10423 err = got_error_from_errno("asprintf");
10425 done:
10426 if (folded_commit)
10427 got_object_commit_close(folded_commit);
10428 free(id_str);
10429 free(folded_logmsg);
10430 return err;
10433 static struct got_histedit_list_entry *
10434 get_folded_commits(struct got_histedit_list_entry *hle)
10436 struct got_histedit_list_entry *prev, *folded = NULL;
10438 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10439 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10440 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10441 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10442 folded = prev;
10443 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10446 return folded;
10449 static const struct got_error *
10450 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10451 struct got_repository *repo)
10453 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10454 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10455 const struct got_error *err = NULL;
10456 struct got_commit_object *commit = NULL;
10457 int logmsg_len;
10458 int fd;
10459 struct got_histedit_list_entry *folded = NULL;
10461 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10462 if (err)
10463 return err;
10465 folded = get_folded_commits(hle);
10466 if (folded) {
10467 while (folded != hle) {
10468 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10469 folded = TAILQ_NEXT(folded, entry);
10470 continue;
10472 err = append_folded_commit_msg(&new_msg, folded,
10473 logmsg, repo);
10474 if (err)
10475 goto done;
10476 free(logmsg);
10477 logmsg = new_msg;
10478 folded = TAILQ_NEXT(folded, entry);
10482 err = got_object_id_str(&id_str, hle->commit_id);
10483 if (err)
10484 goto done;
10485 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10486 if (err)
10487 goto done;
10488 logmsg_len = asprintf(&new_msg,
10489 "%s\n# original log message of commit %s: %s",
10490 logmsg ? logmsg : "", id_str, orig_logmsg);
10491 if (logmsg_len == -1) {
10492 err = got_error_from_errno("asprintf");
10493 goto done;
10495 free(logmsg);
10496 logmsg = new_msg;
10498 err = got_object_id_str(&id_str, hle->commit_id);
10499 if (err)
10500 goto done;
10502 err = got_opentemp_named_fd(&logmsg_path, &fd,
10503 GOT_TMPDIR_STR "/got-logmsg");
10504 if (err)
10505 goto done;
10507 write(fd, logmsg, logmsg_len);
10508 close(fd);
10510 err = get_editor(&editor);
10511 if (err)
10512 goto done;
10514 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10515 logmsg_len, 0);
10516 if (err) {
10517 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10518 goto done;
10519 err = NULL;
10520 hle->logmsg = strdup(new_msg);
10521 if (hle->logmsg == NULL)
10522 err = got_error_from_errno("strdup");
10524 done:
10525 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10526 err = got_error_from_errno2("unlink", logmsg_path);
10527 free(logmsg_path);
10528 free(logmsg);
10529 free(orig_logmsg);
10530 free(editor);
10531 if (commit)
10532 got_object_commit_close(commit);
10533 return err;
10536 static const struct got_error *
10537 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10538 FILE *f, struct got_repository *repo)
10540 const struct got_error *err = NULL;
10541 char *line = NULL, *p, *end;
10542 size_t i, size;
10543 ssize_t len;
10544 int lineno = 0;
10545 const struct got_histedit_cmd *cmd;
10546 struct got_object_id *commit_id = NULL;
10547 struct got_histedit_list_entry *hle = NULL;
10549 for (;;) {
10550 len = getline(&line, &size, f);
10551 if (len == -1) {
10552 const struct got_error *getline_err;
10553 if (feof(f))
10554 break;
10555 getline_err = got_error_from_errno("getline");
10556 err = got_ferror(f, getline_err->code);
10557 break;
10559 lineno++;
10560 p = line;
10561 while (isspace((unsigned char)p[0]))
10562 p++;
10563 if (p[0] == '#' || p[0] == '\0') {
10564 free(line);
10565 line = NULL;
10566 continue;
10568 cmd = NULL;
10569 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10570 cmd = &got_histedit_cmds[i];
10571 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10572 isspace((unsigned char)p[strlen(cmd->name)])) {
10573 p += strlen(cmd->name);
10574 break;
10576 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10577 p++;
10578 break;
10581 if (i == nitems(got_histedit_cmds)) {
10582 err = histedit_syntax_error(lineno);
10583 break;
10585 while (isspace((unsigned char)p[0]))
10586 p++;
10587 if (cmd->code == GOT_HISTEDIT_MESG) {
10588 if (hle == NULL || hle->logmsg != NULL) {
10589 err = got_error(GOT_ERR_HISTEDIT_CMD);
10590 break;
10592 if (p[0] == '\0') {
10593 err = histedit_edit_logmsg(hle, repo);
10594 if (err)
10595 break;
10596 } else {
10597 hle->logmsg = strdup(p);
10598 if (hle->logmsg == NULL) {
10599 err = got_error_from_errno("strdup");
10600 break;
10603 free(line);
10604 line = NULL;
10605 continue;
10606 } else {
10607 end = p;
10608 while (end[0] && !isspace((unsigned char)end[0]))
10609 end++;
10610 *end = '\0';
10612 err = got_object_resolve_id_str(&commit_id, repo, p);
10613 if (err) {
10614 /* override error code */
10615 err = histedit_syntax_error(lineno);
10616 break;
10619 hle = malloc(sizeof(*hle));
10620 if (hle == NULL) {
10621 err = got_error_from_errno("malloc");
10622 break;
10624 hle->cmd = cmd;
10625 hle->commit_id = commit_id;
10626 hle->logmsg = NULL;
10627 commit_id = NULL;
10628 free(line);
10629 line = NULL;
10630 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10633 free(line);
10634 free(commit_id);
10635 return err;
10638 static const struct got_error *
10639 histedit_check_script(struct got_histedit_list *histedit_cmds,
10640 struct got_object_id_queue *commits, struct got_repository *repo)
10642 const struct got_error *err = NULL;
10643 struct got_object_qid *qid;
10644 struct got_histedit_list_entry *hle;
10645 static char msg[92];
10646 char *id_str;
10648 if (TAILQ_EMPTY(histedit_cmds))
10649 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10650 "histedit script contains no commands");
10651 if (STAILQ_EMPTY(commits))
10652 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10654 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10655 struct got_histedit_list_entry *hle2;
10656 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10657 if (hle == hle2)
10658 continue;
10659 if (got_object_id_cmp(hle->commit_id,
10660 hle2->commit_id) != 0)
10661 continue;
10662 err = got_object_id_str(&id_str, hle->commit_id);
10663 if (err)
10664 return err;
10665 snprintf(msg, sizeof(msg), "commit %s is listed "
10666 "more than once in histedit script", id_str);
10667 free(id_str);
10668 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10672 STAILQ_FOREACH(qid, commits, entry) {
10673 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10674 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10675 break;
10677 if (hle == NULL) {
10678 err = got_object_id_str(&id_str, &qid->id);
10679 if (err)
10680 return err;
10681 snprintf(msg, sizeof(msg),
10682 "commit %s missing from histedit script", id_str);
10683 free(id_str);
10684 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10688 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10689 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10690 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10691 "last commit in histedit script cannot be folded");
10693 return NULL;
10696 static const struct got_error *
10697 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10698 const char *path, struct got_object_id_queue *commits,
10699 struct got_repository *repo)
10701 const struct got_error *err = NULL;
10702 char *editor;
10703 FILE *f = NULL;
10705 err = get_editor(&editor);
10706 if (err)
10707 return err;
10709 if (spawn_editor(editor, path) == -1) {
10710 err = got_error_from_errno("failed spawning editor");
10711 goto done;
10714 f = fopen(path, "re");
10715 if (f == NULL) {
10716 err = got_error_from_errno("fopen");
10717 goto done;
10719 err = histedit_parse_list(histedit_cmds, f, repo);
10720 if (err)
10721 goto done;
10723 err = histedit_check_script(histedit_cmds, commits, repo);
10724 done:
10725 if (f && fclose(f) == EOF && err == NULL)
10726 err = got_error_from_errno("fclose");
10727 free(editor);
10728 return err;
10731 static const struct got_error *
10732 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10733 struct got_object_id_queue *, const char *, const char *,
10734 struct got_repository *);
10736 static const struct got_error *
10737 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10738 struct got_object_id_queue *commits, const char *branch_name,
10739 int edit_logmsg_only, int fold_only, int edit_only,
10740 struct got_repository *repo)
10742 const struct got_error *err;
10743 FILE *f = NULL;
10744 char *path = NULL;
10746 err = got_opentemp_named(&path, &f, "got-histedit");
10747 if (err)
10748 return err;
10750 err = write_cmd_list(f, branch_name, commits);
10751 if (err)
10752 goto done;
10754 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10755 fold_only, edit_only, repo);
10756 if (err)
10757 goto done;
10759 if (edit_logmsg_only || fold_only || edit_only) {
10760 rewind(f);
10761 err = histedit_parse_list(histedit_cmds, f, repo);
10762 } else {
10763 if (fclose(f) == EOF) {
10764 err = got_error_from_errno("fclose");
10765 goto done;
10767 f = NULL;
10768 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10769 if (err) {
10770 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10771 err->code != GOT_ERR_HISTEDIT_CMD)
10772 goto done;
10773 err = histedit_edit_list_retry(histedit_cmds, err,
10774 commits, path, branch_name, repo);
10777 done:
10778 if (f && fclose(f) == EOF && err == NULL)
10779 err = got_error_from_errno("fclose");
10780 if (path && unlink(path) != 0 && err == NULL)
10781 err = got_error_from_errno2("unlink", path);
10782 free(path);
10783 return err;
10786 static const struct got_error *
10787 histedit_save_list(struct got_histedit_list *histedit_cmds,
10788 struct got_worktree *worktree, struct got_repository *repo)
10790 const struct got_error *err = NULL;
10791 char *path = NULL;
10792 FILE *f = NULL;
10793 struct got_histedit_list_entry *hle;
10794 struct got_commit_object *commit = NULL;
10796 err = got_worktree_get_histedit_script_path(&path, worktree);
10797 if (err)
10798 return err;
10800 f = fopen(path, "we");
10801 if (f == NULL) {
10802 err = got_error_from_errno2("fopen", path);
10803 goto done;
10805 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10806 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10807 repo);
10808 if (err)
10809 break;
10811 if (hle->logmsg) {
10812 int n = fprintf(f, "%c %s\n",
10813 GOT_HISTEDIT_MESG, hle->logmsg);
10814 if (n < 0) {
10815 err = got_ferror(f, GOT_ERR_IO);
10816 break;
10820 done:
10821 if (f && fclose(f) == EOF && err == NULL)
10822 err = got_error_from_errno("fclose");
10823 free(path);
10824 if (commit)
10825 got_object_commit_close(commit);
10826 return err;
10829 static void
10830 histedit_free_list(struct got_histedit_list *histedit_cmds)
10832 struct got_histedit_list_entry *hle;
10834 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10835 TAILQ_REMOVE(histedit_cmds, hle, entry);
10836 free(hle);
10840 static const struct got_error *
10841 histedit_load_list(struct got_histedit_list *histedit_cmds,
10842 const char *path, struct got_repository *repo)
10844 const struct got_error *err = NULL;
10845 FILE *f = NULL;
10847 f = fopen(path, "re");
10848 if (f == NULL) {
10849 err = got_error_from_errno2("fopen", path);
10850 goto done;
10853 err = histedit_parse_list(histedit_cmds, f, repo);
10854 done:
10855 if (f && fclose(f) == EOF && err == NULL)
10856 err = got_error_from_errno("fclose");
10857 return err;
10860 static const struct got_error *
10861 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10862 const struct got_error *edit_err, struct got_object_id_queue *commits,
10863 const char *path, const char *branch_name, struct got_repository *repo)
10865 const struct got_error *err = NULL, *prev_err = edit_err;
10866 int resp = ' ';
10868 while (resp != 'c' && resp != 'r' && resp != 'a') {
10869 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10870 "or (a)bort: ", getprogname(), prev_err->msg);
10871 resp = getchar();
10872 if (resp == '\n')
10873 resp = getchar();
10874 if (resp == 'c') {
10875 histedit_free_list(histedit_cmds);
10876 err = histedit_run_editor(histedit_cmds, path, commits,
10877 repo);
10878 if (err) {
10879 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10880 err->code != GOT_ERR_HISTEDIT_CMD)
10881 break;
10882 prev_err = err;
10883 resp = ' ';
10884 continue;
10886 break;
10887 } else if (resp == 'r') {
10888 histedit_free_list(histedit_cmds);
10889 err = histedit_edit_script(histedit_cmds,
10890 commits, branch_name, 0, 0, 0, repo);
10891 if (err) {
10892 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10893 err->code != GOT_ERR_HISTEDIT_CMD)
10894 break;
10895 prev_err = err;
10896 resp = ' ';
10897 continue;
10899 break;
10900 } else if (resp == 'a') {
10901 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10902 break;
10903 } else
10904 printf("invalid response '%c'\n", resp);
10907 return err;
10910 static const struct got_error *
10911 histedit_complete(struct got_worktree *worktree,
10912 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10913 struct got_reference *branch, struct got_repository *repo)
10915 printf("Switching work tree to %s\n",
10916 got_ref_get_symref_target(branch));
10917 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10918 branch, repo);
10921 static const struct got_error *
10922 show_histedit_progress(struct got_commit_object *commit,
10923 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10925 const struct got_error *err;
10926 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10928 err = got_object_id_str(&old_id_str, hle->commit_id);
10929 if (err)
10930 goto done;
10932 if (new_id) {
10933 err = got_object_id_str(&new_id_str, new_id);
10934 if (err)
10935 goto done;
10938 old_id_str[12] = '\0';
10939 if (new_id_str)
10940 new_id_str[12] = '\0';
10942 if (hle->logmsg) {
10943 logmsg = strdup(hle->logmsg);
10944 if (logmsg == NULL) {
10945 err = got_error_from_errno("strdup");
10946 goto done;
10948 trim_logmsg(logmsg, 42);
10949 } else {
10950 err = get_short_logmsg(&logmsg, 42, commit);
10951 if (err)
10952 goto done;
10955 switch (hle->cmd->code) {
10956 case GOT_HISTEDIT_PICK:
10957 case GOT_HISTEDIT_EDIT:
10958 printf("%s -> %s: %s\n", old_id_str,
10959 new_id_str ? new_id_str : "no-op change", logmsg);
10960 break;
10961 case GOT_HISTEDIT_DROP:
10962 case GOT_HISTEDIT_FOLD:
10963 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10964 logmsg);
10965 break;
10966 default:
10967 break;
10969 done:
10970 free(old_id_str);
10971 free(new_id_str);
10972 return err;
10975 static const struct got_error *
10976 histedit_commit(struct got_pathlist_head *merged_paths,
10977 struct got_worktree *worktree, struct got_fileindex *fileindex,
10978 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10979 struct got_repository *repo)
10981 const struct got_error *err;
10982 struct got_commit_object *commit;
10983 struct got_object_id *new_commit_id;
10985 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10986 && hle->logmsg == NULL) {
10987 err = histedit_edit_logmsg(hle, repo);
10988 if (err)
10989 return err;
10992 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10993 if (err)
10994 return err;
10996 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10997 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10998 hle->logmsg, repo);
10999 if (err) {
11000 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11001 goto done;
11002 err = show_histedit_progress(commit, hle, NULL);
11003 } else {
11004 err = show_histedit_progress(commit, hle, new_commit_id);
11005 free(new_commit_id);
11007 done:
11008 got_object_commit_close(commit);
11009 return err;
11012 static const struct got_error *
11013 histedit_skip_commit(struct got_histedit_list_entry *hle,
11014 struct got_worktree *worktree, struct got_repository *repo)
11016 const struct got_error *error;
11017 struct got_commit_object *commit;
11019 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11020 repo);
11021 if (error)
11022 return error;
11024 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11025 if (error)
11026 return error;
11028 error = show_histedit_progress(commit, hle, NULL);
11029 got_object_commit_close(commit);
11030 return error;
11033 static const struct got_error *
11034 check_local_changes(void *arg, unsigned char status,
11035 unsigned char staged_status, const char *path,
11036 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11037 struct got_object_id *commit_id, int dirfd, const char *de_name)
11039 int *have_local_changes = arg;
11041 switch (status) {
11042 case GOT_STATUS_ADD:
11043 case GOT_STATUS_DELETE:
11044 case GOT_STATUS_MODIFY:
11045 case GOT_STATUS_CONFLICT:
11046 *have_local_changes = 1;
11047 return got_error(GOT_ERR_CANCELLED);
11048 default:
11049 break;
11052 switch (staged_status) {
11053 case GOT_STATUS_ADD:
11054 case GOT_STATUS_DELETE:
11055 case GOT_STATUS_MODIFY:
11056 *have_local_changes = 1;
11057 return got_error(GOT_ERR_CANCELLED);
11058 default:
11059 break;
11062 return NULL;
11065 static const struct got_error *
11066 cmd_histedit(int argc, char *argv[])
11068 const struct got_error *error = NULL;
11069 struct got_worktree *worktree = NULL;
11070 struct got_fileindex *fileindex = NULL;
11071 struct got_repository *repo = NULL;
11072 char *cwd = NULL;
11073 struct got_reference *branch = NULL;
11074 struct got_reference *tmp_branch = NULL;
11075 struct got_object_id *resume_commit_id = NULL;
11076 struct got_object_id *base_commit_id = NULL;
11077 struct got_object_id *head_commit_id = NULL;
11078 struct got_commit_object *commit = NULL;
11079 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11080 struct got_update_progress_arg upa;
11081 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11082 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11083 int list_backups = 0, delete_backups = 0;
11084 const char *edit_script_path = NULL;
11085 struct got_object_id_queue commits;
11086 struct got_pathlist_head merged_paths;
11087 const struct got_object_id_queue *parent_ids;
11088 struct got_object_qid *pid;
11089 struct got_histedit_list histedit_cmds;
11090 struct got_histedit_list_entry *hle;
11091 int *pack_fds = NULL;
11093 STAILQ_INIT(&commits);
11094 TAILQ_INIT(&histedit_cmds);
11095 TAILQ_INIT(&merged_paths);
11096 memset(&upa, 0, sizeof(upa));
11098 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11099 switch (ch) {
11100 case 'a':
11101 abort_edit = 1;
11102 break;
11103 case 'c':
11104 continue_edit = 1;
11105 break;
11106 case 'e':
11107 edit_only = 1;
11108 break;
11109 case 'f':
11110 fold_only = 1;
11111 break;
11112 case 'F':
11113 edit_script_path = optarg;
11114 break;
11115 case 'm':
11116 edit_logmsg_only = 1;
11117 break;
11118 case 'l':
11119 list_backups = 1;
11120 break;
11121 case 'X':
11122 delete_backups = 1;
11123 break;
11124 default:
11125 usage_histedit();
11126 /* NOTREACHED */
11130 argc -= optind;
11131 argv += optind;
11133 #ifndef PROFILE
11134 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11135 "unveil", NULL) == -1)
11136 err(1, "pledge");
11137 #endif
11138 if (abort_edit && continue_edit)
11139 option_conflict('a', 'c');
11140 if (edit_script_path && edit_logmsg_only)
11141 option_conflict('F', 'm');
11142 if (abort_edit && edit_logmsg_only)
11143 option_conflict('a', 'm');
11144 if (continue_edit && edit_logmsg_only)
11145 option_conflict('c', 'm');
11146 if (abort_edit && fold_only)
11147 option_conflict('a', 'f');
11148 if (continue_edit && fold_only)
11149 option_conflict('c', 'f');
11150 if (fold_only && edit_logmsg_only)
11151 option_conflict('f', 'm');
11152 if (edit_script_path && fold_only)
11153 option_conflict('F', 'f');
11154 if (abort_edit && edit_only)
11155 option_conflict('a', 'e');
11156 if (continue_edit && edit_only)
11157 option_conflict('c', 'e');
11158 if (edit_only && edit_logmsg_only)
11159 option_conflict('e', 'm');
11160 if (edit_script_path && edit_only)
11161 option_conflict('F', 'e');
11162 if (list_backups) {
11163 if (abort_edit)
11164 option_conflict('l', 'a');
11165 if (continue_edit)
11166 option_conflict('l', 'c');
11167 if (edit_script_path)
11168 option_conflict('l', 'F');
11169 if (edit_logmsg_only)
11170 option_conflict('l', 'm');
11171 if (fold_only)
11172 option_conflict('l', 'f');
11173 if (edit_only)
11174 option_conflict('l', 'e');
11175 if (delete_backups)
11176 option_conflict('l', 'X');
11177 if (argc != 0 && argc != 1)
11178 usage_histedit();
11179 } else if (delete_backups) {
11180 if (abort_edit)
11181 option_conflict('X', 'a');
11182 if (continue_edit)
11183 option_conflict('X', 'c');
11184 if (edit_script_path)
11185 option_conflict('X', 'F');
11186 if (edit_logmsg_only)
11187 option_conflict('X', 'm');
11188 if (fold_only)
11189 option_conflict('X', 'f');
11190 if (edit_only)
11191 option_conflict('X', 'e');
11192 if (list_backups)
11193 option_conflict('X', 'l');
11194 if (argc != 0 && argc != 1)
11195 usage_histedit();
11196 } else if (argc != 0)
11197 usage_histedit();
11200 * This command cannot apply unveil(2) in all cases because the
11201 * user may choose to run an editor to edit the histedit script
11202 * and to edit individual commit log messages.
11203 * unveil(2) traverses exec(2); if an editor is used we have to
11204 * apply unveil after edit script and log messages have been written.
11205 * XXX TODO: Make use of unveil(2) where possible.
11208 cwd = getcwd(NULL, 0);
11209 if (cwd == NULL) {
11210 error = got_error_from_errno("getcwd");
11211 goto done;
11214 error = got_repo_pack_fds_open(&pack_fds);
11215 if (error != NULL)
11216 goto done;
11218 error = got_worktree_open(&worktree, cwd);
11219 if (error) {
11220 if (list_backups || delete_backups) {
11221 if (error->code != GOT_ERR_NOT_WORKTREE)
11222 goto done;
11223 } else {
11224 if (error->code == GOT_ERR_NOT_WORKTREE)
11225 error = wrap_not_worktree_error(error,
11226 "histedit", cwd);
11227 goto done;
11231 if (list_backups || delete_backups) {
11232 error = got_repo_open(&repo,
11233 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11234 NULL, pack_fds);
11235 if (error != NULL)
11236 goto done;
11237 error = apply_unveil(got_repo_get_path(repo), 0,
11238 worktree ? got_worktree_get_root_path(worktree) : NULL);
11239 if (error)
11240 goto done;
11241 error = process_backup_refs(
11242 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11243 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11244 goto done; /* nothing else to do */
11247 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11248 NULL, pack_fds);
11249 if (error != NULL)
11250 goto done;
11252 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11253 if (error)
11254 goto done;
11255 if (rebase_in_progress) {
11256 error = got_error(GOT_ERR_REBASING);
11257 goto done;
11260 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11261 repo);
11262 if (error)
11263 goto done;
11264 if (merge_in_progress) {
11265 error = got_error(GOT_ERR_MERGE_BUSY);
11266 goto done;
11269 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11270 if (error)
11271 goto done;
11273 if (edit_in_progress && edit_logmsg_only) {
11274 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11275 "histedit operation is in progress in this "
11276 "work tree and must be continued or aborted "
11277 "before the -m option can be used");
11278 goto done;
11280 if (edit_in_progress && fold_only) {
11281 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11282 "histedit operation is in progress in this "
11283 "work tree and must be continued or aborted "
11284 "before the -f option can be used");
11285 goto done;
11287 if (edit_in_progress && edit_only) {
11288 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11289 "histedit operation is in progress in this "
11290 "work tree and must be continued or aborted "
11291 "before the -e option can be used");
11292 goto done;
11295 if (edit_in_progress && abort_edit) {
11296 error = got_worktree_histedit_continue(&resume_commit_id,
11297 &tmp_branch, &branch, &base_commit_id, &fileindex,
11298 worktree, repo);
11299 if (error)
11300 goto done;
11301 printf("Switching work tree to %s\n",
11302 got_ref_get_symref_target(branch));
11303 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11304 branch, base_commit_id, abort_progress, &upa);
11305 if (error)
11306 goto done;
11307 printf("Histedit of %s aborted\n",
11308 got_ref_get_symref_target(branch));
11309 print_merge_progress_stats(&upa);
11310 goto done; /* nothing else to do */
11311 } else if (abort_edit) {
11312 error = got_error(GOT_ERR_NOT_HISTEDIT);
11313 goto done;
11316 if (continue_edit) {
11317 char *path;
11319 if (!edit_in_progress) {
11320 error = got_error(GOT_ERR_NOT_HISTEDIT);
11321 goto done;
11324 error = got_worktree_get_histedit_script_path(&path, worktree);
11325 if (error)
11326 goto done;
11328 error = histedit_load_list(&histedit_cmds, path, repo);
11329 free(path);
11330 if (error)
11331 goto done;
11333 error = got_worktree_histedit_continue(&resume_commit_id,
11334 &tmp_branch, &branch, &base_commit_id, &fileindex,
11335 worktree, repo);
11336 if (error)
11337 goto done;
11339 error = got_ref_resolve(&head_commit_id, repo, branch);
11340 if (error)
11341 goto done;
11343 error = got_object_open_as_commit(&commit, repo,
11344 head_commit_id);
11345 if (error)
11346 goto done;
11347 parent_ids = got_object_commit_get_parent_ids(commit);
11348 pid = STAILQ_FIRST(parent_ids);
11349 if (pid == NULL) {
11350 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11351 goto done;
11353 error = collect_commits(&commits, head_commit_id, &pid->id,
11354 base_commit_id, got_worktree_get_path_prefix(worktree),
11355 GOT_ERR_HISTEDIT_PATH, repo);
11356 got_object_commit_close(commit);
11357 commit = NULL;
11358 if (error)
11359 goto done;
11360 } else {
11361 if (edit_in_progress) {
11362 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11363 goto done;
11366 error = got_ref_open(&branch, repo,
11367 got_worktree_get_head_ref_name(worktree), 0);
11368 if (error != NULL)
11369 goto done;
11371 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11372 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11373 "will not edit commit history of a branch outside "
11374 "the \"refs/heads/\" reference namespace");
11375 goto done;
11378 error = got_ref_resolve(&head_commit_id, repo, branch);
11379 got_ref_close(branch);
11380 branch = NULL;
11381 if (error)
11382 goto done;
11384 error = got_object_open_as_commit(&commit, repo,
11385 head_commit_id);
11386 if (error)
11387 goto done;
11388 parent_ids = got_object_commit_get_parent_ids(commit);
11389 pid = STAILQ_FIRST(parent_ids);
11390 if (pid == NULL) {
11391 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11392 goto done;
11394 error = collect_commits(&commits, head_commit_id, &pid->id,
11395 got_worktree_get_base_commit_id(worktree),
11396 got_worktree_get_path_prefix(worktree),
11397 GOT_ERR_HISTEDIT_PATH, repo);
11398 got_object_commit_close(commit);
11399 commit = NULL;
11400 if (error)
11401 goto done;
11403 if (STAILQ_EMPTY(&commits)) {
11404 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11405 goto done;
11408 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11409 &base_commit_id, &fileindex, worktree, repo);
11410 if (error)
11411 goto done;
11413 if (edit_script_path) {
11414 error = histedit_load_list(&histedit_cmds,
11415 edit_script_path, repo);
11416 if (error) {
11417 got_worktree_histedit_abort(worktree, fileindex,
11418 repo, branch, base_commit_id,
11419 abort_progress, &upa);
11420 print_merge_progress_stats(&upa);
11421 goto done;
11423 } else {
11424 const char *branch_name;
11425 branch_name = got_ref_get_symref_target(branch);
11426 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11427 branch_name += 11;
11428 error = histedit_edit_script(&histedit_cmds, &commits,
11429 branch_name, edit_logmsg_only, fold_only,
11430 edit_only, repo);
11431 if (error) {
11432 got_worktree_histedit_abort(worktree, fileindex,
11433 repo, branch, base_commit_id,
11434 abort_progress, &upa);
11435 print_merge_progress_stats(&upa);
11436 goto done;
11441 error = histedit_save_list(&histedit_cmds, worktree,
11442 repo);
11443 if (error) {
11444 got_worktree_histedit_abort(worktree, fileindex,
11445 repo, branch, base_commit_id,
11446 abort_progress, &upa);
11447 print_merge_progress_stats(&upa);
11448 goto done;
11453 error = histedit_check_script(&histedit_cmds, &commits, repo);
11454 if (error)
11455 goto done;
11457 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11458 if (resume_commit_id) {
11459 if (got_object_id_cmp(hle->commit_id,
11460 resume_commit_id) != 0)
11461 continue;
11463 resume_commit_id = NULL;
11464 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11465 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11466 error = histedit_skip_commit(hle, worktree,
11467 repo);
11468 if (error)
11469 goto done;
11470 } else {
11471 struct got_pathlist_head paths;
11472 int have_changes = 0;
11474 TAILQ_INIT(&paths);
11475 error = got_pathlist_append(&paths, "", NULL);
11476 if (error)
11477 goto done;
11478 error = got_worktree_status(worktree, &paths,
11479 repo, 0, check_local_changes, &have_changes,
11480 check_cancelled, NULL);
11481 got_pathlist_free(&paths);
11482 if (error) {
11483 if (error->code != GOT_ERR_CANCELLED)
11484 goto done;
11485 if (sigint_received || sigpipe_received)
11486 goto done;
11488 if (have_changes) {
11489 error = histedit_commit(NULL, worktree,
11490 fileindex, tmp_branch, hle, repo);
11491 if (error)
11492 goto done;
11493 } else {
11494 error = got_object_open_as_commit(
11495 &commit, repo, hle->commit_id);
11496 if (error)
11497 goto done;
11498 error = show_histedit_progress(commit,
11499 hle, NULL);
11500 got_object_commit_close(commit);
11501 commit = NULL;
11502 if (error)
11503 goto done;
11506 continue;
11509 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11510 error = histedit_skip_commit(hle, worktree, repo);
11511 if (error)
11512 goto done;
11513 continue;
11516 error = got_object_open_as_commit(&commit, repo,
11517 hle->commit_id);
11518 if (error)
11519 goto done;
11520 parent_ids = got_object_commit_get_parent_ids(commit);
11521 pid = STAILQ_FIRST(parent_ids);
11523 error = got_worktree_histedit_merge_files(&merged_paths,
11524 worktree, fileindex, &pid->id, hle->commit_id, repo,
11525 update_progress, &upa, check_cancelled, NULL);
11526 if (error)
11527 goto done;
11528 got_object_commit_close(commit);
11529 commit = NULL;
11531 print_merge_progress_stats(&upa);
11532 if (upa.conflicts > 0 || upa.missing > 0 ||
11533 upa.not_deleted > 0 || upa.unversioned > 0) {
11534 if (upa.conflicts > 0) {
11535 error = show_rebase_merge_conflict(
11536 hle->commit_id, repo);
11537 if (error)
11538 goto done;
11540 got_worktree_rebase_pathlist_free(&merged_paths);
11541 break;
11544 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11545 char *id_str;
11546 error = got_object_id_str(&id_str, hle->commit_id);
11547 if (error)
11548 goto done;
11549 printf("Stopping histedit for amending commit %s\n",
11550 id_str);
11551 free(id_str);
11552 got_worktree_rebase_pathlist_free(&merged_paths);
11553 error = got_worktree_histedit_postpone(worktree,
11554 fileindex);
11555 goto done;
11558 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11559 error = histedit_skip_commit(hle, worktree, repo);
11560 if (error)
11561 goto done;
11562 continue;
11565 error = histedit_commit(&merged_paths, worktree, fileindex,
11566 tmp_branch, hle, repo);
11567 got_worktree_rebase_pathlist_free(&merged_paths);
11568 if (error)
11569 goto done;
11572 if (upa.conflicts > 0 || upa.missing > 0 ||
11573 upa.not_deleted > 0 || upa.unversioned > 0) {
11574 error = got_worktree_histedit_postpone(worktree, fileindex);
11575 if (error)
11576 goto done;
11577 if (upa.conflicts > 0 && upa.missing == 0 &&
11578 upa.not_deleted == 0 && upa.unversioned == 0) {
11579 error = got_error_msg(GOT_ERR_CONFLICTS,
11580 "conflicts must be resolved before histedit "
11581 "can continue");
11582 } else if (upa.conflicts > 0) {
11583 error = got_error_msg(GOT_ERR_CONFLICTS,
11584 "conflicts must be resolved before histedit "
11585 "can continue; changes destined for some "
11586 "files were not yet merged and should be "
11587 "merged manually if required before the "
11588 "histedit operation is continued");
11589 } else {
11590 error = got_error_msg(GOT_ERR_CONFLICTS,
11591 "changes destined for some files were not "
11592 "yet merged and should be merged manually "
11593 "if required before the histedit operation "
11594 "is continued");
11596 } else
11597 error = histedit_complete(worktree, fileindex, tmp_branch,
11598 branch, repo);
11599 done:
11600 got_object_id_queue_free(&commits);
11601 histedit_free_list(&histedit_cmds);
11602 free(head_commit_id);
11603 free(base_commit_id);
11604 free(resume_commit_id);
11605 if (commit)
11606 got_object_commit_close(commit);
11607 if (branch)
11608 got_ref_close(branch);
11609 if (tmp_branch)
11610 got_ref_close(tmp_branch);
11611 if (worktree)
11612 got_worktree_close(worktree);
11613 if (repo) {
11614 const struct got_error *close_err = got_repo_close(repo);
11615 if (error == NULL)
11616 error = close_err;
11618 if (pack_fds) {
11619 const struct got_error *pack_err =
11620 got_repo_pack_fds_close(pack_fds);
11621 if (error == NULL)
11622 error = pack_err;
11624 return error;
11627 __dead static void
11628 usage_integrate(void)
11630 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11631 exit(1);
11634 static const struct got_error *
11635 cmd_integrate(int argc, char *argv[])
11637 const struct got_error *error = NULL;
11638 struct got_repository *repo = NULL;
11639 struct got_worktree *worktree = NULL;
11640 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11641 const char *branch_arg = NULL;
11642 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11643 struct got_fileindex *fileindex = NULL;
11644 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11645 int ch;
11646 struct got_update_progress_arg upa;
11647 int *pack_fds = NULL;
11649 while ((ch = getopt(argc, argv, "")) != -1) {
11650 switch (ch) {
11651 default:
11652 usage_integrate();
11653 /* NOTREACHED */
11657 argc -= optind;
11658 argv += optind;
11660 if (argc != 1)
11661 usage_integrate();
11662 branch_arg = argv[0];
11663 #ifndef PROFILE
11664 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11665 "unveil", NULL) == -1)
11666 err(1, "pledge");
11667 #endif
11668 cwd = getcwd(NULL, 0);
11669 if (cwd == NULL) {
11670 error = got_error_from_errno("getcwd");
11671 goto done;
11674 error = got_repo_pack_fds_open(&pack_fds);
11675 if (error != NULL)
11676 goto done;
11678 error = got_worktree_open(&worktree, cwd);
11679 if (error) {
11680 if (error->code == GOT_ERR_NOT_WORKTREE)
11681 error = wrap_not_worktree_error(error, "integrate",
11682 cwd);
11683 goto done;
11686 error = check_rebase_or_histedit_in_progress(worktree);
11687 if (error)
11688 goto done;
11690 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11691 NULL, pack_fds);
11692 if (error != NULL)
11693 goto done;
11695 error = apply_unveil(got_repo_get_path(repo), 0,
11696 got_worktree_get_root_path(worktree));
11697 if (error)
11698 goto done;
11700 error = check_merge_in_progress(worktree, repo);
11701 if (error)
11702 goto done;
11704 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11705 error = got_error_from_errno("asprintf");
11706 goto done;
11709 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11710 &base_branch_ref, worktree, refname, repo);
11711 if (error)
11712 goto done;
11714 refname = strdup(got_ref_get_name(branch_ref));
11715 if (refname == NULL) {
11716 error = got_error_from_errno("strdup");
11717 got_worktree_integrate_abort(worktree, fileindex, repo,
11718 branch_ref, base_branch_ref);
11719 goto done;
11721 base_refname = strdup(got_ref_get_name(base_branch_ref));
11722 if (base_refname == NULL) {
11723 error = got_error_from_errno("strdup");
11724 got_worktree_integrate_abort(worktree, fileindex, repo,
11725 branch_ref, base_branch_ref);
11726 goto done;
11729 error = got_ref_resolve(&commit_id, repo, branch_ref);
11730 if (error)
11731 goto done;
11733 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11734 if (error)
11735 goto done;
11737 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11738 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11739 "specified branch has already been integrated");
11740 got_worktree_integrate_abort(worktree, fileindex, repo,
11741 branch_ref, base_branch_ref);
11742 goto done;
11745 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11746 if (error) {
11747 if (error->code == GOT_ERR_ANCESTRY)
11748 error = got_error(GOT_ERR_REBASE_REQUIRED);
11749 got_worktree_integrate_abort(worktree, fileindex, repo,
11750 branch_ref, base_branch_ref);
11751 goto done;
11754 memset(&upa, 0, sizeof(upa));
11755 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11756 branch_ref, base_branch_ref, update_progress, &upa,
11757 check_cancelled, NULL);
11758 if (error)
11759 goto done;
11761 printf("Integrated %s into %s\n", refname, base_refname);
11762 print_update_progress_stats(&upa);
11763 done:
11764 if (repo) {
11765 const struct got_error *close_err = got_repo_close(repo);
11766 if (error == NULL)
11767 error = close_err;
11769 if (worktree)
11770 got_worktree_close(worktree);
11771 if (pack_fds) {
11772 const struct got_error *pack_err =
11773 got_repo_pack_fds_close(pack_fds);
11774 if (error == NULL)
11775 error = pack_err;
11777 free(cwd);
11778 free(base_commit_id);
11779 free(commit_id);
11780 free(refname);
11781 free(base_refname);
11782 return error;
11785 __dead static void
11786 usage_merge(void)
11788 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11789 getprogname());
11790 exit(1);
11793 static const struct got_error *
11794 cmd_merge(int argc, char *argv[])
11796 const struct got_error *error = NULL;
11797 struct got_worktree *worktree = NULL;
11798 struct got_repository *repo = NULL;
11799 struct got_fileindex *fileindex = NULL;
11800 char *cwd = NULL, *id_str = NULL, *author = NULL;
11801 struct got_reference *branch = NULL, *wt_branch = NULL;
11802 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11803 struct got_object_id *wt_branch_tip = NULL;
11804 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11805 int interrupt_merge = 0;
11806 struct got_update_progress_arg upa;
11807 struct got_object_id *merge_commit_id = NULL;
11808 char *branch_name = NULL;
11809 int *pack_fds = NULL;
11811 memset(&upa, 0, sizeof(upa));
11813 while ((ch = getopt(argc, argv, "acn")) != -1) {
11814 switch (ch) {
11815 case 'a':
11816 abort_merge = 1;
11817 break;
11818 case 'c':
11819 continue_merge = 1;
11820 break;
11821 case 'n':
11822 interrupt_merge = 1;
11823 break;
11824 default:
11825 usage_rebase();
11826 /* NOTREACHED */
11830 argc -= optind;
11831 argv += optind;
11833 #ifndef PROFILE
11834 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11835 "unveil", NULL) == -1)
11836 err(1, "pledge");
11837 #endif
11839 if (abort_merge && continue_merge)
11840 option_conflict('a', 'c');
11841 if (abort_merge || continue_merge) {
11842 if (argc != 0)
11843 usage_merge();
11844 } else if (argc != 1)
11845 usage_merge();
11847 cwd = getcwd(NULL, 0);
11848 if (cwd == NULL) {
11849 error = got_error_from_errno("getcwd");
11850 goto done;
11853 error = got_repo_pack_fds_open(&pack_fds);
11854 if (error != NULL)
11855 goto done;
11857 error = got_worktree_open(&worktree, cwd);
11858 if (error) {
11859 if (error->code == GOT_ERR_NOT_WORKTREE)
11860 error = wrap_not_worktree_error(error,
11861 "merge", cwd);
11862 goto done;
11865 error = got_repo_open(&repo,
11866 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11867 pack_fds);
11868 if (error != NULL)
11869 goto done;
11871 error = apply_unveil(got_repo_get_path(repo), 0,
11872 worktree ? got_worktree_get_root_path(worktree) : NULL);
11873 if (error)
11874 goto done;
11876 error = check_rebase_or_histedit_in_progress(worktree);
11877 if (error)
11878 goto done;
11880 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11881 repo);
11882 if (error)
11883 goto done;
11885 if (abort_merge) {
11886 if (!merge_in_progress) {
11887 error = got_error(GOT_ERR_NOT_MERGING);
11888 goto done;
11890 error = got_worktree_merge_continue(&branch_name,
11891 &branch_tip, &fileindex, worktree, repo);
11892 if (error)
11893 goto done;
11894 error = got_worktree_merge_abort(worktree, fileindex, repo,
11895 abort_progress, &upa);
11896 if (error)
11897 goto done;
11898 printf("Merge of %s aborted\n", branch_name);
11899 goto done; /* nothing else to do */
11902 error = get_author(&author, repo, worktree);
11903 if (error)
11904 goto done;
11906 if (continue_merge) {
11907 if (!merge_in_progress) {
11908 error = got_error(GOT_ERR_NOT_MERGING);
11909 goto done;
11911 error = got_worktree_merge_continue(&branch_name,
11912 &branch_tip, &fileindex, worktree, repo);
11913 if (error)
11914 goto done;
11915 } else {
11916 error = got_ref_open(&branch, repo, argv[0], 0);
11917 if (error != NULL)
11918 goto done;
11919 branch_name = strdup(got_ref_get_name(branch));
11920 if (branch_name == NULL) {
11921 error = got_error_from_errno("strdup");
11922 goto done;
11924 error = got_ref_resolve(&branch_tip, repo, branch);
11925 if (error)
11926 goto done;
11929 error = got_ref_open(&wt_branch, repo,
11930 got_worktree_get_head_ref_name(worktree), 0);
11931 if (error)
11932 goto done;
11933 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11934 if (error)
11935 goto done;
11936 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11937 wt_branch_tip, branch_tip, 0, repo,
11938 check_cancelled, NULL);
11939 if (error && error->code != GOT_ERR_ANCESTRY)
11940 goto done;
11942 if (!continue_merge) {
11943 error = check_path_prefix(wt_branch_tip, branch_tip,
11944 got_worktree_get_path_prefix(worktree),
11945 GOT_ERR_MERGE_PATH, repo);
11946 if (error)
11947 goto done;
11948 if (yca_id) {
11949 error = check_same_branch(wt_branch_tip, branch,
11950 yca_id, repo);
11951 if (error) {
11952 if (error->code != GOT_ERR_ANCESTRY)
11953 goto done;
11954 error = NULL;
11955 } else {
11956 static char msg[512];
11957 snprintf(msg, sizeof(msg),
11958 "cannot create a merge commit because "
11959 "%s is based on %s; %s can be integrated "
11960 "with 'got integrate' instead", branch_name,
11961 got_worktree_get_head_ref_name(worktree),
11962 branch_name);
11963 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11964 goto done;
11967 error = got_worktree_merge_prepare(&fileindex, worktree,
11968 branch, repo);
11969 if (error)
11970 goto done;
11972 error = got_worktree_merge_branch(worktree, fileindex,
11973 yca_id, branch_tip, repo, update_progress, &upa,
11974 check_cancelled, NULL);
11975 if (error)
11976 goto done;
11977 print_merge_progress_stats(&upa);
11978 if (!upa.did_something) {
11979 error = got_worktree_merge_abort(worktree, fileindex,
11980 repo, abort_progress, &upa);
11981 if (error)
11982 goto done;
11983 printf("Already up-to-date\n");
11984 goto done;
11988 if (interrupt_merge) {
11989 error = got_worktree_merge_postpone(worktree, fileindex);
11990 if (error)
11991 goto done;
11992 printf("Merge of %s interrupted on request\n", branch_name);
11993 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11994 upa.not_deleted > 0 || upa.unversioned > 0) {
11995 error = got_worktree_merge_postpone(worktree, fileindex);
11996 if (error)
11997 goto done;
11998 if (upa.conflicts > 0 && upa.missing == 0 &&
11999 upa.not_deleted == 0 && upa.unversioned == 0) {
12000 error = got_error_msg(GOT_ERR_CONFLICTS,
12001 "conflicts must be resolved before merging "
12002 "can continue");
12003 } else if (upa.conflicts > 0) {
12004 error = got_error_msg(GOT_ERR_CONFLICTS,
12005 "conflicts must be resolved before merging "
12006 "can continue; changes destined for some "
12007 "files were not yet merged and "
12008 "should be merged manually if required before the "
12009 "merge operation is continued");
12010 } else {
12011 error = got_error_msg(GOT_ERR_CONFLICTS,
12012 "changes destined for some "
12013 "files were not yet merged and should be "
12014 "merged manually if required before the "
12015 "merge operation is continued");
12017 goto done;
12018 } else {
12019 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12020 fileindex, author, NULL, 1, branch_tip, branch_name,
12021 repo, continue_merge ? print_status : NULL, NULL);
12022 if (error)
12023 goto done;
12024 error = got_worktree_merge_complete(worktree, fileindex, repo);
12025 if (error)
12026 goto done;
12027 error = got_object_id_str(&id_str, merge_commit_id);
12028 if (error)
12029 goto done;
12030 printf("Merged %s into %s: %s\n", branch_name,
12031 got_worktree_get_head_ref_name(worktree),
12032 id_str);
12035 done:
12036 free(id_str);
12037 free(merge_commit_id);
12038 free(author);
12039 free(branch_tip);
12040 free(branch_name);
12041 free(yca_id);
12042 if (branch)
12043 got_ref_close(branch);
12044 if (wt_branch)
12045 got_ref_close(wt_branch);
12046 if (worktree)
12047 got_worktree_close(worktree);
12048 if (repo) {
12049 const struct got_error *close_err = got_repo_close(repo);
12050 if (error == NULL)
12051 error = close_err;
12053 if (pack_fds) {
12054 const struct got_error *pack_err =
12055 got_repo_pack_fds_close(pack_fds);
12056 if (error == NULL)
12057 error = pack_err;
12059 return error;
12062 __dead static void
12063 usage_stage(void)
12065 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12066 "[-S] [file-path ...]\n",
12067 getprogname());
12068 exit(1);
12071 static const struct got_error *
12072 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12073 const char *path, struct got_object_id *blob_id,
12074 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12075 int dirfd, const char *de_name)
12077 const struct got_error *err = NULL;
12078 char *id_str = NULL;
12080 if (staged_status != GOT_STATUS_ADD &&
12081 staged_status != GOT_STATUS_MODIFY &&
12082 staged_status != GOT_STATUS_DELETE)
12083 return NULL;
12085 if (staged_status == GOT_STATUS_ADD ||
12086 staged_status == GOT_STATUS_MODIFY)
12087 err = got_object_id_str(&id_str, staged_blob_id);
12088 else
12089 err = got_object_id_str(&id_str, blob_id);
12090 if (err)
12091 return err;
12093 printf("%s %c %s\n", id_str, staged_status, path);
12094 free(id_str);
12095 return NULL;
12098 static const struct got_error *
12099 cmd_stage(int argc, char *argv[])
12101 const struct got_error *error = NULL;
12102 struct got_repository *repo = NULL;
12103 struct got_worktree *worktree = NULL;
12104 char *cwd = NULL;
12105 struct got_pathlist_head paths;
12106 struct got_pathlist_entry *pe;
12107 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12108 FILE *patch_script_file = NULL;
12109 const char *patch_script_path = NULL;
12110 struct choose_patch_arg cpa;
12111 int *pack_fds = NULL;
12113 TAILQ_INIT(&paths);
12115 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12116 switch (ch) {
12117 case 'l':
12118 list_stage = 1;
12119 break;
12120 case 'p':
12121 pflag = 1;
12122 break;
12123 case 'F':
12124 patch_script_path = optarg;
12125 break;
12126 case 'S':
12127 allow_bad_symlinks = 1;
12128 break;
12129 default:
12130 usage_stage();
12131 /* NOTREACHED */
12135 argc -= optind;
12136 argv += optind;
12138 #ifndef PROFILE
12139 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12140 "unveil", NULL) == -1)
12141 err(1, "pledge");
12142 #endif
12143 if (list_stage && (pflag || patch_script_path))
12144 errx(1, "-l option cannot be used with other options");
12145 if (patch_script_path && !pflag)
12146 errx(1, "-F option can only be used together with -p option");
12148 cwd = getcwd(NULL, 0);
12149 if (cwd == NULL) {
12150 error = got_error_from_errno("getcwd");
12151 goto done;
12154 error = got_repo_pack_fds_open(&pack_fds);
12155 if (error != NULL)
12156 goto done;
12158 error = got_worktree_open(&worktree, cwd);
12159 if (error) {
12160 if (error->code == GOT_ERR_NOT_WORKTREE)
12161 error = wrap_not_worktree_error(error, "stage", cwd);
12162 goto done;
12165 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12166 NULL, pack_fds);
12167 if (error != NULL)
12168 goto done;
12170 if (patch_script_path) {
12171 patch_script_file = fopen(patch_script_path, "re");
12172 if (patch_script_file == NULL) {
12173 error = got_error_from_errno2("fopen",
12174 patch_script_path);
12175 goto done;
12178 error = apply_unveil(got_repo_get_path(repo), 0,
12179 got_worktree_get_root_path(worktree));
12180 if (error)
12181 goto done;
12183 error = check_merge_in_progress(worktree, repo);
12184 if (error)
12185 goto done;
12187 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12188 if (error)
12189 goto done;
12191 if (list_stage)
12192 error = got_worktree_status(worktree, &paths, repo, 0,
12193 print_stage, NULL, check_cancelled, NULL);
12194 else {
12195 cpa.patch_script_file = patch_script_file;
12196 cpa.action = "stage";
12197 error = got_worktree_stage(worktree, &paths,
12198 pflag ? NULL : print_status, NULL,
12199 pflag ? choose_patch : NULL, &cpa,
12200 allow_bad_symlinks, repo);
12202 done:
12203 if (patch_script_file && fclose(patch_script_file) == EOF &&
12204 error == NULL)
12205 error = got_error_from_errno2("fclose", patch_script_path);
12206 if (repo) {
12207 const struct got_error *close_err = got_repo_close(repo);
12208 if (error == NULL)
12209 error = close_err;
12211 if (worktree)
12212 got_worktree_close(worktree);
12213 if (pack_fds) {
12214 const struct got_error *pack_err =
12215 got_repo_pack_fds_close(pack_fds);
12216 if (error == NULL)
12217 error = pack_err;
12219 TAILQ_FOREACH(pe, &paths, entry)
12220 free((char *)pe->path);
12221 got_pathlist_free(&paths);
12222 free(cwd);
12223 return error;
12226 __dead static void
12227 usage_unstage(void)
12229 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12230 "[file-path ...]\n",
12231 getprogname());
12232 exit(1);
12236 static const struct got_error *
12237 cmd_unstage(int argc, char *argv[])
12239 const struct got_error *error = NULL;
12240 struct got_repository *repo = NULL;
12241 struct got_worktree *worktree = NULL;
12242 char *cwd = NULL;
12243 struct got_pathlist_head paths;
12244 struct got_pathlist_entry *pe;
12245 int ch, pflag = 0;
12246 struct got_update_progress_arg upa;
12247 FILE *patch_script_file = NULL;
12248 const char *patch_script_path = NULL;
12249 struct choose_patch_arg cpa;
12250 int *pack_fds = NULL;
12252 TAILQ_INIT(&paths);
12254 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12255 switch (ch) {
12256 case 'p':
12257 pflag = 1;
12258 break;
12259 case 'F':
12260 patch_script_path = optarg;
12261 break;
12262 default:
12263 usage_unstage();
12264 /* NOTREACHED */
12268 argc -= optind;
12269 argv += optind;
12271 #ifndef PROFILE
12272 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12273 "unveil", NULL) == -1)
12274 err(1, "pledge");
12275 #endif
12276 if (patch_script_path && !pflag)
12277 errx(1, "-F option can only be used together with -p option");
12279 cwd = getcwd(NULL, 0);
12280 if (cwd == NULL) {
12281 error = got_error_from_errno("getcwd");
12282 goto done;
12285 error = got_repo_pack_fds_open(&pack_fds);
12286 if (error != NULL)
12287 goto done;
12289 error = got_worktree_open(&worktree, cwd);
12290 if (error) {
12291 if (error->code == GOT_ERR_NOT_WORKTREE)
12292 error = wrap_not_worktree_error(error, "unstage", cwd);
12293 goto done;
12296 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12297 NULL, pack_fds);
12298 if (error != NULL)
12299 goto done;
12301 if (patch_script_path) {
12302 patch_script_file = fopen(patch_script_path, "re");
12303 if (patch_script_file == NULL) {
12304 error = got_error_from_errno2("fopen",
12305 patch_script_path);
12306 goto done;
12310 error = apply_unveil(got_repo_get_path(repo), 0,
12311 got_worktree_get_root_path(worktree));
12312 if (error)
12313 goto done;
12315 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12316 if (error)
12317 goto done;
12319 cpa.patch_script_file = patch_script_file;
12320 cpa.action = "unstage";
12321 memset(&upa, 0, sizeof(upa));
12322 error = got_worktree_unstage(worktree, &paths, update_progress,
12323 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12324 if (!error)
12325 print_merge_progress_stats(&upa);
12326 done:
12327 if (patch_script_file && fclose(patch_script_file) == EOF &&
12328 error == NULL)
12329 error = got_error_from_errno2("fclose", patch_script_path);
12330 if (repo) {
12331 const struct got_error *close_err = got_repo_close(repo);
12332 if (error == NULL)
12333 error = close_err;
12335 if (worktree)
12336 got_worktree_close(worktree);
12337 if (pack_fds) {
12338 const struct got_error *pack_err =
12339 got_repo_pack_fds_close(pack_fds);
12340 if (error == NULL)
12341 error = pack_err;
12343 TAILQ_FOREACH(pe, &paths, entry)
12344 free((char *)pe->path);
12345 got_pathlist_free(&paths);
12346 free(cwd);
12347 return error;
12350 __dead static void
12351 usage_cat(void)
12353 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12354 "arg1 [arg2 ...]\n", getprogname());
12355 exit(1);
12358 static const struct got_error *
12359 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12361 const struct got_error *err;
12362 struct got_blob_object *blob;
12363 int fd = -1;
12365 fd = got_opentempfd();
12366 if (fd == -1)
12367 return got_error_from_errno("got_opentempfd");
12369 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12370 if (err)
12371 goto done;
12373 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12374 done:
12375 if (fd != -1 && close(fd) == -1 && err == NULL)
12376 err = got_error_from_errno("close");
12377 if (blob)
12378 got_object_blob_close(blob);
12379 return err;
12382 static const struct got_error *
12383 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12385 const struct got_error *err;
12386 struct got_tree_object *tree;
12387 int nentries, i;
12389 err = got_object_open_as_tree(&tree, repo, id);
12390 if (err)
12391 return err;
12393 nentries = got_object_tree_get_nentries(tree);
12394 for (i = 0; i < nentries; i++) {
12395 struct got_tree_entry *te;
12396 char *id_str;
12397 if (sigint_received || sigpipe_received)
12398 break;
12399 te = got_object_tree_get_entry(tree, i);
12400 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12401 if (err)
12402 break;
12403 fprintf(outfile, "%s %.7o %s\n", id_str,
12404 got_tree_entry_get_mode(te),
12405 got_tree_entry_get_name(te));
12406 free(id_str);
12409 got_object_tree_close(tree);
12410 return err;
12413 static void
12414 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12416 long long h, m;
12417 char sign = '+';
12419 if (gmtoff < 0) {
12420 sign = '-';
12421 gmtoff = -gmtoff;
12424 h = (long long)gmtoff / 3600;
12425 m = ((long long)gmtoff - h*3600) / 60;
12426 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12429 static const struct got_error *
12430 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12432 const struct got_error *err;
12433 struct got_commit_object *commit;
12434 const struct got_object_id_queue *parent_ids;
12435 struct got_object_qid *pid;
12436 char *id_str = NULL;
12437 const char *logmsg = NULL;
12438 char gmtoff[6];
12440 err = got_object_open_as_commit(&commit, repo, id);
12441 if (err)
12442 return err;
12444 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12445 if (err)
12446 goto done;
12448 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12449 parent_ids = got_object_commit_get_parent_ids(commit);
12450 fprintf(outfile, "numparents %d\n",
12451 got_object_commit_get_nparents(commit));
12452 STAILQ_FOREACH(pid, parent_ids, entry) {
12453 char *pid_str;
12454 err = got_object_id_str(&pid_str, &pid->id);
12455 if (err)
12456 goto done;
12457 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12458 free(pid_str);
12460 format_gmtoff(gmtoff, sizeof(gmtoff),
12461 got_object_commit_get_author_gmtoff(commit));
12462 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12463 got_object_commit_get_author(commit),
12464 (long long)got_object_commit_get_author_time(commit),
12465 gmtoff);
12467 format_gmtoff(gmtoff, sizeof(gmtoff),
12468 got_object_commit_get_committer_gmtoff(commit));
12469 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12470 got_object_commit_get_author(commit),
12471 (long long)got_object_commit_get_committer_time(commit),
12472 gmtoff);
12474 logmsg = got_object_commit_get_logmsg_raw(commit);
12475 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12476 fprintf(outfile, "%s", logmsg);
12477 done:
12478 free(id_str);
12479 got_object_commit_close(commit);
12480 return err;
12483 static const struct got_error *
12484 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12486 const struct got_error *err;
12487 struct got_tag_object *tag;
12488 char *id_str = NULL;
12489 const char *tagmsg = NULL;
12490 char gmtoff[6];
12492 err = got_object_open_as_tag(&tag, repo, id);
12493 if (err)
12494 return err;
12496 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12497 if (err)
12498 goto done;
12500 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12502 switch (got_object_tag_get_object_type(tag)) {
12503 case GOT_OBJ_TYPE_BLOB:
12504 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12505 GOT_OBJ_LABEL_BLOB);
12506 break;
12507 case GOT_OBJ_TYPE_TREE:
12508 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12509 GOT_OBJ_LABEL_TREE);
12510 break;
12511 case GOT_OBJ_TYPE_COMMIT:
12512 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12513 GOT_OBJ_LABEL_COMMIT);
12514 break;
12515 case GOT_OBJ_TYPE_TAG:
12516 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12517 GOT_OBJ_LABEL_TAG);
12518 break;
12519 default:
12520 break;
12523 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12524 got_object_tag_get_name(tag));
12526 format_gmtoff(gmtoff, sizeof(gmtoff),
12527 got_object_tag_get_tagger_gmtoff(tag));
12528 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12529 got_object_tag_get_tagger(tag),
12530 (long long)got_object_tag_get_tagger_time(tag),
12531 gmtoff);
12533 tagmsg = got_object_tag_get_message(tag);
12534 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12535 fprintf(outfile, "%s", tagmsg);
12536 done:
12537 free(id_str);
12538 got_object_tag_close(tag);
12539 return err;
12542 static const struct got_error *
12543 cmd_cat(int argc, char *argv[])
12545 const struct got_error *error;
12546 struct got_repository *repo = NULL;
12547 struct got_worktree *worktree = NULL;
12548 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12549 const char *commit_id_str = NULL;
12550 struct got_object_id *id = NULL, *commit_id = NULL;
12551 struct got_commit_object *commit = NULL;
12552 int ch, obj_type, i, force_path = 0;
12553 struct got_reflist_head refs;
12554 int *pack_fds = NULL;
12556 TAILQ_INIT(&refs);
12558 #ifndef PROFILE
12559 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12560 NULL) == -1)
12561 err(1, "pledge");
12562 #endif
12564 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12565 switch (ch) {
12566 case 'c':
12567 commit_id_str = optarg;
12568 break;
12569 case 'r':
12570 repo_path = realpath(optarg, NULL);
12571 if (repo_path == NULL)
12572 return got_error_from_errno2("realpath",
12573 optarg);
12574 got_path_strip_trailing_slashes(repo_path);
12575 break;
12576 case 'P':
12577 force_path = 1;
12578 break;
12579 default:
12580 usage_cat();
12581 /* NOTREACHED */
12585 argc -= optind;
12586 argv += optind;
12588 cwd = getcwd(NULL, 0);
12589 if (cwd == NULL) {
12590 error = got_error_from_errno("getcwd");
12591 goto done;
12594 error = got_repo_pack_fds_open(&pack_fds);
12595 if (error != NULL)
12596 goto done;
12598 if (repo_path == NULL) {
12599 error = got_worktree_open(&worktree, cwd);
12600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12601 goto done;
12602 if (worktree) {
12603 repo_path = strdup(
12604 got_worktree_get_repo_path(worktree));
12605 if (repo_path == NULL) {
12606 error = got_error_from_errno("strdup");
12607 goto done;
12610 /* Release work tree lock. */
12611 got_worktree_close(worktree);
12612 worktree = NULL;
12616 if (repo_path == NULL) {
12617 repo_path = strdup(cwd);
12618 if (repo_path == NULL)
12619 return got_error_from_errno("strdup");
12622 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12623 free(repo_path);
12624 if (error != NULL)
12625 goto done;
12627 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12628 if (error)
12629 goto done;
12631 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12632 if (error)
12633 goto done;
12635 if (commit_id_str == NULL)
12636 commit_id_str = GOT_REF_HEAD;
12637 error = got_repo_match_object_id(&commit_id, NULL,
12638 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12639 if (error)
12640 goto done;
12642 error = got_object_open_as_commit(&commit, repo, commit_id);
12643 if (error)
12644 goto done;
12646 for (i = 0; i < argc; i++) {
12647 if (force_path) {
12648 error = got_object_id_by_path(&id, repo, commit,
12649 argv[i]);
12650 if (error)
12651 break;
12652 } else {
12653 error = got_repo_match_object_id(&id, &label, argv[i],
12654 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12655 repo);
12656 if (error) {
12657 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12658 error->code != GOT_ERR_NOT_REF)
12659 break;
12660 error = got_object_id_by_path(&id, repo,
12661 commit, argv[i]);
12662 if (error)
12663 break;
12667 error = got_object_get_type(&obj_type, repo, id);
12668 if (error)
12669 break;
12671 switch (obj_type) {
12672 case GOT_OBJ_TYPE_BLOB:
12673 error = cat_blob(id, repo, stdout);
12674 break;
12675 case GOT_OBJ_TYPE_TREE:
12676 error = cat_tree(id, repo, stdout);
12677 break;
12678 case GOT_OBJ_TYPE_COMMIT:
12679 error = cat_commit(id, repo, stdout);
12680 break;
12681 case GOT_OBJ_TYPE_TAG:
12682 error = cat_tag(id, repo, stdout);
12683 break;
12684 default:
12685 error = got_error(GOT_ERR_OBJ_TYPE);
12686 break;
12688 if (error)
12689 break;
12690 free(label);
12691 label = NULL;
12692 free(id);
12693 id = NULL;
12695 done:
12696 free(label);
12697 free(id);
12698 free(commit_id);
12699 if (commit)
12700 got_object_commit_close(commit);
12701 if (worktree)
12702 got_worktree_close(worktree);
12703 if (repo) {
12704 const struct got_error *close_err = got_repo_close(repo);
12705 if (error == NULL)
12706 error = close_err;
12708 if (pack_fds) {
12709 const struct got_error *pack_err =
12710 got_repo_pack_fds_close(pack_fds);
12711 if (error == NULL)
12712 error = pack_err;
12715 got_ref_list_free(&refs);
12716 return error;
12719 __dead static void
12720 usage_info(void)
12722 fprintf(stderr, "usage: %s info [path ...]\n",
12723 getprogname());
12724 exit(1);
12727 static const struct got_error *
12728 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12729 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12730 struct got_object_id *commit_id)
12732 const struct got_error *err = NULL;
12733 char *id_str = NULL;
12734 char datebuf[128];
12735 struct tm mytm, *tm;
12736 struct got_pathlist_head *paths = arg;
12737 struct got_pathlist_entry *pe;
12740 * Clear error indication from any of the path arguments which
12741 * would cause this file index entry to be displayed.
12743 TAILQ_FOREACH(pe, paths, entry) {
12744 if (got_path_cmp(path, pe->path, strlen(path),
12745 pe->path_len) == 0 ||
12746 got_path_is_child(path, pe->path, pe->path_len))
12747 pe->data = NULL; /* no error */
12750 printf(GOT_COMMIT_SEP_STR);
12751 if (S_ISLNK(mode))
12752 printf("symlink: %s\n", path);
12753 else if (S_ISREG(mode)) {
12754 printf("file: %s\n", path);
12755 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12756 } else if (S_ISDIR(mode))
12757 printf("directory: %s\n", path);
12758 else
12759 printf("something: %s\n", path);
12761 tm = localtime_r(&mtime, &mytm);
12762 if (tm == NULL)
12763 return NULL;
12764 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12765 return got_error(GOT_ERR_NO_SPACE);
12766 printf("timestamp: %s\n", datebuf);
12768 if (blob_id) {
12769 err = got_object_id_str(&id_str, blob_id);
12770 if (err)
12771 return err;
12772 printf("based on blob: %s\n", id_str);
12773 free(id_str);
12776 if (staged_blob_id) {
12777 err = got_object_id_str(&id_str, staged_blob_id);
12778 if (err)
12779 return err;
12780 printf("based on staged blob: %s\n", id_str);
12781 free(id_str);
12784 if (commit_id) {
12785 err = got_object_id_str(&id_str, commit_id);
12786 if (err)
12787 return err;
12788 printf("based on commit: %s\n", id_str);
12789 free(id_str);
12792 return NULL;
12795 static const struct got_error *
12796 cmd_info(int argc, char *argv[])
12798 const struct got_error *error = NULL;
12799 struct got_worktree *worktree = NULL;
12800 char *cwd = NULL, *id_str = NULL;
12801 struct got_pathlist_head paths;
12802 struct got_pathlist_entry *pe;
12803 char *uuidstr = NULL;
12804 int ch, show_files = 0;
12805 int *pack_fds = NULL;
12807 TAILQ_INIT(&paths);
12809 while ((ch = getopt(argc, argv, "")) != -1) {
12810 switch (ch) {
12811 default:
12812 usage_info();
12813 /* NOTREACHED */
12817 argc -= optind;
12818 argv += optind;
12820 #ifndef PROFILE
12821 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12822 NULL) == -1)
12823 err(1, "pledge");
12824 #endif
12825 cwd = getcwd(NULL, 0);
12826 if (cwd == NULL) {
12827 error = got_error_from_errno("getcwd");
12828 goto done;
12831 error = got_repo_pack_fds_open(&pack_fds);
12832 if (error != NULL)
12833 goto done;
12835 error = got_worktree_open(&worktree, cwd);
12836 if (error) {
12837 if (error->code == GOT_ERR_NOT_WORKTREE)
12838 error = wrap_not_worktree_error(error, "info", cwd);
12839 goto done;
12842 #ifndef PROFILE
12843 /* Remove "cpath" promise. */
12844 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12845 NULL) == -1)
12846 err(1, "pledge");
12847 #endif
12848 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12849 if (error)
12850 goto done;
12852 if (argc >= 1) {
12853 error = get_worktree_paths_from_argv(&paths, argc, argv,
12854 worktree);
12855 if (error)
12856 goto done;
12857 show_files = 1;
12860 error = got_object_id_str(&id_str,
12861 got_worktree_get_base_commit_id(worktree));
12862 if (error)
12863 goto done;
12865 error = got_worktree_get_uuid(&uuidstr, worktree);
12866 if (error)
12867 goto done;
12869 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12870 printf("work tree base commit: %s\n", id_str);
12871 printf("work tree path prefix: %s\n",
12872 got_worktree_get_path_prefix(worktree));
12873 printf("work tree branch reference: %s\n",
12874 got_worktree_get_head_ref_name(worktree));
12875 printf("work tree UUID: %s\n", uuidstr);
12876 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12878 if (show_files) {
12879 struct got_pathlist_entry *pe;
12880 TAILQ_FOREACH(pe, &paths, entry) {
12881 if (pe->path_len == 0)
12882 continue;
12884 * Assume this path will fail. This will be corrected
12885 * in print_path_info() in case the path does suceeed.
12887 pe->data = (void *)got_error_path(pe->path,
12888 GOT_ERR_BAD_PATH);
12890 error = got_worktree_path_info(worktree, &paths,
12891 print_path_info, &paths, check_cancelled, NULL);
12892 if (error)
12893 goto done;
12894 TAILQ_FOREACH(pe, &paths, entry) {
12895 if (pe->data != NULL) {
12896 error = pe->data; /* bad path */
12897 break;
12901 done:
12902 if (pack_fds) {
12903 const struct got_error *pack_err =
12904 got_repo_pack_fds_close(pack_fds);
12905 if (error == NULL)
12906 error = pack_err;
12908 TAILQ_FOREACH(pe, &paths, entry)
12909 free((char *)pe->path);
12910 got_pathlist_free(&paths);
12911 free(cwd);
12912 free(id_str);
12913 free(uuidstr);
12914 return error;