Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static volatile sig_atomic_t sigint_received;
67 static volatile sig_atomic_t sigpipe_received;
69 static void
70 catch_sigint(int signo)
71 {
72 sigint_received = 1;
73 }
75 static void
76 catch_sigpipe(int signo)
77 {
78 sigpipe_received = 1;
79 }
82 struct got_cmd {
83 const char *cmd_name;
84 const struct got_error *(*cmd_main)(int, char *[]);
85 void (*cmd_usage)(void);
86 const char *cmd_alias;
87 };
89 __dead static void usage(int, int);
90 __dead static void usage_init(void);
91 __dead static void usage_import(void);
92 __dead static void usage_clone(void);
93 __dead static void usage_fetch(void);
94 __dead static void usage_checkout(void);
95 __dead static void usage_update(void);
96 __dead static void usage_log(void);
97 __dead static void usage_diff(void);
98 __dead static void usage_blame(void);
99 __dead static void usage_tree(void);
100 __dead static void usage_status(void);
101 __dead static void usage_ref(void);
102 __dead static void usage_branch(void);
103 __dead static void usage_tag(void);
104 __dead static void usage_add(void);
105 __dead static void usage_remove(void);
106 __dead static void usage_patch(void);
107 __dead static void usage_revert(void);
108 __dead static void usage_commit(void);
109 __dead static void usage_send(void);
110 __dead static void usage_cherrypick(void);
111 __dead static void usage_backout(void);
112 __dead static void usage_rebase(void);
113 __dead static void usage_histedit(void);
114 __dead static void usage_integrate(void);
115 __dead static void usage_merge(void);
116 __dead static void usage_stage(void);
117 __dead static void usage_unstage(void);
118 __dead static void usage_cat(void);
119 __dead static void usage_info(void);
121 static const struct got_error* cmd_init(int, char *[]);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "init", cmd_init, usage_init, "" },
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_init(void)
350 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
351 exit(1);
354 static const struct got_error *
355 cmd_init(int argc, char *argv[])
357 const struct got_error *error = NULL;
358 char *repo_path = NULL;
359 int ch;
361 while ((ch = getopt(argc, argv, "")) != -1) {
362 switch (ch) {
363 default:
364 usage_init();
365 /* NOTREACHED */
369 argc -= optind;
370 argv += optind;
372 #ifndef PROFILE
373 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
374 err(1, "pledge");
375 #endif
376 if (argc != 1)
377 usage_init();
379 repo_path = strdup(argv[0]);
380 if (repo_path == NULL)
381 return got_error_from_errno("strdup");
383 got_path_strip_trailing_slashes(repo_path);
385 error = got_path_mkdir(repo_path);
386 if (error &&
387 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
388 goto done;
390 error = apply_unveil(repo_path, 0, NULL);
391 if (error)
392 goto done;
394 error = got_repo_init(repo_path);
395 done:
396 free(repo_path);
397 return error;
400 __dead static void
401 usage_import(void)
403 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
404 "[-r repository-path] [-I pattern] path\n", getprogname());
405 exit(1);
408 static int
409 spawn_editor(const char *editor, const char *file)
411 pid_t pid;
412 sig_t sighup, sigint, sigquit;
413 int st = -1;
415 sighup = signal(SIGHUP, SIG_IGN);
416 sigint = signal(SIGINT, SIG_IGN);
417 sigquit = signal(SIGQUIT, SIG_IGN);
419 switch (pid = fork()) {
420 case -1:
421 goto doneediting;
422 case 0:
423 execl(editor, editor, file, (char *)NULL);
424 _exit(127);
427 while (waitpid(pid, &st, 0) == -1)
428 if (errno != EINTR)
429 break;
431 doneediting:
432 (void)signal(SIGHUP, sighup);
433 (void)signal(SIGINT, sigint);
434 (void)signal(SIGQUIT, sigquit);
436 if (!WIFEXITED(st)) {
437 errno = EINTR;
438 return -1;
441 return WEXITSTATUS(st);
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 char *line = NULL;
451 size_t linesize = 0;
452 ssize_t linelen;
453 struct stat st, st2;
454 FILE *fp = NULL;
455 size_t len, logmsg_len;
456 char *initial_content_stripped = NULL, *buf = NULL, *s;
458 *logmsg = NULL;
460 if (stat(logmsg_path, &st) == -1)
461 return got_error_from_errno2("stat", logmsg_path);
463 if (spawn_editor(editor, logmsg_path) == -1)
464 return got_error_from_errno("failed spawning editor");
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno("stat");
469 if (require_modification &&
470 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 /*
475 * Set up a stripped version of the initial content without comments
476 * and blank lines. We need this in order to check if the message
477 * has in fact been edited.
478 */
479 initial_content_stripped = malloc(initial_content_len + 1);
480 if (initial_content_stripped == NULL)
481 return got_error_from_errno("malloc");
482 initial_content_stripped[0] = '\0';
484 buf = strdup(initial_content);
485 if (buf == NULL) {
486 err = got_error_from_errno("strdup");
487 goto done;
489 s = buf;
490 len = 0;
491 while ((line = strsep(&s, "\n")) != NULL) {
492 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
493 continue; /* remove comments and leading empty lines */
494 len = strlcat(initial_content_stripped, line,
495 initial_content_len + 1);
496 if (len >= initial_content_len + 1) {
497 err = got_error(GOT_ERR_NO_SPACE);
498 goto done;
501 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
502 initial_content_stripped[len - 1] = '\0';
503 len--;
506 logmsg_len = st2.st_size;
507 *logmsg = malloc(logmsg_len + 1);
508 if (*logmsg == NULL)
509 return got_error_from_errno("malloc");
510 (*logmsg)[0] = '\0';
512 fp = fopen(logmsg_path, "re");
513 if (fp == NULL) {
514 err = got_error_from_errno("fopen");
515 goto done;
518 len = 0;
519 while ((linelen = getline(&line, &linesize, fp)) != -1) {
520 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
521 continue; /* remove comments and leading empty lines */
522 len = strlcat(*logmsg, line, logmsg_len + 1);
523 if (len >= logmsg_len + 1) {
524 err = got_error(GOT_ERR_NO_SPACE);
525 goto done;
528 free(line);
529 if (ferror(fp)) {
530 err = got_ferror(fp, GOT_ERR_IO);
531 goto done;
533 while (len > 0 && (*logmsg)[len - 1] == '\n') {
534 (*logmsg)[len - 1] = '\0';
535 len--;
538 if (len == 0) {
539 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
540 "commit message cannot be empty, aborting");
541 goto done;
543 if (require_modification &&
544 strcmp(*logmsg, initial_content_stripped) == 0)
545 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
546 "no changes made to commit message, aborting");
547 done:
548 free(initial_content_stripped);
549 free(buf);
550 if (fp && fclose(fp) == EOF && err == NULL)
551 err = got_error_from_errno("fclose");
552 if (err) {
553 free(*logmsg);
554 *logmsg = NULL;
556 return err;
559 static const struct got_error *
560 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
561 const char *path_dir, const char *branch_name)
563 char *initial_content = NULL;
564 const struct got_error *err = NULL;
565 int initial_content_len;
566 int fd = -1;
568 initial_content_len = asprintf(&initial_content,
569 "\n# %s to be imported to branch %s\n", path_dir,
570 branch_name);
571 if (initial_content_len == -1)
572 return got_error_from_errno("asprintf");
574 err = got_opentemp_named_fd(logmsg_path, &fd,
575 GOT_TMPDIR_STR "/got-importmsg");
576 if (err)
577 goto done;
579 if (write(fd, initial_content, initial_content_len) == -1) {
580 err = got_error_from_errno2("write", *logmsg_path);
581 goto done;
584 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
585 initial_content_len, 1);
586 done:
587 if (fd != -1 && close(fd) == -1 && err == NULL)
588 err = got_error_from_errno2("close", *logmsg_path);
589 free(initial_content);
590 if (err) {
591 free(*logmsg_path);
592 *logmsg_path = NULL;
594 return err;
597 static const struct got_error *
598 import_progress(void *arg, const char *path)
600 printf("A %s\n", path);
601 return NULL;
604 static int
605 valid_author(const char *author)
607 /*
608 * Really dumb email address check; we're only doing this to
609 * avoid git's object parser breaking on commits we create.
610 */
611 while (*author && *author != '<')
612 author++;
613 if (*author != '<')
614 return 0;
615 while (*author && *author != '@')
616 author++;
617 if (*author != '@')
618 return 0;
619 while (*author && *author != '>')
620 author++;
621 return *author == '>';
624 static const struct got_error *
625 get_author(char **author, struct got_repository *repo,
626 struct got_worktree *worktree)
628 const struct got_error *err = NULL;
629 const char *got_author = NULL, *name, *email;
630 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
632 *author = NULL;
634 if (worktree)
635 worktree_conf = got_worktree_get_gotconfig(worktree);
636 repo_conf = got_repo_get_gotconfig(repo);
638 /*
639 * Priority of potential author information sources, from most
640 * significant to least significant:
641 * 1) work tree's .got/got.conf file
642 * 2) repository's got.conf file
643 * 3) repository's git config file
644 * 4) environment variables
645 * 5) global git config files (in user's home directory or /etc)
646 */
648 if (worktree_conf)
649 got_author = got_gotconfig_get_author(worktree_conf);
650 if (got_author == NULL)
651 got_author = got_gotconfig_get_author(repo_conf);
652 if (got_author == NULL) {
653 name = got_repo_get_gitconfig_author_name(repo);
654 email = got_repo_get_gitconfig_author_email(repo);
655 if (name && email) {
656 if (asprintf(author, "%s <%s>", name, email) == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
661 got_author = getenv("GOT_AUTHOR");
662 if (got_author == NULL) {
663 name = got_repo_get_global_gitconfig_author_name(repo);
664 email = got_repo_get_global_gitconfig_author_email(
665 repo);
666 if (name && email) {
667 if (asprintf(author, "%s <%s>", name, email)
668 == -1)
669 return got_error_from_errno("asprintf");
670 return NULL;
672 /* TODO: Look up user in password database? */
673 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
677 *author = strdup(got_author);
678 if (*author == NULL)
679 return got_error_from_errno("strdup");
681 if (!valid_author(*author)) {
682 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
683 free(*author);
684 *author = NULL;
686 return err;
689 static const struct got_error *
690 get_gitconfig_path(char **gitconfig_path)
692 const char *homedir = getenv("HOME");
694 *gitconfig_path = NULL;
695 if (homedir) {
696 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
697 return got_error_from_errno("asprintf");
700 return NULL;
703 static const struct got_error *
704 cmd_import(int argc, char *argv[])
706 const struct got_error *error = NULL;
707 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
708 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
709 const char *branch_name = "main";
710 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
711 struct got_repository *repo = NULL;
712 struct got_reference *branch_ref = NULL, *head_ref = NULL;
713 struct got_object_id *new_commit_id = NULL;
714 int ch;
715 struct got_pathlist_head ignores;
716 struct got_pathlist_entry *pe;
717 int preserve_logmsg = 0;
718 int *pack_fds = NULL;
720 TAILQ_INIT(&ignores);
722 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
723 switch (ch) {
724 case 'b':
725 branch_name = optarg;
726 break;
727 case 'm':
728 logmsg = strdup(optarg);
729 if (logmsg == NULL) {
730 error = got_error_from_errno("strdup");
731 goto done;
733 break;
734 case 'r':
735 repo_path = realpath(optarg, NULL);
736 if (repo_path == NULL) {
737 error = got_error_from_errno2("realpath",
738 optarg);
739 goto done;
741 break;
742 case 'I':
743 if (optarg[0] == '\0')
744 break;
745 error = got_pathlist_insert(&pe, &ignores, optarg,
746 NULL);
747 if (error)
748 goto done;
749 break;
750 default:
751 usage_import();
752 /* NOTREACHED */
756 argc -= optind;
757 argv += optind;
759 #ifndef PROFILE
760 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
761 "unveil",
762 NULL) == -1)
763 err(1, "pledge");
764 #endif
765 if (argc != 1)
766 usage_import();
768 if (repo_path == NULL) {
769 repo_path = getcwd(NULL, 0);
770 if (repo_path == NULL)
771 return got_error_from_errno("getcwd");
773 got_path_strip_trailing_slashes(repo_path);
774 error = get_gitconfig_path(&gitconfig_path);
775 if (error)
776 goto done;
777 error = got_repo_pack_fds_open(&pack_fds);
778 if (error != NULL)
779 goto done;
780 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
781 if (error)
782 goto done;
784 error = get_author(&author, repo, NULL);
785 if (error)
786 return error;
788 /*
789 * Don't let the user create a branch name with a leading '-'.
790 * While technically a valid reference name, this case is usually
791 * an unintended typo.
792 */
793 if (branch_name[0] == '-')
794 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
796 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
797 error = got_error_from_errno("asprintf");
798 goto done;
801 error = got_ref_open(&branch_ref, repo, refname, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF)
804 goto done;
805 } else {
806 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
807 "import target branch already exists");
808 goto done;
811 path_dir = realpath(argv[0], NULL);
812 if (path_dir == NULL) {
813 error = got_error_from_errno2("realpath", argv[0]);
814 goto done;
816 got_path_strip_trailing_slashes(path_dir);
818 /*
819 * unveil(2) traverses exec(2); if an editor is used we have
820 * to apply unveil after the log message has been written.
821 */
822 if (logmsg == NULL || strlen(logmsg) == 0) {
823 error = get_editor(&editor);
824 if (error)
825 goto done;
826 free(logmsg);
827 error = collect_import_msg(&logmsg, &logmsg_path, editor,
828 path_dir, refname);
829 if (error) {
830 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
831 logmsg_path != NULL)
832 preserve_logmsg = 1;
833 goto done;
837 if (unveil(path_dir, "r") != 0) {
838 error = got_error_from_errno2("unveil", path_dir);
839 if (logmsg_path)
840 preserve_logmsg = 1;
841 goto done;
844 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
845 if (error) {
846 if (logmsg_path)
847 preserve_logmsg = 1;
848 goto done;
851 error = got_repo_import(&new_commit_id, path_dir, logmsg,
852 author, &ignores, repo, import_progress, NULL);
853 if (error) {
854 if (logmsg_path)
855 preserve_logmsg = 1;
856 goto done;
859 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
860 if (error) {
861 if (logmsg_path)
862 preserve_logmsg = 1;
863 goto done;
866 error = got_ref_write(branch_ref, repo);
867 if (error) {
868 if (logmsg_path)
869 preserve_logmsg = 1;
870 goto done;
873 error = got_object_id_str(&id_str, new_commit_id);
874 if (error) {
875 if (logmsg_path)
876 preserve_logmsg = 1;
877 goto done;
880 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
881 if (error) {
882 if (error->code != GOT_ERR_NOT_REF) {
883 if (logmsg_path)
884 preserve_logmsg = 1;
885 goto done;
888 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
889 branch_ref);
890 if (error) {
891 if (logmsg_path)
892 preserve_logmsg = 1;
893 goto done;
896 error = got_ref_write(head_ref, repo);
897 if (error) {
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
904 printf("Created branch %s with commit %s\n",
905 got_ref_get_name(branch_ref), id_str);
906 done:
907 if (pack_fds) {
908 const struct got_error *pack_err =
909 got_repo_pack_fds_close(pack_fds);
910 if (error == NULL)
911 error = pack_err;
913 if (preserve_logmsg) {
914 fprintf(stderr, "%s: log message preserved in %s\n",
915 getprogname(), logmsg_path);
916 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
917 error = got_error_from_errno2("unlink", logmsg_path);
918 free(logmsg);
919 free(logmsg_path);
920 free(repo_path);
921 free(editor);
922 free(refname);
923 free(new_commit_id);
924 free(id_str);
925 free(author);
926 free(gitconfig_path);
927 if (branch_ref)
928 got_ref_close(branch_ref);
929 if (head_ref)
930 got_ref_close(head_ref);
931 return error;
934 __dead static void
935 usage_clone(void)
937 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
938 "[-R reference] repository-url [directory]\n", getprogname());
939 exit(1);
942 struct got_fetch_progress_arg {
943 char last_scaled_size[FMT_SCALED_STRSIZE];
944 int last_p_indexed;
945 int last_p_resolved;
946 int verbosity;
948 struct got_repository *repo;
950 int create_configs;
951 int configs_created;
952 struct {
953 struct got_pathlist_head *symrefs;
954 struct got_pathlist_head *wanted_branches;
955 struct got_pathlist_head *wanted_refs;
956 const char *proto;
957 const char *host;
958 const char *port;
959 const char *remote_repo_path;
960 const char *git_url;
961 int fetch_all_branches;
962 int mirror_references;
963 } config_info;
964 };
966 /* XXX forward declaration */
967 static const struct got_error *
968 create_config_files(const char *proto, const char *host, const char *port,
969 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
970 int mirror_references, struct got_pathlist_head *symrefs,
971 struct got_pathlist_head *wanted_branches,
972 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
974 static const struct got_error *
975 fetch_progress(void *arg, const char *message, off_t packfile_size,
976 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
978 const struct got_error *err = NULL;
979 struct got_fetch_progress_arg *a = arg;
980 char scaled_size[FMT_SCALED_STRSIZE];
981 int p_indexed, p_resolved;
982 int print_size = 0, print_indexed = 0, print_resolved = 0;
984 /*
985 * In order to allow a failed clone to be resumed with 'got fetch'
986 * we try to create configuration files as soon as possible.
987 * Once the server has sent information about its default branch
988 * we have all required information.
989 */
990 if (a->create_configs && !a->configs_created &&
991 !TAILQ_EMPTY(a->config_info.symrefs)) {
992 err = create_config_files(a->config_info.proto,
993 a->config_info.host, a->config_info.port,
994 a->config_info.remote_repo_path,
995 a->config_info.git_url,
996 a->config_info.fetch_all_branches,
997 a->config_info.mirror_references,
998 a->config_info.symrefs,
999 a->config_info.wanted_branches,
1000 a->config_info.wanted_refs, a->repo);
1001 if (err)
1002 return err;
1003 a->configs_created = 1;
1006 if (a->verbosity < 0)
1007 return NULL;
1009 if (message && message[0] != '\0') {
1010 printf("\rserver: %s", message);
1011 fflush(stdout);
1012 return NULL;
1015 if (packfile_size > 0 || nobj_indexed > 0) {
1016 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1017 (a->last_scaled_size[0] == '\0' ||
1018 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1019 print_size = 1;
1020 if (strlcpy(a->last_scaled_size, scaled_size,
1021 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1022 return got_error(GOT_ERR_NO_SPACE);
1024 if (nobj_indexed > 0) {
1025 p_indexed = (nobj_indexed * 100) / nobj_total;
1026 if (p_indexed != a->last_p_indexed) {
1027 a->last_p_indexed = p_indexed;
1028 print_indexed = 1;
1029 print_size = 1;
1032 if (nobj_resolved > 0) {
1033 p_resolved = (nobj_resolved * 100) /
1034 (nobj_total - nobj_loose);
1035 if (p_resolved != a->last_p_resolved) {
1036 a->last_p_resolved = p_resolved;
1037 print_resolved = 1;
1038 print_indexed = 1;
1039 print_size = 1;
1044 if (print_size || print_indexed || print_resolved)
1045 printf("\r");
1046 if (print_size)
1047 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1048 if (print_indexed)
1049 printf("; indexing %d%%", p_indexed);
1050 if (print_resolved)
1051 printf("; resolving deltas %d%%", p_resolved);
1052 if (print_size || print_indexed || print_resolved)
1053 fflush(stdout);
1055 return NULL;
1058 static const struct got_error *
1059 create_symref(const char *refname, struct got_reference *target_ref,
1060 int verbosity, struct got_repository *repo)
1062 const struct got_error *err;
1063 struct got_reference *head_symref;
1065 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1066 if (err)
1067 return err;
1069 err = got_ref_write(head_symref, repo);
1070 if (err == NULL && verbosity > 0) {
1071 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1072 got_ref_get_name(target_ref));
1074 got_ref_close(head_symref);
1075 return err;
1078 static const struct got_error *
1079 list_remote_refs(struct got_pathlist_head *symrefs,
1080 struct got_pathlist_head *refs)
1082 const struct got_error *err;
1083 struct got_pathlist_entry *pe;
1085 TAILQ_FOREACH(pe, symrefs, entry) {
1086 const char *refname = pe->path;
1087 const char *targetref = pe->data;
1089 printf("%s: %s\n", refname, targetref);
1092 TAILQ_FOREACH(pe, refs, entry) {
1093 const char *refname = pe->path;
1094 struct got_object_id *id = pe->data;
1095 char *id_str;
1097 err = got_object_id_str(&id_str, id);
1098 if (err)
1099 return err;
1100 printf("%s: %s\n", refname, id_str);
1101 free(id_str);
1104 return NULL;
1107 static const struct got_error *
1108 create_ref(const char *refname, struct got_object_id *id,
1109 int verbosity, struct got_repository *repo)
1111 const struct got_error *err = NULL;
1112 struct got_reference *ref;
1113 char *id_str;
1115 err = got_object_id_str(&id_str, id);
1116 if (err)
1117 return err;
1119 err = got_ref_alloc(&ref, refname, id);
1120 if (err)
1121 goto done;
1123 err = got_ref_write(ref, repo);
1124 got_ref_close(ref);
1126 if (err == NULL && verbosity >= 0)
1127 printf("Created reference %s: %s\n", refname, id_str);
1128 done:
1129 free(id_str);
1130 return err;
1133 static int
1134 match_wanted_ref(const char *refname, const char *wanted_ref)
1136 if (strncmp(refname, "refs/", 5) != 0)
1137 return 0;
1138 refname += 5;
1141 * Prevent fetching of references that won't make any
1142 * sense outside of the remote repository's context.
1144 if (strncmp(refname, "got/", 4) == 0)
1145 return 0;
1146 if (strncmp(refname, "remotes/", 8) == 0)
1147 return 0;
1149 if (strncmp(wanted_ref, "refs/", 5) == 0)
1150 wanted_ref += 5;
1152 /* Allow prefix match. */
1153 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1154 return 1;
1156 /* Allow exact match. */
1157 return (strcmp(refname, wanted_ref) == 0);
1160 static int
1161 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1163 struct got_pathlist_entry *pe;
1165 TAILQ_FOREACH(pe, wanted_refs, entry) {
1166 if (match_wanted_ref(refname, pe->path))
1167 return 1;
1170 return 0;
1173 static const struct got_error *
1174 create_wanted_ref(const char *refname, struct got_object_id *id,
1175 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1177 const struct got_error *err;
1178 char *remote_refname;
1180 if (strncmp("refs/", refname, 5) == 0)
1181 refname += 5;
1183 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1184 remote_repo_name, refname) == -1)
1185 return got_error_from_errno("asprintf");
1187 err = create_ref(remote_refname, id, verbosity, repo);
1188 free(remote_refname);
1189 return err;
1192 static const struct got_error *
1193 create_gotconfig(const char *proto, const char *host, const char *port,
1194 const char *remote_repo_path, const char *default_branch,
1195 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1196 struct got_pathlist_head *wanted_refs, int mirror_references,
1197 struct got_repository *repo)
1199 const struct got_error *err = NULL;
1200 char *gotconfig_path = NULL;
1201 char *gotconfig = NULL;
1202 FILE *gotconfig_file = NULL;
1203 const char *branchname = NULL;
1204 char *branches = NULL, *refs = NULL;
1205 ssize_t n;
1207 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1208 struct got_pathlist_entry *pe;
1209 TAILQ_FOREACH(pe, wanted_branches, entry) {
1210 char *s;
1211 branchname = pe->path;
1212 if (strncmp(branchname, "refs/heads/", 11) == 0)
1213 branchname += 11;
1214 if (asprintf(&s, "%s\"%s\" ",
1215 branches ? branches : "", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1219 free(branches);
1220 branches = s;
1222 } else if (!fetch_all_branches && default_branch) {
1223 branchname = default_branch;
1224 if (strncmp(branchname, "refs/heads/", 11) == 0)
1225 branchname += 11;
1226 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1227 err = got_error_from_errno("asprintf");
1228 goto done;
1231 if (!TAILQ_EMPTY(wanted_refs)) {
1232 struct got_pathlist_entry *pe;
1233 TAILQ_FOREACH(pe, wanted_refs, entry) {
1234 char *s;
1235 const char *refname = pe->path;
1236 if (strncmp(refname, "refs/", 5) == 0)
1237 branchname += 5;
1238 if (asprintf(&s, "%s\"%s\" ",
1239 refs ? refs : "", refname) == -1) {
1240 err = got_error_from_errno("asprintf");
1241 goto done;
1243 free(refs);
1244 refs = s;
1248 /* Create got.conf(5). */
1249 gotconfig_path = got_repo_get_path_gotconfig(repo);
1250 if (gotconfig_path == NULL) {
1251 err = got_error_from_errno("got_repo_get_path_gotconfig");
1252 goto done;
1254 gotconfig_file = fopen(gotconfig_path, "ae");
1255 if (gotconfig_file == NULL) {
1256 err = got_error_from_errno2("fopen", gotconfig_path);
1257 goto done;
1259 if (asprintf(&gotconfig,
1260 "remote \"%s\" {\n"
1261 "\tserver %s\n"
1262 "\tprotocol %s\n"
1263 "%s%s%s"
1264 "\trepository \"%s\"\n"
1265 "%s%s%s"
1266 "%s%s%s"
1267 "%s"
1268 "%s"
1269 "}\n",
1270 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1271 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1272 remote_repo_path, branches ? "\tbranch { " : "",
1273 branches ? branches : "", branches ? "}\n" : "",
1274 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1275 mirror_references ? "\tmirror-references yes\n" : "",
1276 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1277 err = got_error_from_errno("asprintf");
1278 goto done;
1280 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1281 if (n != strlen(gotconfig)) {
1282 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1283 goto done;
1286 done:
1287 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1288 err = got_error_from_errno2("fclose", gotconfig_path);
1289 free(gotconfig_path);
1290 free(branches);
1291 return err;
1294 static const struct got_error *
1295 create_gitconfig(const char *git_url, const char *default_branch,
1296 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1297 struct got_pathlist_head *wanted_refs, int mirror_references,
1298 struct got_repository *repo)
1300 const struct got_error *err = NULL;
1301 char *gitconfig_path = NULL;
1302 char *gitconfig = NULL;
1303 FILE *gitconfig_file = NULL;
1304 char *branches = NULL, *refs = NULL;
1305 const char *branchname;
1306 ssize_t n;
1308 /* Create a config file Git can understand. */
1309 gitconfig_path = got_repo_get_path_gitconfig(repo);
1310 if (gitconfig_path == NULL) {
1311 err = got_error_from_errno("got_repo_get_path_gitconfig");
1312 goto done;
1314 gitconfig_file = fopen(gitconfig_path, "ae");
1315 if (gitconfig_file == NULL) {
1316 err = got_error_from_errno2("fopen", gitconfig_path);
1317 goto done;
1319 if (fetch_all_branches) {
1320 if (mirror_references) {
1321 if (asprintf(&branches,
1322 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1323 err = got_error_from_errno("asprintf");
1324 goto done;
1326 } else if (asprintf(&branches,
1327 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1328 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 } else if (!TAILQ_EMPTY(wanted_branches)) {
1333 struct got_pathlist_entry *pe;
1334 TAILQ_FOREACH(pe, wanted_branches, entry) {
1335 char *s;
1336 branchname = pe->path;
1337 if (strncmp(branchname, "refs/heads/", 11) == 0)
1338 branchname += 11;
1339 if (mirror_references) {
1340 if (asprintf(&s,
1341 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1342 branches ? branches : "",
1343 branchname, branchname) == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 } else if (asprintf(&s,
1348 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1349 branches ? branches : "",
1350 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1351 branchname) == -1) {
1352 err = got_error_from_errno("asprintf");
1353 goto done;
1355 free(branches);
1356 branches = s;
1358 } else {
1360 * If the server specified a default branch, use just that one.
1361 * Otherwise fall back to fetching all branches on next fetch.
1363 if (default_branch) {
1364 branchname = default_branch;
1365 if (strncmp(branchname, "refs/heads/", 11) == 0)
1366 branchname += 11;
1367 } else
1368 branchname = "*"; /* fall back to all branches */
1369 if (mirror_references) {
1370 if (asprintf(&branches,
1371 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1372 branchname, branchname) == -1) {
1373 err = got_error_from_errno("asprintf");
1374 goto done;
1376 } else if (asprintf(&branches,
1377 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1378 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1379 branchname) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1384 if (!TAILQ_EMPTY(wanted_refs)) {
1385 struct got_pathlist_entry *pe;
1386 TAILQ_FOREACH(pe, wanted_refs, entry) {
1387 char *s;
1388 const char *refname = pe->path;
1389 if (strncmp(refname, "refs/", 5) == 0)
1390 refname += 5;
1391 if (mirror_references) {
1392 if (asprintf(&s,
1393 "%s\tfetch = refs/%s:refs/%s\n",
1394 refs ? refs : "", refname, refname) == -1) {
1395 err = got_error_from_errno("asprintf");
1396 goto done;
1398 } else if (asprintf(&s,
1399 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1400 refs ? refs : "",
1401 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1402 refname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 free(refs);
1407 refs = s;
1411 if (asprintf(&gitconfig,
1412 "[remote \"%s\"]\n"
1413 "\turl = %s\n"
1414 "%s"
1415 "%s"
1416 "\tfetch = refs/tags/*:refs/tags/*\n",
1417 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1418 refs ? refs : "") == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1423 if (n != strlen(gitconfig)) {
1424 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1425 goto done;
1427 done:
1428 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1429 err = got_error_from_errno2("fclose", gitconfig_path);
1430 free(gitconfig_path);
1431 free(branches);
1432 return err;
1435 static const struct got_error *
1436 create_config_files(const char *proto, const char *host, const char *port,
1437 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1438 int mirror_references, struct got_pathlist_head *symrefs,
1439 struct got_pathlist_head *wanted_branches,
1440 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1442 const struct got_error *err = NULL;
1443 const char *default_branch = NULL;
1444 struct got_pathlist_entry *pe;
1447 * If we asked for a set of wanted branches then use the first
1448 * one of those.
1450 if (!TAILQ_EMPTY(wanted_branches)) {
1451 pe = TAILQ_FIRST(wanted_branches);
1452 default_branch = pe->path;
1453 } else {
1454 /* First HEAD ref listed by server is the default branch. */
1455 TAILQ_FOREACH(pe, symrefs, entry) {
1456 const char *refname = pe->path;
1457 const char *target = pe->data;
1459 if (strcmp(refname, GOT_REF_HEAD) != 0)
1460 continue;
1462 default_branch = target;
1463 break;
1467 /* Create got.conf(5). */
1468 err = create_gotconfig(proto, host, port, remote_repo_path,
1469 default_branch, fetch_all_branches, wanted_branches,
1470 wanted_refs, mirror_references, repo);
1471 if (err)
1472 return err;
1474 /* Create a config file Git can understand. */
1475 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1476 wanted_branches, wanted_refs, mirror_references, repo);
1479 static const struct got_error *
1480 cmd_clone(int argc, char *argv[])
1482 const struct got_error *error = NULL;
1483 const char *uri, *dirname;
1484 char *proto, *host, *port, *repo_name, *server_path;
1485 char *default_destdir = NULL, *id_str = NULL;
1486 const char *repo_path;
1487 struct got_repository *repo = NULL;
1488 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1489 struct got_pathlist_entry *pe;
1490 struct got_object_id *pack_hash = NULL;
1491 int ch, fetchfd = -1, fetchstatus;
1492 pid_t fetchpid = -1;
1493 struct got_fetch_progress_arg fpa;
1494 char *git_url = NULL;
1495 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1496 int list_refs_only = 0;
1497 int *pack_fds = NULL;
1499 TAILQ_INIT(&refs);
1500 TAILQ_INIT(&symrefs);
1501 TAILQ_INIT(&wanted_branches);
1502 TAILQ_INIT(&wanted_refs);
1504 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1505 switch (ch) {
1506 case 'a':
1507 fetch_all_branches = 1;
1508 break;
1509 case 'b':
1510 error = got_pathlist_append(&wanted_branches,
1511 optarg, NULL);
1512 if (error)
1513 return error;
1514 break;
1515 case 'l':
1516 list_refs_only = 1;
1517 break;
1518 case 'm':
1519 mirror_references = 1;
1520 break;
1521 case 'v':
1522 if (verbosity < 0)
1523 verbosity = 0;
1524 else if (verbosity < 3)
1525 verbosity++;
1526 break;
1527 case 'q':
1528 verbosity = -1;
1529 break;
1530 case 'R':
1531 error = got_pathlist_append(&wanted_refs,
1532 optarg, NULL);
1533 if (error)
1534 return error;
1535 break;
1536 default:
1537 usage_clone();
1538 break;
1541 argc -= optind;
1542 argv += optind;
1544 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1545 option_conflict('a', 'b');
1546 if (list_refs_only) {
1547 if (!TAILQ_EMPTY(&wanted_branches))
1548 option_conflict('l', 'b');
1549 if (fetch_all_branches)
1550 option_conflict('l', 'a');
1551 if (mirror_references)
1552 option_conflict('l', 'm');
1553 if (!TAILQ_EMPTY(&wanted_refs))
1554 option_conflict('l', 'R');
1557 uri = argv[0];
1559 if (argc == 1)
1560 dirname = NULL;
1561 else if (argc == 2)
1562 dirname = argv[1];
1563 else
1564 usage_clone();
1566 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1567 &repo_name, uri);
1568 if (error)
1569 goto done;
1571 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1572 host, port ? ":" : "", port ? port : "",
1573 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1574 error = got_error_from_errno("asprintf");
1575 goto done;
1578 if (strcmp(proto, "git") == 0) {
1579 #ifndef PROFILE
1580 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1581 "sendfd dns inet unveil", NULL) == -1)
1582 err(1, "pledge");
1583 #endif
1584 } else if (strcmp(proto, "git+ssh") == 0 ||
1585 strcmp(proto, "ssh") == 0) {
1586 #ifndef PROFILE
1587 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1588 "sendfd unveil", NULL) == -1)
1589 err(1, "pledge");
1590 #endif
1591 } else if (strcmp(proto, "http") == 0 ||
1592 strcmp(proto, "git+http") == 0) {
1593 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1594 goto done;
1595 } else {
1596 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1597 goto done;
1599 if (dirname == NULL) {
1600 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1601 error = got_error_from_errno("asprintf");
1602 goto done;
1604 repo_path = default_destdir;
1605 } else
1606 repo_path = dirname;
1608 if (!list_refs_only) {
1609 error = got_path_mkdir(repo_path);
1610 if (error &&
1611 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1612 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1613 goto done;
1614 if (!got_path_dir_is_empty(repo_path)) {
1615 error = got_error_path(repo_path,
1616 GOT_ERR_DIR_NOT_EMPTY);
1617 goto done;
1621 error = got_dial_apply_unveil(proto);
1622 if (error)
1623 goto done;
1625 error = apply_unveil(repo_path, 0, NULL);
1626 if (error)
1627 goto done;
1629 if (verbosity >= 0)
1630 printf("Connecting to %s%s%s\n", host,
1631 port ? ":" : "", port ? port : "");
1633 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1634 server_path, verbosity);
1635 if (error)
1636 goto done;
1638 if (!list_refs_only) {
1639 error = got_repo_init(repo_path);
1640 if (error)
1641 goto done;
1642 error = got_repo_pack_fds_open(&pack_fds);
1643 if (error != NULL)
1644 goto done;
1645 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1646 if (error)
1647 goto done;
1650 fpa.last_scaled_size[0] = '\0';
1651 fpa.last_p_indexed = -1;
1652 fpa.last_p_resolved = -1;
1653 fpa.verbosity = verbosity;
1654 fpa.create_configs = 1;
1655 fpa.configs_created = 0;
1656 fpa.repo = repo;
1657 fpa.config_info.symrefs = &symrefs;
1658 fpa.config_info.wanted_branches = &wanted_branches;
1659 fpa.config_info.wanted_refs = &wanted_refs;
1660 fpa.config_info.proto = proto;
1661 fpa.config_info.host = host;
1662 fpa.config_info.port = port;
1663 fpa.config_info.remote_repo_path = server_path;
1664 fpa.config_info.git_url = git_url;
1665 fpa.config_info.fetch_all_branches = fetch_all_branches;
1666 fpa.config_info.mirror_references = mirror_references;
1667 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1668 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1669 fetch_all_branches, &wanted_branches, &wanted_refs,
1670 list_refs_only, verbosity, fetchfd, repo,
1671 fetch_progress, &fpa);
1672 if (error)
1673 goto done;
1675 if (list_refs_only) {
1676 error = list_remote_refs(&symrefs, &refs);
1677 goto done;
1680 if (pack_hash == NULL) {
1681 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1682 "server sent an empty pack file");
1683 goto done;
1685 error = got_object_id_str(&id_str, pack_hash);
1686 if (error)
1687 goto done;
1688 if (verbosity >= 0)
1689 printf("\nFetched %s.pack\n", id_str);
1690 free(id_str);
1692 /* Set up references provided with the pack file. */
1693 TAILQ_FOREACH(pe, &refs, entry) {
1694 const char *refname = pe->path;
1695 struct got_object_id *id = pe->data;
1696 char *remote_refname;
1698 if (is_wanted_ref(&wanted_refs, refname) &&
1699 !mirror_references) {
1700 error = create_wanted_ref(refname, id,
1701 GOT_FETCH_DEFAULT_REMOTE_NAME,
1702 verbosity - 1, repo);
1703 if (error)
1704 goto done;
1705 continue;
1708 error = create_ref(refname, id, verbosity - 1, repo);
1709 if (error)
1710 goto done;
1712 if (mirror_references)
1713 continue;
1715 if (strncmp("refs/heads/", refname, 11) != 0)
1716 continue;
1718 if (asprintf(&remote_refname,
1719 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1720 refname + 11) == -1) {
1721 error = got_error_from_errno("asprintf");
1722 goto done;
1724 error = create_ref(remote_refname, id, verbosity - 1, repo);
1725 free(remote_refname);
1726 if (error)
1727 goto done;
1730 /* Set the HEAD reference if the server provided one. */
1731 TAILQ_FOREACH(pe, &symrefs, entry) {
1732 struct got_reference *target_ref;
1733 const char *refname = pe->path;
1734 const char *target = pe->data;
1735 char *remote_refname = NULL, *remote_target = NULL;
1737 if (strcmp(refname, GOT_REF_HEAD) != 0)
1738 continue;
1740 error = got_ref_open(&target_ref, repo, target, 0);
1741 if (error) {
1742 if (error->code == GOT_ERR_NOT_REF) {
1743 error = NULL;
1744 continue;
1746 goto done;
1749 error = create_symref(refname, target_ref, verbosity, repo);
1750 got_ref_close(target_ref);
1751 if (error)
1752 goto done;
1754 if (mirror_references)
1755 continue;
1757 if (strncmp("refs/heads/", target, 11) != 0)
1758 continue;
1760 if (asprintf(&remote_refname,
1761 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1762 refname) == -1) {
1763 error = got_error_from_errno("asprintf");
1764 goto done;
1766 if (asprintf(&remote_target,
1767 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 target + 11) == -1) {
1769 error = got_error_from_errno("asprintf");
1770 free(remote_refname);
1771 goto done;
1773 error = got_ref_open(&target_ref, repo, remote_target, 0);
1774 if (error) {
1775 free(remote_refname);
1776 free(remote_target);
1777 if (error->code == GOT_ERR_NOT_REF) {
1778 error = NULL;
1779 continue;
1781 goto done;
1783 error = create_symref(remote_refname, target_ref,
1784 verbosity - 1, repo);
1785 free(remote_refname);
1786 free(remote_target);
1787 got_ref_close(target_ref);
1788 if (error)
1789 goto done;
1791 if (pe == NULL) {
1793 * We failed to set the HEAD reference. If we asked for
1794 * a set of wanted branches use the first of one of those
1795 * which could be fetched instead.
1797 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1798 const char *target = pe->path;
1799 struct got_reference *target_ref;
1801 error = got_ref_open(&target_ref, repo, target, 0);
1802 if (error) {
1803 if (error->code == GOT_ERR_NOT_REF) {
1804 error = NULL;
1805 continue;
1807 goto done;
1810 error = create_symref(GOT_REF_HEAD, target_ref,
1811 verbosity, repo);
1812 got_ref_close(target_ref);
1813 if (error)
1814 goto done;
1815 break;
1819 if (verbosity >= 0)
1820 printf("Created %s repository '%s'\n",
1821 mirror_references ? "mirrored" : "cloned", repo_path);
1822 done:
1823 if (pack_fds) {
1824 const struct got_error *pack_err =
1825 got_repo_pack_fds_close(pack_fds);
1826 if (error == NULL)
1827 error = pack_err;
1829 if (fetchpid > 0) {
1830 if (kill(fetchpid, SIGTERM) == -1)
1831 error = got_error_from_errno("kill");
1832 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1833 error = got_error_from_errno("waitpid");
1835 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1836 error = got_error_from_errno("close");
1837 if (repo) {
1838 const struct got_error *close_err = got_repo_close(repo);
1839 if (error == NULL)
1840 error = close_err;
1842 TAILQ_FOREACH(pe, &refs, entry) {
1843 free((void *)pe->path);
1844 free(pe->data);
1846 got_pathlist_free(&refs);
1847 TAILQ_FOREACH(pe, &symrefs, entry) {
1848 free((void *)pe->path);
1849 free(pe->data);
1851 got_pathlist_free(&symrefs);
1852 got_pathlist_free(&wanted_branches);
1853 got_pathlist_free(&wanted_refs);
1854 free(pack_hash);
1855 free(proto);
1856 free(host);
1857 free(port);
1858 free(server_path);
1859 free(repo_name);
1860 free(default_destdir);
1861 free(git_url);
1862 return error;
1865 static const struct got_error *
1866 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1867 int replace_tags, int verbosity, struct got_repository *repo)
1869 const struct got_error *err = NULL;
1870 char *new_id_str = NULL;
1871 struct got_object_id *old_id = NULL;
1873 err = got_object_id_str(&new_id_str, new_id);
1874 if (err)
1875 goto done;
1877 if (!replace_tags &&
1878 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1879 err = got_ref_resolve(&old_id, repo, ref);
1880 if (err)
1881 goto done;
1882 if (got_object_id_cmp(old_id, new_id) == 0)
1883 goto done;
1884 if (verbosity >= 0) {
1885 printf("Rejecting update of existing tag %s: %s\n",
1886 got_ref_get_name(ref), new_id_str);
1888 goto done;
1891 if (got_ref_is_symbolic(ref)) {
1892 if (verbosity >= 0) {
1893 printf("Replacing reference %s: %s\n",
1894 got_ref_get_name(ref),
1895 got_ref_get_symref_target(ref));
1897 err = got_ref_change_symref_to_ref(ref, new_id);
1898 if (err)
1899 goto done;
1900 err = got_ref_write(ref, repo);
1901 if (err)
1902 goto done;
1903 } else {
1904 err = got_ref_resolve(&old_id, repo, ref);
1905 if (err)
1906 goto done;
1907 if (got_object_id_cmp(old_id, new_id) == 0)
1908 goto done;
1910 err = got_ref_change_ref(ref, new_id);
1911 if (err)
1912 goto done;
1913 err = got_ref_write(ref, repo);
1914 if (err)
1915 goto done;
1918 if (verbosity >= 0)
1919 printf("Updated %s: %s\n", got_ref_get_name(ref),
1920 new_id_str);
1921 done:
1922 free(old_id);
1923 free(new_id_str);
1924 return err;
1927 static const struct got_error *
1928 update_symref(const char *refname, struct got_reference *target_ref,
1929 int verbosity, struct got_repository *repo)
1931 const struct got_error *err = NULL, *unlock_err;
1932 struct got_reference *symref;
1933 int symref_is_locked = 0;
1935 err = got_ref_open(&symref, repo, refname, 1);
1936 if (err) {
1937 if (err->code != GOT_ERR_NOT_REF)
1938 return err;
1939 err = got_ref_alloc_symref(&symref, refname, target_ref);
1940 if (err)
1941 goto done;
1943 err = got_ref_write(symref, repo);
1944 if (err)
1945 goto done;
1947 if (verbosity >= 0)
1948 printf("Created reference %s: %s\n",
1949 got_ref_get_name(symref),
1950 got_ref_get_symref_target(symref));
1951 } else {
1952 symref_is_locked = 1;
1954 if (strcmp(got_ref_get_symref_target(symref),
1955 got_ref_get_name(target_ref)) == 0)
1956 goto done;
1958 err = got_ref_change_symref(symref,
1959 got_ref_get_name(target_ref));
1960 if (err)
1961 goto done;
1963 err = got_ref_write(symref, repo);
1964 if (err)
1965 goto done;
1967 if (verbosity >= 0)
1968 printf("Updated %s: %s\n", got_ref_get_name(symref),
1969 got_ref_get_symref_target(symref));
1972 done:
1973 if (symref_is_locked) {
1974 unlock_err = got_ref_unlock(symref);
1975 if (unlock_err && err == NULL)
1976 err = unlock_err;
1978 got_ref_close(symref);
1979 return err;
1982 __dead static void
1983 usage_fetch(void)
1985 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1986 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1987 "[remote-repository-name]\n",
1988 getprogname());
1989 exit(1);
1992 static const struct got_error *
1993 delete_missing_ref(struct got_reference *ref,
1994 int verbosity, struct got_repository *repo)
1996 const struct got_error *err = NULL;
1997 struct got_object_id *id = NULL;
1998 char *id_str = NULL;
2000 if (got_ref_is_symbolic(ref)) {
2001 err = got_ref_delete(ref, repo);
2002 if (err)
2003 return err;
2004 if (verbosity >= 0) {
2005 printf("Deleted %s: %s\n",
2006 got_ref_get_name(ref),
2007 got_ref_get_symref_target(ref));
2009 } else {
2010 err = got_ref_resolve(&id, repo, ref);
2011 if (err)
2012 return err;
2013 err = got_object_id_str(&id_str, id);
2014 if (err)
2015 goto done;
2017 err = got_ref_delete(ref, repo);
2018 if (err)
2019 goto done;
2020 if (verbosity >= 0) {
2021 printf("Deleted %s: %s\n",
2022 got_ref_get_name(ref), id_str);
2025 done:
2026 free(id);
2027 free(id_str);
2028 return NULL;
2031 static const struct got_error *
2032 delete_missing_refs(struct got_pathlist_head *their_refs,
2033 struct got_pathlist_head *their_symrefs,
2034 const struct got_remote_repo *remote,
2035 int verbosity, struct got_repository *repo)
2037 const struct got_error *err = NULL, *unlock_err;
2038 struct got_reflist_head my_refs;
2039 struct got_reflist_entry *re;
2040 struct got_pathlist_entry *pe;
2041 char *remote_namespace = NULL;
2042 char *local_refname = NULL;
2044 TAILQ_INIT(&my_refs);
2046 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2047 == -1)
2048 return got_error_from_errno("asprintf");
2050 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2051 if (err)
2052 goto done;
2054 TAILQ_FOREACH(re, &my_refs, entry) {
2055 const char *refname = got_ref_get_name(re->ref);
2056 const char *their_refname;
2058 if (remote->mirror_references) {
2059 their_refname = refname;
2060 } else {
2061 if (strncmp(refname, remote_namespace,
2062 strlen(remote_namespace)) == 0) {
2063 if (strcmp(refname + strlen(remote_namespace),
2064 GOT_REF_HEAD) == 0)
2065 continue;
2066 if (asprintf(&local_refname, "refs/heads/%s",
2067 refname + strlen(remote_namespace)) == -1) {
2068 err = got_error_from_errno("asprintf");
2069 goto done;
2071 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2072 continue;
2074 their_refname = local_refname;
2077 TAILQ_FOREACH(pe, their_refs, entry) {
2078 if (strcmp(their_refname, pe->path) == 0)
2079 break;
2081 if (pe != NULL)
2082 continue;
2084 TAILQ_FOREACH(pe, their_symrefs, entry) {
2085 if (strcmp(their_refname, pe->path) == 0)
2086 break;
2088 if (pe != NULL)
2089 continue;
2091 err = delete_missing_ref(re->ref, verbosity, repo);
2092 if (err)
2093 break;
2095 if (local_refname) {
2096 struct got_reference *ref;
2097 err = got_ref_open(&ref, repo, local_refname, 1);
2098 if (err) {
2099 if (err->code != GOT_ERR_NOT_REF)
2100 break;
2101 free(local_refname);
2102 local_refname = NULL;
2103 continue;
2105 err = delete_missing_ref(ref, verbosity, repo);
2106 if (err)
2107 break;
2108 unlock_err = got_ref_unlock(ref);
2109 got_ref_close(ref);
2110 if (unlock_err && err == NULL) {
2111 err = unlock_err;
2112 break;
2115 free(local_refname);
2116 local_refname = NULL;
2119 done:
2120 free(remote_namespace);
2121 free(local_refname);
2122 return err;
2125 static const struct got_error *
2126 update_wanted_ref(const char *refname, struct got_object_id *id,
2127 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2129 const struct got_error *err, *unlock_err;
2130 char *remote_refname;
2131 struct got_reference *ref;
2133 if (strncmp("refs/", refname, 5) == 0)
2134 refname += 5;
2136 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2137 remote_repo_name, refname) == -1)
2138 return got_error_from_errno("asprintf");
2140 err = got_ref_open(&ref, repo, remote_refname, 1);
2141 if (err) {
2142 if (err->code != GOT_ERR_NOT_REF)
2143 goto done;
2144 err = create_ref(remote_refname, id, verbosity, repo);
2145 } else {
2146 err = update_ref(ref, id, 0, verbosity, repo);
2147 unlock_err = got_ref_unlock(ref);
2148 if (unlock_err && err == NULL)
2149 err = unlock_err;
2150 got_ref_close(ref);
2152 done:
2153 free(remote_refname);
2154 return err;
2157 static const struct got_error *
2158 delete_ref(struct got_repository *repo, struct got_reference *ref)
2160 const struct got_error *err = NULL;
2161 struct got_object_id *id = NULL;
2162 char *id_str = NULL;
2163 const char *target;
2165 if (got_ref_is_symbolic(ref)) {
2166 target = got_ref_get_symref_target(ref);
2167 } else {
2168 err = got_ref_resolve(&id, repo, ref);
2169 if (err)
2170 goto done;
2171 err = got_object_id_str(&id_str, id);
2172 if (err)
2173 goto done;
2174 target = id_str;
2177 err = got_ref_delete(ref, repo);
2178 if (err)
2179 goto done;
2181 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2182 done:
2183 free(id);
2184 free(id_str);
2185 return err;
2188 static const struct got_error *
2189 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2191 const struct got_error *err = NULL;
2192 struct got_reflist_head refs;
2193 struct got_reflist_entry *re;
2194 char *prefix;
2196 TAILQ_INIT(&refs);
2198 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2199 err = got_error_from_errno("asprintf");
2200 goto done;
2202 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2203 if (err)
2204 goto done;
2206 TAILQ_FOREACH(re, &refs, entry)
2207 delete_ref(repo, re->ref);
2208 done:
2209 got_ref_list_free(&refs);
2210 return err;
2213 static const struct got_error *
2214 cmd_fetch(int argc, char *argv[])
2216 const struct got_error *error = NULL, *unlock_err;
2217 char *cwd = NULL, *repo_path = NULL;
2218 const char *remote_name;
2219 char *proto = NULL, *host = NULL, *port = NULL;
2220 char *repo_name = NULL, *server_path = NULL;
2221 const struct got_remote_repo *remotes, *remote = NULL;
2222 int nremotes;
2223 char *id_str = NULL;
2224 struct got_repository *repo = NULL;
2225 struct got_worktree *worktree = NULL;
2226 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2227 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2228 struct got_pathlist_entry *pe;
2229 struct got_object_id *pack_hash = NULL;
2230 int i, ch, fetchfd = -1, fetchstatus;
2231 pid_t fetchpid = -1;
2232 struct got_fetch_progress_arg fpa;
2233 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2234 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2235 int *pack_fds = NULL;
2237 TAILQ_INIT(&refs);
2238 TAILQ_INIT(&symrefs);
2239 TAILQ_INIT(&wanted_branches);
2240 TAILQ_INIT(&wanted_refs);
2242 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2243 switch (ch) {
2244 case 'a':
2245 fetch_all_branches = 1;
2246 break;
2247 case 'b':
2248 error = got_pathlist_append(&wanted_branches,
2249 optarg, NULL);
2250 if (error)
2251 return error;
2252 break;
2253 case 'd':
2254 delete_refs = 1;
2255 break;
2256 case 'l':
2257 list_refs_only = 1;
2258 break;
2259 case 'r':
2260 repo_path = realpath(optarg, NULL);
2261 if (repo_path == NULL)
2262 return got_error_from_errno2("realpath",
2263 optarg);
2264 got_path_strip_trailing_slashes(repo_path);
2265 break;
2266 case 't':
2267 replace_tags = 1;
2268 break;
2269 case 'v':
2270 if (verbosity < 0)
2271 verbosity = 0;
2272 else if (verbosity < 3)
2273 verbosity++;
2274 break;
2275 case 'q':
2276 verbosity = -1;
2277 break;
2278 case 'R':
2279 error = got_pathlist_append(&wanted_refs,
2280 optarg, NULL);
2281 if (error)
2282 return error;
2283 break;
2284 case 'X':
2285 delete_remote = 1;
2286 break;
2287 default:
2288 usage_fetch();
2289 break;
2292 argc -= optind;
2293 argv += optind;
2295 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2296 option_conflict('a', 'b');
2297 if (list_refs_only) {
2298 if (!TAILQ_EMPTY(&wanted_branches))
2299 option_conflict('l', 'b');
2300 if (fetch_all_branches)
2301 option_conflict('l', 'a');
2302 if (delete_refs)
2303 option_conflict('l', 'd');
2304 if (delete_remote)
2305 option_conflict('l', 'X');
2307 if (delete_remote) {
2308 if (fetch_all_branches)
2309 option_conflict('X', 'a');
2310 if (!TAILQ_EMPTY(&wanted_branches))
2311 option_conflict('X', 'b');
2312 if (delete_refs)
2313 option_conflict('X', 'd');
2314 if (replace_tags)
2315 option_conflict('X', 't');
2316 if (!TAILQ_EMPTY(&wanted_refs))
2317 option_conflict('X', 'R');
2320 if (argc == 0) {
2321 if (delete_remote)
2322 errx(1, "-X option requires a remote name");
2323 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2324 } else if (argc == 1)
2325 remote_name = argv[0];
2326 else
2327 usage_fetch();
2329 cwd = getcwd(NULL, 0);
2330 if (cwd == NULL) {
2331 error = got_error_from_errno("getcwd");
2332 goto done;
2335 error = got_repo_pack_fds_open(&pack_fds);
2336 if (error != NULL)
2337 goto done;
2339 if (repo_path == NULL) {
2340 error = got_worktree_open(&worktree, cwd);
2341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2342 goto done;
2343 else
2344 error = NULL;
2345 if (worktree) {
2346 repo_path =
2347 strdup(got_worktree_get_repo_path(worktree));
2348 if (repo_path == NULL)
2349 error = got_error_from_errno("strdup");
2350 if (error)
2351 goto done;
2352 } else {
2353 repo_path = strdup(cwd);
2354 if (repo_path == NULL) {
2355 error = got_error_from_errno("strdup");
2356 goto done;
2361 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2362 if (error)
2363 goto done;
2365 if (delete_remote) {
2366 error = delete_refs_for_remote(repo, remote_name);
2367 goto done; /* nothing else to do */
2370 if (worktree) {
2371 worktree_conf = got_worktree_get_gotconfig(worktree);
2372 if (worktree_conf) {
2373 got_gotconfig_get_remotes(&nremotes, &remotes,
2374 worktree_conf);
2375 for (i = 0; i < nremotes; i++) {
2376 if (strcmp(remotes[i].name, remote_name) == 0) {
2377 remote = &remotes[i];
2378 break;
2383 if (remote == NULL) {
2384 repo_conf = got_repo_get_gotconfig(repo);
2385 if (repo_conf) {
2386 got_gotconfig_get_remotes(&nremotes, &remotes,
2387 repo_conf);
2388 for (i = 0; i < nremotes; i++) {
2389 if (strcmp(remotes[i].name, remote_name) == 0) {
2390 remote = &remotes[i];
2391 break;
2396 if (remote == NULL) {
2397 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2398 for (i = 0; i < nremotes; i++) {
2399 if (strcmp(remotes[i].name, remote_name) == 0) {
2400 remote = &remotes[i];
2401 break;
2405 if (remote == NULL) {
2406 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2407 goto done;
2410 if (TAILQ_EMPTY(&wanted_branches)) {
2411 if (!fetch_all_branches)
2412 fetch_all_branches = remote->fetch_all_branches;
2413 for (i = 0; i < remote->nfetch_branches; i++) {
2414 got_pathlist_append(&wanted_branches,
2415 remote->fetch_branches[i], NULL);
2418 if (TAILQ_EMPTY(&wanted_refs)) {
2419 for (i = 0; i < remote->nfetch_refs; i++) {
2420 got_pathlist_append(&wanted_refs,
2421 remote->fetch_refs[i], NULL);
2425 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2426 &repo_name, remote->fetch_url);
2427 if (error)
2428 goto done;
2430 if (strcmp(proto, "git") == 0) {
2431 #ifndef PROFILE
2432 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2433 "sendfd dns inet unveil", NULL) == -1)
2434 err(1, "pledge");
2435 #endif
2436 } else if (strcmp(proto, "git+ssh") == 0 ||
2437 strcmp(proto, "ssh") == 0) {
2438 #ifndef PROFILE
2439 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2440 "sendfd unveil", NULL) == -1)
2441 err(1, "pledge");
2442 #endif
2443 } else if (strcmp(proto, "http") == 0 ||
2444 strcmp(proto, "git+http") == 0) {
2445 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2446 goto done;
2447 } else {
2448 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2449 goto done;
2452 error = got_dial_apply_unveil(proto);
2453 if (error)
2454 goto done;
2456 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2457 if (error)
2458 goto done;
2460 if (verbosity >= 0)
2461 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2462 port ? ":" : "", port ? port : "");
2464 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2465 server_path, verbosity);
2466 if (error)
2467 goto done;
2469 fpa.last_scaled_size[0] = '\0';
2470 fpa.last_p_indexed = -1;
2471 fpa.last_p_resolved = -1;
2472 fpa.verbosity = verbosity;
2473 fpa.repo = repo;
2474 fpa.create_configs = 0;
2475 fpa.configs_created = 0;
2476 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2477 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2478 remote->mirror_references, fetch_all_branches, &wanted_branches,
2479 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2480 fetch_progress, &fpa);
2481 if (error)
2482 goto done;
2484 if (list_refs_only) {
2485 error = list_remote_refs(&symrefs, &refs);
2486 goto done;
2489 if (pack_hash == NULL) {
2490 if (verbosity >= 0)
2491 printf("Already up-to-date\n");
2492 } else if (verbosity >= 0) {
2493 error = got_object_id_str(&id_str, pack_hash);
2494 if (error)
2495 goto done;
2496 printf("\nFetched %s.pack\n", id_str);
2497 free(id_str);
2498 id_str = NULL;
2501 /* Update references provided with the pack file. */
2502 TAILQ_FOREACH(pe, &refs, entry) {
2503 const char *refname = pe->path;
2504 struct got_object_id *id = pe->data;
2505 struct got_reference *ref;
2506 char *remote_refname;
2508 if (is_wanted_ref(&wanted_refs, refname) &&
2509 !remote->mirror_references) {
2510 error = update_wanted_ref(refname, id,
2511 remote->name, verbosity, repo);
2512 if (error)
2513 goto done;
2514 continue;
2517 if (remote->mirror_references ||
2518 strncmp("refs/tags/", refname, 10) == 0) {
2519 error = got_ref_open(&ref, repo, refname, 1);
2520 if (error) {
2521 if (error->code != GOT_ERR_NOT_REF)
2522 goto done;
2523 error = create_ref(refname, id, verbosity,
2524 repo);
2525 if (error)
2526 goto done;
2527 } else {
2528 error = update_ref(ref, id, replace_tags,
2529 verbosity, repo);
2530 unlock_err = got_ref_unlock(ref);
2531 if (unlock_err && error == NULL)
2532 error = unlock_err;
2533 got_ref_close(ref);
2534 if (error)
2535 goto done;
2537 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2538 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2539 remote_name, refname + 11) == -1) {
2540 error = got_error_from_errno("asprintf");
2541 goto done;
2544 error = got_ref_open(&ref, repo, remote_refname, 1);
2545 if (error) {
2546 if (error->code != GOT_ERR_NOT_REF)
2547 goto done;
2548 error = create_ref(remote_refname, id,
2549 verbosity, repo);
2550 if (error)
2551 goto done;
2552 } else {
2553 error = update_ref(ref, id, replace_tags,
2554 verbosity, repo);
2555 unlock_err = got_ref_unlock(ref);
2556 if (unlock_err && error == NULL)
2557 error = unlock_err;
2558 got_ref_close(ref);
2559 if (error)
2560 goto done;
2563 /* Also create a local branch if none exists yet. */
2564 error = got_ref_open(&ref, repo, refname, 1);
2565 if (error) {
2566 if (error->code != GOT_ERR_NOT_REF)
2567 goto done;
2568 error = create_ref(refname, id, verbosity,
2569 repo);
2570 if (error)
2571 goto done;
2572 } else {
2573 unlock_err = got_ref_unlock(ref);
2574 if (unlock_err && error == NULL)
2575 error = unlock_err;
2576 got_ref_close(ref);
2580 if (delete_refs) {
2581 error = delete_missing_refs(&refs, &symrefs, remote,
2582 verbosity, repo);
2583 if (error)
2584 goto done;
2587 if (!remote->mirror_references) {
2588 /* Update remote HEAD reference if the server provided one. */
2589 TAILQ_FOREACH(pe, &symrefs, entry) {
2590 struct got_reference *target_ref;
2591 const char *refname = pe->path;
2592 const char *target = pe->data;
2593 char *remote_refname = NULL, *remote_target = NULL;
2595 if (strcmp(refname, GOT_REF_HEAD) != 0)
2596 continue;
2598 if (strncmp("refs/heads/", target, 11) != 0)
2599 continue;
2601 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2602 remote->name, refname) == -1) {
2603 error = got_error_from_errno("asprintf");
2604 goto done;
2606 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2607 remote->name, target + 11) == -1) {
2608 error = got_error_from_errno("asprintf");
2609 free(remote_refname);
2610 goto done;
2613 error = got_ref_open(&target_ref, repo, remote_target,
2614 0);
2615 if (error) {
2616 free(remote_refname);
2617 free(remote_target);
2618 if (error->code == GOT_ERR_NOT_REF) {
2619 error = NULL;
2620 continue;
2622 goto done;
2624 error = update_symref(remote_refname, target_ref,
2625 verbosity, repo);
2626 free(remote_refname);
2627 free(remote_target);
2628 got_ref_close(target_ref);
2629 if (error)
2630 goto done;
2633 done:
2634 if (fetchpid > 0) {
2635 if (kill(fetchpid, SIGTERM) == -1)
2636 error = got_error_from_errno("kill");
2637 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2638 error = got_error_from_errno("waitpid");
2640 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2641 error = got_error_from_errno("close");
2642 if (repo) {
2643 const struct got_error *close_err = got_repo_close(repo);
2644 if (error == NULL)
2645 error = close_err;
2647 if (worktree)
2648 got_worktree_close(worktree);
2649 if (pack_fds) {
2650 const struct got_error *pack_err =
2651 got_repo_pack_fds_close(pack_fds);
2652 if (error == NULL)
2653 error = pack_err;
2655 TAILQ_FOREACH(pe, &refs, entry) {
2656 free((void *)pe->path);
2657 free(pe->data);
2659 got_pathlist_free(&refs);
2660 TAILQ_FOREACH(pe, &symrefs, entry) {
2661 free((void *)pe->path);
2662 free(pe->data);
2664 got_pathlist_free(&symrefs);
2665 got_pathlist_free(&wanted_branches);
2666 got_pathlist_free(&wanted_refs);
2667 free(id_str);
2668 free(cwd);
2669 free(repo_path);
2670 free(pack_hash);
2671 free(proto);
2672 free(host);
2673 free(port);
2674 free(server_path);
2675 free(repo_name);
2676 return error;
2680 __dead static void
2681 usage_checkout(void)
2683 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2684 "[-p prefix] [-q] repository-path [worktree-path]\n",
2685 getprogname());
2686 exit(1);
2689 static void
2690 show_worktree_base_ref_warning(void)
2692 fprintf(stderr, "%s: warning: could not create a reference "
2693 "to the work tree's base commit; the commit could be "
2694 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2695 "repository writable and running 'got update' will prevent this\n",
2696 getprogname());
2699 struct got_checkout_progress_arg {
2700 const char *worktree_path;
2701 int had_base_commit_ref_error;
2702 int verbosity;
2705 static const struct got_error *
2706 checkout_progress(void *arg, unsigned char status, const char *path)
2708 struct got_checkout_progress_arg *a = arg;
2710 /* Base commit bump happens silently. */
2711 if (status == GOT_STATUS_BUMP_BASE)
2712 return NULL;
2714 if (status == GOT_STATUS_BASE_REF_ERR) {
2715 a->had_base_commit_ref_error = 1;
2716 return NULL;
2719 while (path[0] == '/')
2720 path++;
2722 if (a->verbosity >= 0)
2723 printf("%c %s/%s\n", status, a->worktree_path, path);
2725 return NULL;
2728 static const struct got_error *
2729 check_cancelled(void *arg)
2731 if (sigint_received || sigpipe_received)
2732 return got_error(GOT_ERR_CANCELLED);
2733 return NULL;
2736 static const struct got_error *
2737 check_linear_ancestry(struct got_object_id *commit_id,
2738 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2739 struct got_repository *repo)
2741 const struct got_error *err = NULL;
2742 struct got_object_id *yca_id;
2744 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2745 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2746 if (err)
2747 return err;
2749 if (yca_id == NULL)
2750 return got_error(GOT_ERR_ANCESTRY);
2753 * Require a straight line of history between the target commit
2754 * and the work tree's base commit.
2756 * Non-linear situations such as this require a rebase:
2758 * (commit) D F (base_commit)
2759 * \ /
2760 * C E
2761 * \ /
2762 * B (yca)
2763 * |
2764 * A
2766 * 'got update' only handles linear cases:
2767 * Update forwards in time: A (base/yca) - B - C - D (commit)
2768 * Update backwards in time: D (base) - C - B - A (commit/yca)
2770 if (allow_forwards_in_time_only) {
2771 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2772 return got_error(GOT_ERR_ANCESTRY);
2773 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2774 got_object_id_cmp(base_commit_id, yca_id) != 0)
2775 return got_error(GOT_ERR_ANCESTRY);
2777 free(yca_id);
2778 return NULL;
2781 static const struct got_error *
2782 check_same_branch(struct got_object_id *commit_id,
2783 struct got_reference *head_ref, struct got_object_id *yca_id,
2784 struct got_repository *repo)
2786 const struct got_error *err = NULL;
2787 struct got_commit_graph *graph = NULL;
2788 struct got_object_id *head_commit_id = NULL;
2789 int is_same_branch = 0;
2791 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2792 if (err)
2793 goto done;
2795 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2796 is_same_branch = 1;
2797 goto done;
2799 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2800 is_same_branch = 1;
2801 goto done;
2804 err = got_commit_graph_open(&graph, "/", 1);
2805 if (err)
2806 goto done;
2808 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2809 check_cancelled, NULL);
2810 if (err)
2811 goto done;
2813 for (;;) {
2814 struct got_object_id *id;
2815 err = got_commit_graph_iter_next(&id, graph, repo,
2816 check_cancelled, NULL);
2817 if (err) {
2818 if (err->code == GOT_ERR_ITER_COMPLETED)
2819 err = NULL;
2820 break;
2823 if (id) {
2824 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2825 break;
2826 if (got_object_id_cmp(id, commit_id) == 0) {
2827 is_same_branch = 1;
2828 break;
2832 done:
2833 if (graph)
2834 got_commit_graph_close(graph);
2835 free(head_commit_id);
2836 if (!err && !is_same_branch)
2837 err = got_error(GOT_ERR_ANCESTRY);
2838 return err;
2841 static const struct got_error *
2842 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2844 static char msg[512];
2845 const char *branch_name;
2847 if (got_ref_is_symbolic(ref))
2848 branch_name = got_ref_get_symref_target(ref);
2849 else
2850 branch_name = got_ref_get_name(ref);
2852 if (strncmp("refs/heads/", branch_name, 11) == 0)
2853 branch_name += 11;
2855 snprintf(msg, sizeof(msg),
2856 "target commit is not contained in branch '%s'; "
2857 "the branch to use must be specified with -b; "
2858 "if necessary a new branch can be created for "
2859 "this commit with 'got branch -c %s BRANCH_NAME'",
2860 branch_name, commit_id_str);
2862 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2865 static const struct got_error *
2866 cmd_checkout(int argc, char *argv[])
2868 const struct got_error *error = NULL;
2869 struct got_repository *repo = NULL;
2870 struct got_reference *head_ref = NULL, *ref = NULL;
2871 struct got_worktree *worktree = NULL;
2872 char *repo_path = NULL;
2873 char *worktree_path = NULL;
2874 const char *path_prefix = "";
2875 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2876 char *commit_id_str = NULL;
2877 struct got_object_id *commit_id = NULL;
2878 char *cwd = NULL;
2879 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2880 struct got_pathlist_head paths;
2881 struct got_checkout_progress_arg cpa;
2882 int *pack_fds = NULL;
2884 TAILQ_INIT(&paths);
2886 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2887 switch (ch) {
2888 case 'b':
2889 branch_name = optarg;
2890 break;
2891 case 'c':
2892 commit_id_str = strdup(optarg);
2893 if (commit_id_str == NULL)
2894 return got_error_from_errno("strdup");
2895 break;
2896 case 'E':
2897 allow_nonempty = 1;
2898 break;
2899 case 'p':
2900 path_prefix = optarg;
2901 break;
2902 case 'q':
2903 verbosity = -1;
2904 break;
2905 default:
2906 usage_checkout();
2907 /* NOTREACHED */
2911 argc -= optind;
2912 argv += optind;
2914 #ifndef PROFILE
2915 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2916 "unveil", NULL) == -1)
2917 err(1, "pledge");
2918 #endif
2919 if (argc == 1) {
2920 char *base, *dotgit;
2921 const char *path;
2922 repo_path = realpath(argv[0], NULL);
2923 if (repo_path == NULL)
2924 return got_error_from_errno2("realpath", argv[0]);
2925 cwd = getcwd(NULL, 0);
2926 if (cwd == NULL) {
2927 error = got_error_from_errno("getcwd");
2928 goto done;
2930 if (path_prefix[0])
2931 path = path_prefix;
2932 else
2933 path = repo_path;
2934 error = got_path_basename(&base, path);
2935 if (error)
2936 goto done;
2937 dotgit = strstr(base, ".git");
2938 if (dotgit)
2939 *dotgit = '\0';
2940 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2941 error = got_error_from_errno("asprintf");
2942 free(base);
2943 goto done;
2945 free(base);
2946 } else if (argc == 2) {
2947 repo_path = realpath(argv[0], NULL);
2948 if (repo_path == NULL) {
2949 error = got_error_from_errno2("realpath", argv[0]);
2950 goto done;
2952 worktree_path = realpath(argv[1], NULL);
2953 if (worktree_path == NULL) {
2954 if (errno != ENOENT) {
2955 error = got_error_from_errno2("realpath",
2956 argv[1]);
2957 goto done;
2959 worktree_path = strdup(argv[1]);
2960 if (worktree_path == NULL) {
2961 error = got_error_from_errno("strdup");
2962 goto done;
2965 } else
2966 usage_checkout();
2968 got_path_strip_trailing_slashes(repo_path);
2969 got_path_strip_trailing_slashes(worktree_path);
2971 error = got_repo_pack_fds_open(&pack_fds);
2972 if (error != NULL)
2973 goto done;
2975 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2976 if (error != NULL)
2977 goto done;
2979 /* Pre-create work tree path for unveil(2) */
2980 error = got_path_mkdir(worktree_path);
2981 if (error) {
2982 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2983 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2984 goto done;
2985 if (!allow_nonempty &&
2986 !got_path_dir_is_empty(worktree_path)) {
2987 error = got_error_path(worktree_path,
2988 GOT_ERR_DIR_NOT_EMPTY);
2989 goto done;
2993 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2994 if (error)
2995 goto done;
2997 error = got_ref_open(&head_ref, repo, branch_name, 0);
2998 if (error != NULL)
2999 goto done;
3001 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3002 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3003 goto done;
3005 error = got_worktree_open(&worktree, worktree_path);
3006 if (error != NULL)
3007 goto done;
3009 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3010 path_prefix);
3011 if (error != NULL)
3012 goto done;
3013 if (!same_path_prefix) {
3014 error = got_error(GOT_ERR_PATH_PREFIX);
3015 goto done;
3018 if (commit_id_str) {
3019 struct got_reflist_head refs;
3020 TAILQ_INIT(&refs);
3021 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3022 NULL);
3023 if (error)
3024 goto done;
3025 error = got_repo_match_object_id(&commit_id, NULL,
3026 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3027 got_ref_list_free(&refs);
3028 if (error)
3029 goto done;
3030 error = check_linear_ancestry(commit_id,
3031 got_worktree_get_base_commit_id(worktree), 0, repo);
3032 if (error != NULL) {
3033 if (error->code == GOT_ERR_ANCESTRY) {
3034 error = checkout_ancestry_error(
3035 head_ref, commit_id_str);
3037 goto done;
3039 error = check_same_branch(commit_id, head_ref, NULL, repo);
3040 if (error) {
3041 if (error->code == GOT_ERR_ANCESTRY) {
3042 error = checkout_ancestry_error(
3043 head_ref, commit_id_str);
3045 goto done;
3047 error = got_worktree_set_base_commit_id(worktree, repo,
3048 commit_id);
3049 if (error)
3050 goto done;
3051 /* Expand potentially abbreviated commit ID string. */
3052 free(commit_id_str);
3053 error = got_object_id_str(&commit_id_str, commit_id);
3054 if (error)
3055 goto done;
3056 } else {
3057 commit_id = got_object_id_dup(
3058 got_worktree_get_base_commit_id(worktree));
3059 if (commit_id == NULL) {
3060 error = got_error_from_errno("got_object_id_dup");
3061 goto done;
3063 error = got_object_id_str(&commit_id_str, commit_id);
3064 if (error)
3065 goto done;
3068 error = got_pathlist_append(&paths, "", NULL);
3069 if (error)
3070 goto done;
3071 cpa.worktree_path = worktree_path;
3072 cpa.had_base_commit_ref_error = 0;
3073 cpa.verbosity = verbosity;
3074 error = got_worktree_checkout_files(worktree, &paths, repo,
3075 checkout_progress, &cpa, check_cancelled, NULL);
3076 if (error != NULL)
3077 goto done;
3079 if (got_ref_is_symbolic(head_ref)) {
3080 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3081 if (error)
3082 goto done;
3083 refname = got_ref_get_name(ref);
3084 } else
3085 refname = got_ref_get_name(head_ref);
3086 printf("Checked out %s: %s\n", refname, commit_id_str);
3087 printf("Now shut up and hack\n");
3088 if (cpa.had_base_commit_ref_error)
3089 show_worktree_base_ref_warning();
3090 done:
3091 if (pack_fds) {
3092 const struct got_error *pack_err =
3093 got_repo_pack_fds_close(pack_fds);
3094 if (error == NULL)
3095 error = pack_err;
3097 if (head_ref)
3098 got_ref_close(head_ref);
3099 if (ref)
3100 got_ref_close(ref);
3101 got_pathlist_free(&paths);
3102 free(commit_id_str);
3103 free(commit_id);
3104 free(repo_path);
3105 free(worktree_path);
3106 free(cwd);
3107 return error;
3110 struct got_update_progress_arg {
3111 int did_something;
3112 int conflicts;
3113 int obstructed;
3114 int not_updated;
3115 int missing;
3116 int not_deleted;
3117 int unversioned;
3118 int verbosity;
3121 static void
3122 print_update_progress_stats(struct got_update_progress_arg *upa)
3124 if (!upa->did_something)
3125 return;
3127 if (upa->conflicts > 0)
3128 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3129 if (upa->obstructed > 0)
3130 printf("File paths obstructed by a non-regular file: %d\n",
3131 upa->obstructed);
3132 if (upa->not_updated > 0)
3133 printf("Files not updated because of existing merge "
3134 "conflicts: %d\n", upa->not_updated);
3138 * The meaning of some status codes differs between merge-style operations and
3139 * update operations. For example, the ! status code means "file was missing"
3140 * if changes were merged into the work tree, and "missing file was restored"
3141 * if the work tree was updated. This function should be used by any operation
3142 * which merges changes into the work tree without updating the work tree.
3144 static void
3145 print_merge_progress_stats(struct got_update_progress_arg *upa)
3147 if (!upa->did_something)
3148 return;
3150 if (upa->conflicts > 0)
3151 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3152 if (upa->obstructed > 0)
3153 printf("File paths obstructed by a non-regular file: %d\n",
3154 upa->obstructed);
3155 if (upa->missing > 0)
3156 printf("Files which had incoming changes but could not be "
3157 "found in the work tree: %d\n", upa->missing);
3158 if (upa->not_deleted > 0)
3159 printf("Files not deleted due to differences in deleted "
3160 "content: %d\n", upa->not_deleted);
3161 if (upa->unversioned > 0)
3162 printf("Files not merged because an unversioned file was "
3163 "found in the work tree: %d\n", upa->unversioned);
3166 __dead static void
3167 usage_update(void)
3169 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3170 "[path ...]\n",
3171 getprogname());
3172 exit(1);
3175 static const struct got_error *
3176 update_progress(void *arg, unsigned char status, const char *path)
3178 struct got_update_progress_arg *upa = arg;
3180 if (status == GOT_STATUS_EXISTS ||
3181 status == GOT_STATUS_BASE_REF_ERR)
3182 return NULL;
3184 upa->did_something = 1;
3186 /* Base commit bump happens silently. */
3187 if (status == GOT_STATUS_BUMP_BASE)
3188 return NULL;
3190 if (status == GOT_STATUS_CONFLICT)
3191 upa->conflicts++;
3192 if (status == GOT_STATUS_OBSTRUCTED)
3193 upa->obstructed++;
3194 if (status == GOT_STATUS_CANNOT_UPDATE)
3195 upa->not_updated++;
3196 if (status == GOT_STATUS_MISSING)
3197 upa->missing++;
3198 if (status == GOT_STATUS_CANNOT_DELETE)
3199 upa->not_deleted++;
3200 if (status == GOT_STATUS_UNVERSIONED)
3201 upa->unversioned++;
3203 while (path[0] == '/')
3204 path++;
3205 if (upa->verbosity >= 0)
3206 printf("%c %s\n", status, path);
3208 return NULL;
3211 static const struct got_error *
3212 switch_head_ref(struct got_reference *head_ref,
3213 struct got_object_id *commit_id, struct got_worktree *worktree,
3214 struct got_repository *repo)
3216 const struct got_error *err = NULL;
3217 char *base_id_str;
3218 int ref_has_moved = 0;
3220 /* Trivial case: switching between two different references. */
3221 if (strcmp(got_ref_get_name(head_ref),
3222 got_worktree_get_head_ref_name(worktree)) != 0) {
3223 printf("Switching work tree from %s to %s\n",
3224 got_worktree_get_head_ref_name(worktree),
3225 got_ref_get_name(head_ref));
3226 return got_worktree_set_head_ref(worktree, head_ref);
3229 err = check_linear_ancestry(commit_id,
3230 got_worktree_get_base_commit_id(worktree), 0, repo);
3231 if (err) {
3232 if (err->code != GOT_ERR_ANCESTRY)
3233 return err;
3234 ref_has_moved = 1;
3236 if (!ref_has_moved)
3237 return NULL;
3239 /* Switching to a rebased branch with the same reference name. */
3240 err = got_object_id_str(&base_id_str,
3241 got_worktree_get_base_commit_id(worktree));
3242 if (err)
3243 return err;
3244 printf("Reference %s now points at a different branch\n",
3245 got_worktree_get_head_ref_name(worktree));
3246 printf("Switching work tree from %s to %s\n", base_id_str,
3247 got_worktree_get_head_ref_name(worktree));
3248 return NULL;
3251 static const struct got_error *
3252 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3254 const struct got_error *err;
3255 int in_progress;
3257 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3258 if (err)
3259 return err;
3260 if (in_progress)
3261 return got_error(GOT_ERR_REBASING);
3263 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3264 if (err)
3265 return err;
3266 if (in_progress)
3267 return got_error(GOT_ERR_HISTEDIT_BUSY);
3269 return NULL;
3272 static const struct got_error *
3273 check_merge_in_progress(struct got_worktree *worktree,
3274 struct got_repository *repo)
3276 const struct got_error *err;
3277 int in_progress;
3279 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3280 if (err)
3281 return err;
3282 if (in_progress)
3283 return got_error(GOT_ERR_MERGE_BUSY);
3285 return NULL;
3288 static const struct got_error *
3289 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3290 char *argv[], struct got_worktree *worktree)
3292 const struct got_error *err = NULL;
3293 char *path;
3294 struct got_pathlist_entry *new;
3295 int i;
3297 if (argc == 0) {
3298 path = strdup("");
3299 if (path == NULL)
3300 return got_error_from_errno("strdup");
3301 return got_pathlist_append(paths, path, NULL);
3304 for (i = 0; i < argc; i++) {
3305 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3306 if (err)
3307 break;
3308 err = got_pathlist_insert(&new, paths, path, NULL);
3309 if (err || new == NULL /* duplicate */) {
3310 free(path);
3311 if (err)
3312 break;
3316 return err;
3319 static const struct got_error *
3320 wrap_not_worktree_error(const struct got_error *orig_err,
3321 const char *cmdname, const char *path)
3323 const struct got_error *err;
3324 struct got_repository *repo;
3325 static char msg[512];
3326 int *pack_fds = NULL;
3328 err = got_repo_pack_fds_open(&pack_fds);
3329 if (err)
3330 return err;
3332 err = got_repo_open(&repo, path, NULL, pack_fds);
3333 if (err)
3334 return orig_err;
3336 snprintf(msg, sizeof(msg),
3337 "'got %s' needs a work tree in addition to a git repository\n"
3338 "Work trees can be checked out from this Git repository with "
3339 "'got checkout'.\n"
3340 "The got(1) manual page contains more information.", cmdname);
3341 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3342 got_repo_close(repo);
3343 if (pack_fds) {
3344 const struct got_error *pack_err =
3345 got_repo_pack_fds_close(pack_fds);
3346 if (err == NULL)
3347 err = pack_err;
3349 return err;
3352 static const struct got_error *
3353 cmd_update(int argc, char *argv[])
3355 const struct got_error *error = NULL;
3356 struct got_repository *repo = NULL;
3357 struct got_worktree *worktree = NULL;
3358 char *worktree_path = NULL;
3359 struct got_object_id *commit_id = NULL;
3360 char *commit_id_str = NULL;
3361 const char *branch_name = NULL;
3362 struct got_reference *head_ref = NULL;
3363 struct got_pathlist_head paths;
3364 struct got_pathlist_entry *pe;
3365 int ch, verbosity = 0;
3366 struct got_update_progress_arg upa;
3367 int *pack_fds = NULL;
3369 TAILQ_INIT(&paths);
3371 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3372 switch (ch) {
3373 case 'b':
3374 branch_name = optarg;
3375 break;
3376 case 'c':
3377 commit_id_str = strdup(optarg);
3378 if (commit_id_str == NULL)
3379 return got_error_from_errno("strdup");
3380 break;
3381 case 'q':
3382 verbosity = -1;
3383 break;
3384 default:
3385 usage_update();
3386 /* NOTREACHED */
3390 argc -= optind;
3391 argv += optind;
3393 #ifndef PROFILE
3394 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3395 "unveil", NULL) == -1)
3396 err(1, "pledge");
3397 #endif
3398 worktree_path = getcwd(NULL, 0);
3399 if (worktree_path == NULL) {
3400 error = got_error_from_errno("getcwd");
3401 goto done;
3404 error = got_repo_pack_fds_open(&pack_fds);
3405 if (error != NULL)
3406 goto done;
3408 error = got_worktree_open(&worktree, worktree_path);
3409 if (error) {
3410 if (error->code == GOT_ERR_NOT_WORKTREE)
3411 error = wrap_not_worktree_error(error, "update",
3412 worktree_path);
3413 goto done;
3416 error = check_rebase_or_histedit_in_progress(worktree);
3417 if (error)
3418 goto done;
3420 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3421 NULL, pack_fds);
3422 if (error != NULL)
3423 goto done;
3425 error = apply_unveil(got_repo_get_path(repo), 0,
3426 got_worktree_get_root_path(worktree));
3427 if (error)
3428 goto done;
3430 error = check_merge_in_progress(worktree, repo);
3431 if (error)
3432 goto done;
3434 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3435 if (error)
3436 goto done;
3438 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3439 got_worktree_get_head_ref_name(worktree), 0);
3440 if (error != NULL)
3441 goto done;
3442 if (commit_id_str == NULL) {
3443 error = got_ref_resolve(&commit_id, repo, head_ref);
3444 if (error != NULL)
3445 goto done;
3446 error = got_object_id_str(&commit_id_str, commit_id);
3447 if (error != NULL)
3448 goto done;
3449 } else {
3450 struct got_reflist_head refs;
3451 TAILQ_INIT(&refs);
3452 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3453 NULL);
3454 if (error)
3455 goto done;
3456 error = got_repo_match_object_id(&commit_id, NULL,
3457 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3458 got_ref_list_free(&refs);
3459 free(commit_id_str);
3460 commit_id_str = NULL;
3461 if (error)
3462 goto done;
3463 error = got_object_id_str(&commit_id_str, commit_id);
3464 if (error)
3465 goto done;
3468 if (branch_name) {
3469 struct got_object_id *head_commit_id;
3470 TAILQ_FOREACH(pe, &paths, entry) {
3471 if (pe->path_len == 0)
3472 continue;
3473 error = got_error_msg(GOT_ERR_BAD_PATH,
3474 "switching between branches requires that "
3475 "the entire work tree gets updated");
3476 goto done;
3478 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3479 if (error)
3480 goto done;
3481 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3482 repo);
3483 free(head_commit_id);
3484 if (error != NULL)
3485 goto done;
3486 error = check_same_branch(commit_id, head_ref, NULL, repo);
3487 if (error)
3488 goto done;
3489 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3490 if (error)
3491 goto done;
3492 } else {
3493 error = check_linear_ancestry(commit_id,
3494 got_worktree_get_base_commit_id(worktree), 0, repo);
3495 if (error != NULL) {
3496 if (error->code == GOT_ERR_ANCESTRY)
3497 error = got_error(GOT_ERR_BRANCH_MOVED);
3498 goto done;
3500 error = check_same_branch(commit_id, head_ref, NULL, repo);
3501 if (error)
3502 goto done;
3505 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3506 commit_id) != 0) {
3507 error = got_worktree_set_base_commit_id(worktree, repo,
3508 commit_id);
3509 if (error)
3510 goto done;
3513 memset(&upa, 0, sizeof(upa));
3514 upa.verbosity = verbosity;
3515 error = got_worktree_checkout_files(worktree, &paths, repo,
3516 update_progress, &upa, check_cancelled, NULL);
3517 if (error != NULL)
3518 goto done;
3520 if (upa.did_something) {
3521 printf("Updated to %s: %s\n",
3522 got_worktree_get_head_ref_name(worktree), commit_id_str);
3523 } else
3524 printf("Already up-to-date\n");
3526 print_update_progress_stats(&upa);
3527 done:
3528 if (pack_fds) {
3529 const struct got_error *pack_err =
3530 got_repo_pack_fds_close(pack_fds);
3531 if (error == NULL)
3532 error = pack_err;
3534 free(worktree_path);
3535 TAILQ_FOREACH(pe, &paths, entry)
3536 free((char *)pe->path);
3537 got_pathlist_free(&paths);
3538 free(commit_id);
3539 free(commit_id_str);
3540 return error;
3543 static const struct got_error *
3544 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3545 const char *path, int diff_context, int ignore_whitespace,
3546 int force_text_diff, struct got_repository *repo, FILE *outfile)
3548 const struct got_error *err = NULL;
3549 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3550 FILE *f1 = NULL, *f2 = NULL;
3551 int fd1 = -1, fd2 = -1;
3553 fd1 = got_opentempfd();
3554 if (fd1 == -1)
3555 return got_error_from_errno("got_opentempfd");
3556 fd2 = got_opentempfd();
3557 if (fd2 == -1) {
3558 err = got_error_from_errno("got_opentempfd");
3559 goto done;
3562 if (blob_id1) {
3563 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3564 fd1);
3565 if (err)
3566 goto done;
3567 f1 = got_opentemp();
3568 if (f1 == NULL) {
3569 err = got_error_from_errno("got_opentemp");
3570 goto done;
3574 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3575 if (err)
3576 goto done;
3578 f2 = got_opentemp();
3579 if (f2 == NULL) {
3580 err = got_error_from_errno("got_opentemp");
3581 goto done;
3584 while (path[0] == '/')
3585 path++;
3586 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3587 diff_context, ignore_whitespace, force_text_diff, outfile);
3588 done:
3589 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3590 err = got_error_from_errno("close");
3591 if (blob1)
3592 got_object_blob_close(blob1);
3593 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3594 err = got_error_from_errno("close");
3595 got_object_blob_close(blob2);
3596 if (f1 && fclose(f1) == EOF && err == NULL)
3597 err = got_error_from_errno("fclose");
3598 if (f2 && fclose(f2) == EOF && err == NULL)
3599 err = got_error_from_errno("fclose");
3600 return err;
3603 static const struct got_error *
3604 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3605 const char *path, int diff_context, int ignore_whitespace,
3606 int force_text_diff, struct got_repository *repo, FILE *outfile)
3608 const struct got_error *err = NULL;
3609 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3610 struct got_diff_blob_output_unidiff_arg arg;
3611 FILE *f1 = NULL, *f2 = NULL;
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 f1 = got_opentemp();
3619 if (f1 == NULL) {
3620 err = got_error_from_errno("got_opentemp");
3621 goto done;
3624 fd1 = got_opentempfd();
3625 if (fd1 == -1) {
3626 err = got_error_from_errno("got_opentempfd");
3627 goto done;
3631 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3632 if (err)
3633 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;
4598 * Create a file which contains the target path of a symlink so we can feed
4599 * it as content to the diff engine.
4601 static const struct got_error *
4602 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4603 const char *abspath)
4605 const struct got_error *err = NULL;
4606 char target_path[PATH_MAX];
4607 ssize_t target_len, outlen;
4609 *fd = -1;
4611 if (dirfd != -1) {
4612 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4613 if (target_len == -1)
4614 return got_error_from_errno2("readlinkat", abspath);
4615 } else {
4616 target_len = readlink(abspath, target_path, PATH_MAX);
4617 if (target_len == -1)
4618 return got_error_from_errno2("readlink", abspath);
4621 *fd = got_opentempfd();
4622 if (*fd == -1)
4623 return got_error_from_errno("got_opentempfd");
4625 outlen = write(*fd, target_path, target_len);
4626 if (outlen == -1) {
4627 err = got_error_from_errno("got_opentempfd");
4628 goto done;
4631 if (lseek(*fd, 0, SEEK_SET) == -1) {
4632 err = got_error_from_errno2("lseek", abspath);
4633 goto done;
4635 done:
4636 if (err) {
4637 close(*fd);
4638 *fd = -1;
4640 return err;
4643 static const struct got_error *
4644 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4645 const char *path, struct got_object_id *blob_id,
4646 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4647 int dirfd, const char *de_name)
4649 struct print_diff_arg *a = arg;
4650 const struct got_error *err = NULL;
4651 struct got_blob_object *blob1 = NULL;
4652 int fd = -1, fd1 = -1, fd2 = -1;
4653 FILE *f1 = NULL, *f2 = NULL;
4654 char *abspath = NULL, *label1 = NULL;
4655 struct stat sb;
4656 off_t size1 = 0;
4658 if (a->diff_staged) {
4659 if (staged_status != GOT_STATUS_MODIFY &&
4660 staged_status != GOT_STATUS_ADD &&
4661 staged_status != GOT_STATUS_DELETE)
4662 return NULL;
4663 } else {
4664 if (staged_status == GOT_STATUS_DELETE)
4665 return NULL;
4666 if (status == GOT_STATUS_NONEXISTENT)
4667 return got_error_set_errno(ENOENT, path);
4668 if (status != GOT_STATUS_MODIFY &&
4669 status != GOT_STATUS_ADD &&
4670 status != GOT_STATUS_DELETE &&
4671 status != GOT_STATUS_CONFLICT)
4672 return NULL;
4675 if (!a->header_shown) {
4676 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4677 got_worktree_get_root_path(a->worktree));
4678 printf("commit - %s\n", a->id_str);
4679 printf("path + %s%s\n",
4680 got_worktree_get_root_path(a->worktree),
4681 a->diff_staged ? " (staged changes)" : "");
4682 a->header_shown = 1;
4685 if (a->diff_staged) {
4686 const char *label1 = NULL, *label2 = NULL;
4687 switch (staged_status) {
4688 case GOT_STATUS_MODIFY:
4689 label1 = path;
4690 label2 = path;
4691 break;
4692 case GOT_STATUS_ADD:
4693 label2 = path;
4694 break;
4695 case GOT_STATUS_DELETE:
4696 label1 = path;
4697 break;
4698 default:
4699 return got_error(GOT_ERR_FILE_STATUS);
4701 f1 = got_opentemp();
4702 if (f1 == NULL) {
4703 err = got_error_from_errno("got_opentemp");
4704 goto done;
4706 f2 = got_opentemp();
4707 if (f2 == NULL) {
4708 err = got_error_from_errno("got_opentemp");
4709 goto done;
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, f1, f2, fd1, fd2,
4722 blob_id, staged_blob_id, label1, label2, a->diff_context,
4723 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4724 goto done;
4727 fd1 = got_opentempfd();
4728 if (fd1 == -1) {
4729 err = got_error_from_errno("got_opentempfd");
4730 goto done;
4733 if (staged_status == GOT_STATUS_ADD ||
4734 staged_status == GOT_STATUS_MODIFY) {
4735 char *id_str;
4736 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4737 8192, fd1);
4738 if (err)
4739 goto done;
4740 err = got_object_id_str(&id_str, staged_blob_id);
4741 if (err)
4742 goto done;
4743 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4744 err = got_error_from_errno("asprintf");
4745 free(id_str);
4746 goto done;
4748 free(id_str);
4749 } else if (status != GOT_STATUS_ADD) {
4750 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4751 fd1);
4752 if (err)
4753 goto done;
4756 if (status != GOT_STATUS_DELETE) {
4757 if (asprintf(&abspath, "%s/%s",
4758 got_worktree_get_root_path(a->worktree), path) == -1) {
4759 err = got_error_from_errno("asprintf");
4760 goto done;
4763 if (dirfd != -1) {
4764 fd = openat(dirfd, de_name,
4765 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4766 if (fd == -1) {
4767 if (!got_err_open_nofollow_on_symlink()) {
4768 err = got_error_from_errno2("openat",
4769 abspath);
4770 goto done;
4772 err = get_symlink_target_file(&fd, dirfd,
4773 de_name, abspath);
4774 if (err)
4775 goto done;
4777 } else {
4778 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4779 if (fd == -1) {
4780 if (!got_err_open_nofollow_on_symlink()) {
4781 err = got_error_from_errno2("open",
4782 abspath);
4783 goto done;
4785 err = get_symlink_target_file(&fd, dirfd,
4786 de_name, abspath);
4787 if (err)
4788 goto done;
4791 if (fstat(fd, &sb) == -1) {
4792 err = got_error_from_errno2("fstat", abspath);
4793 goto done;
4795 f2 = fdopen(fd, "r");
4796 if (f2 == NULL) {
4797 err = got_error_from_errno2("fdopen", abspath);
4798 goto done;
4800 fd = -1;
4801 } else
4802 sb.st_size = 0;
4804 if (blob1) {
4805 f1 = got_opentemp();
4806 if (f1 == NULL) {
4807 err = got_error_from_errno("got_opentemp");
4808 goto done;
4810 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4811 blob1);
4812 if (err)
4813 goto done;
4816 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4817 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4818 stdout);
4819 done:
4820 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4821 err = got_error_from_errno("close");
4822 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4823 err = got_error_from_errno("close");
4824 if (blob1)
4825 got_object_blob_close(blob1);
4826 if (f1 && fclose(f1) == EOF && err == NULL)
4827 err = got_error_from_errno("fclose");
4828 if (f2 && fclose(f2) == EOF && err == NULL)
4829 err = got_error_from_errno("fclose");
4830 if (fd != -1 && close(fd) == -1 && err == NULL)
4831 err = got_error_from_errno("close");
4832 free(abspath);
4833 return err;
4836 static const struct got_error *
4837 cmd_diff(int argc, char *argv[])
4839 const struct got_error *error;
4840 struct got_repository *repo = NULL;
4841 struct got_worktree *worktree = NULL;
4842 char *cwd = NULL, *repo_path = NULL;
4843 const char *commit_args[2] = { NULL, NULL };
4844 int ncommit_args = 0;
4845 struct got_object_id *ids[2] = { NULL, NULL };
4846 char *labels[2] = { NULL, NULL };
4847 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4848 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4849 int force_text_diff = 0, force_path = 0, rflag = 0;
4850 const char *errstr;
4851 struct got_reflist_head refs;
4852 struct got_pathlist_head paths;
4853 struct got_pathlist_entry *pe;
4854 FILE *f1 = NULL, *f2 = NULL;
4855 int fd1 = -1, fd2 = -1;
4856 int *pack_fds = NULL;
4858 TAILQ_INIT(&refs);
4859 TAILQ_INIT(&paths);
4861 #ifndef PROFILE
4862 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4863 NULL) == -1)
4864 err(1, "pledge");
4865 #endif
4867 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4868 switch (ch) {
4869 case 'a':
4870 force_text_diff = 1;
4871 break;
4872 case 'c':
4873 if (ncommit_args >= 2)
4874 errx(1, "too many -c options used");
4875 commit_args[ncommit_args++] = optarg;
4876 break;
4877 case 'C':
4878 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4879 &errstr);
4880 if (errstr != NULL)
4881 errx(1, "number of context lines is %s: %s",
4882 errstr, optarg);
4883 break;
4884 case 'r':
4885 repo_path = realpath(optarg, NULL);
4886 if (repo_path == NULL)
4887 return got_error_from_errno2("realpath",
4888 optarg);
4889 got_path_strip_trailing_slashes(repo_path);
4890 rflag = 1;
4891 break;
4892 case 's':
4893 diff_staged = 1;
4894 break;
4895 case 'w':
4896 ignore_whitespace = 1;
4897 break;
4898 case 'P':
4899 force_path = 1;
4900 break;
4901 default:
4902 usage_diff();
4903 /* NOTREACHED */
4907 argc -= optind;
4908 argv += optind;
4910 cwd = getcwd(NULL, 0);
4911 if (cwd == NULL) {
4912 error = got_error_from_errno("getcwd");
4913 goto done;
4916 error = got_repo_pack_fds_open(&pack_fds);
4917 if (error != NULL)
4918 goto done;
4920 if (repo_path == NULL) {
4921 error = got_worktree_open(&worktree, cwd);
4922 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4923 goto done;
4924 else
4925 error = NULL;
4926 if (worktree) {
4927 repo_path =
4928 strdup(got_worktree_get_repo_path(worktree));
4929 if (repo_path == NULL) {
4930 error = got_error_from_errno("strdup");
4931 goto done;
4933 } else {
4934 repo_path = strdup(cwd);
4935 if (repo_path == NULL) {
4936 error = got_error_from_errno("strdup");
4937 goto done;
4942 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4943 free(repo_path);
4944 if (error != NULL)
4945 goto done;
4947 if (rflag || worktree == NULL || ncommit_args > 0) {
4948 if (force_path) {
4949 error = got_error_msg(GOT_ERR_NOT_IMPL,
4950 "-P option can only be used when diffing "
4951 "a work tree");
4952 goto done;
4954 if (diff_staged) {
4955 error = got_error_msg(GOT_ERR_NOT_IMPL,
4956 "-s option can only be used when diffing "
4957 "a work tree");
4958 goto done;
4962 error = apply_unveil(got_repo_get_path(repo), 1,
4963 worktree ? got_worktree_get_root_path(worktree) : NULL);
4964 if (error)
4965 goto done;
4967 if ((!force_path && argc == 2) || ncommit_args > 0) {
4968 int obj_type = (ncommit_args > 0 ?
4969 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4970 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4971 NULL);
4972 if (error)
4973 goto done;
4974 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4975 const char *arg;
4976 if (ncommit_args > 0)
4977 arg = commit_args[i];
4978 else
4979 arg = argv[i];
4980 error = got_repo_match_object_id(&ids[i], &labels[i],
4981 arg, obj_type, &refs, repo);
4982 if (error) {
4983 if (error->code != GOT_ERR_NOT_REF &&
4984 error->code != GOT_ERR_NO_OBJ)
4985 goto done;
4986 if (ncommit_args > 0)
4987 goto done;
4988 error = NULL;
4989 break;
4994 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4995 struct print_diff_arg arg;
4996 char *id_str;
4998 if (worktree == NULL) {
4999 if (argc == 2 && ids[0] == NULL) {
5000 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5001 goto done;
5002 } else if (argc == 2 && ids[1] == NULL) {
5003 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5004 goto done;
5005 } else if (argc > 0) {
5006 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5007 "%s", "specified paths cannot be resolved");
5008 goto done;
5009 } else {
5010 error = got_error(GOT_ERR_NOT_WORKTREE);
5011 goto done;
5015 error = get_worktree_paths_from_argv(&paths, argc, argv,
5016 worktree);
5017 if (error)
5018 goto done;
5020 error = got_object_id_str(&id_str,
5021 got_worktree_get_base_commit_id(worktree));
5022 if (error)
5023 goto done;
5024 arg.repo = repo;
5025 arg.worktree = worktree;
5026 arg.diff_context = diff_context;
5027 arg.id_str = id_str;
5028 arg.header_shown = 0;
5029 arg.diff_staged = diff_staged;
5030 arg.ignore_whitespace = ignore_whitespace;
5031 arg.force_text_diff = force_text_diff;
5033 error = got_worktree_status(worktree, &paths, repo, 0,
5034 print_diff, &arg, check_cancelled, NULL);
5035 free(id_str);
5036 goto done;
5039 if (ncommit_args == 1) {
5040 struct got_commit_object *commit;
5041 error = got_object_open_as_commit(&commit, repo, ids[0]);
5042 if (error)
5043 goto done;
5045 labels[1] = labels[0];
5046 ids[1] = ids[0];
5047 if (got_object_commit_get_nparents(commit) > 0) {
5048 const struct got_object_id_queue *pids;
5049 struct got_object_qid *pid;
5050 pids = got_object_commit_get_parent_ids(commit);
5051 pid = STAILQ_FIRST(pids);
5052 ids[0] = got_object_id_dup(&pid->id);
5053 if (ids[0] == NULL) {
5054 error = got_error_from_errno(
5055 "got_object_id_dup");
5056 got_object_commit_close(commit);
5057 goto done;
5059 error = got_object_id_str(&labels[0], ids[0]);
5060 if (error) {
5061 got_object_commit_close(commit);
5062 goto done;
5064 } else {
5065 ids[0] = NULL;
5066 labels[0] = strdup("/dev/null");
5067 if (labels[0] == NULL) {
5068 error = got_error_from_errno("strdup");
5069 got_object_commit_close(commit);
5070 goto done;
5074 got_object_commit_close(commit);
5077 if (ncommit_args == 0 && argc > 2) {
5078 error = got_error_msg(GOT_ERR_BAD_PATH,
5079 "path arguments cannot be used when diffing two objects");
5080 goto done;
5083 if (ids[0]) {
5084 error = got_object_get_type(&type1, repo, ids[0]);
5085 if (error)
5086 goto done;
5089 error = got_object_get_type(&type2, repo, ids[1]);
5090 if (error)
5091 goto done;
5092 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5093 error = got_error(GOT_ERR_OBJ_TYPE);
5094 goto done;
5096 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5097 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5098 "path arguments cannot be used when diffing blobs");
5099 goto done;
5102 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5103 char *in_repo_path;
5104 struct got_pathlist_entry *new;
5105 if (worktree) {
5106 const char *prefix;
5107 char *p;
5108 error = got_worktree_resolve_path(&p, worktree,
5109 argv[i]);
5110 if (error)
5111 goto done;
5112 prefix = got_worktree_get_path_prefix(worktree);
5113 while (prefix[0] == '/')
5114 prefix++;
5115 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5116 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5117 p) == -1) {
5118 error = got_error_from_errno("asprintf");
5119 free(p);
5120 goto done;
5122 free(p);
5123 } else {
5124 char *mapped_path, *s;
5125 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5126 if (error)
5127 goto done;
5128 s = mapped_path;
5129 while (s[0] == '/')
5130 s++;
5131 in_repo_path = strdup(s);
5132 if (in_repo_path == NULL) {
5133 error = got_error_from_errno("asprintf");
5134 free(mapped_path);
5135 goto done;
5137 free(mapped_path);
5140 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5141 if (error || new == NULL /* duplicate */)
5142 free(in_repo_path);
5143 if (error)
5144 goto done;
5147 if (worktree) {
5148 /* Release work tree lock. */
5149 got_worktree_close(worktree);
5150 worktree = NULL;
5153 f1 = got_opentemp();
5154 if (f1 == NULL) {
5155 error = got_error_from_errno("got_opentemp");
5156 goto done;
5159 f2 = got_opentemp();
5160 if (f2 == NULL) {
5161 error = got_error_from_errno("got_opentemp");
5162 goto done;
5165 fd1 = got_opentempfd();
5166 if (fd1 == -1) {
5167 error = got_error_from_errno("got_opentempfd");
5168 goto done;
5171 fd2 = got_opentempfd();
5172 if (fd2 == -1) {
5173 error = got_error_from_errno("got_opentempfd");
5174 goto done;
5177 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5178 case GOT_OBJ_TYPE_BLOB:
5179 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5180 fd1, fd2, ids[0], ids[1], NULL, NULL, diff_context,
5181 ignore_whitespace, force_text_diff, repo, stdout);
5182 break;
5183 case GOT_OBJ_TYPE_TREE:
5184 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5185 ids[0], ids[1], &paths, "", "", diff_context,
5186 ignore_whitespace, force_text_diff, repo, stdout);
5187 break;
5188 case GOT_OBJ_TYPE_COMMIT:
5189 printf("diff %s %s\n", labels[0], labels[1]);
5190 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5191 fd1, fd2, ids[0], ids[1], &paths, diff_context,
5192 ignore_whitespace, force_text_diff, repo, stdout);
5193 break;
5194 default:
5195 error = got_error(GOT_ERR_OBJ_TYPE);
5197 done:
5198 free(labels[0]);
5199 free(labels[1]);
5200 free(ids[0]);
5201 free(ids[1]);
5202 if (worktree)
5203 got_worktree_close(worktree);
5204 if (repo) {
5205 const struct got_error *close_err = got_repo_close(repo);
5206 if (error == NULL)
5207 error = close_err;
5209 if (pack_fds) {
5210 const struct got_error *pack_err =
5211 got_repo_pack_fds_close(pack_fds);
5212 if (error == NULL)
5213 error = pack_err;
5215 TAILQ_FOREACH(pe, &paths, entry)
5216 free((char *)pe->path);
5217 got_pathlist_free(&paths);
5218 got_ref_list_free(&refs);
5219 if (f1 && fclose(f1) == EOF && error == NULL)
5220 error = got_error_from_errno("fclose");
5221 if (f2 && fclose(f2) == EOF && error == NULL)
5222 error = got_error_from_errno("fclose");
5223 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5224 error = got_error_from_errno("close");
5225 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5226 error = got_error_from_errno("close");
5227 return error;
5230 __dead static void
5231 usage_blame(void)
5233 fprintf(stderr,
5234 "usage: %s blame [-c commit] [-r repository-path] path\n",
5235 getprogname());
5236 exit(1);
5239 struct blame_line {
5240 int annotated;
5241 char *id_str;
5242 char *committer;
5243 char datebuf[11]; /* YYYY-MM-DD + NUL */
5246 struct blame_cb_args {
5247 struct blame_line *lines;
5248 int nlines;
5249 int nlines_prec;
5250 int lineno_cur;
5251 off_t *line_offsets;
5252 FILE *f;
5253 struct got_repository *repo;
5256 static const struct got_error *
5257 blame_cb(void *arg, int nlines, int lineno,
5258 struct got_commit_object *commit, struct got_object_id *id)
5260 const struct got_error *err = NULL;
5261 struct blame_cb_args *a = arg;
5262 struct blame_line *bline;
5263 char *line = NULL;
5264 size_t linesize = 0;
5265 off_t offset;
5266 struct tm tm;
5267 time_t committer_time;
5269 if (nlines != a->nlines ||
5270 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5271 return got_error(GOT_ERR_RANGE);
5273 if (sigint_received)
5274 return got_error(GOT_ERR_ITER_COMPLETED);
5276 if (lineno == -1)
5277 return NULL; /* no change in this commit */
5279 /* Annotate this line. */
5280 bline = &a->lines[lineno - 1];
5281 if (bline->annotated)
5282 return NULL;
5283 err = got_object_id_str(&bline->id_str, id);
5284 if (err)
5285 return err;
5287 bline->committer = strdup(got_object_commit_get_committer(commit));
5288 if (bline->committer == NULL) {
5289 err = got_error_from_errno("strdup");
5290 goto done;
5293 committer_time = got_object_commit_get_committer_time(commit);
5294 if (gmtime_r(&committer_time, &tm) == NULL)
5295 return got_error_from_errno("gmtime_r");
5296 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5297 &tm) == 0) {
5298 err = got_error(GOT_ERR_NO_SPACE);
5299 goto done;
5301 bline->annotated = 1;
5303 /* Print lines annotated so far. */
5304 bline = &a->lines[a->lineno_cur - 1];
5305 if (!bline->annotated)
5306 goto done;
5308 offset = a->line_offsets[a->lineno_cur - 1];
5309 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5310 err = got_error_from_errno("fseeko");
5311 goto done;
5314 while (bline->annotated) {
5315 char *smallerthan, *at, *nl, *committer;
5316 size_t len;
5318 if (getline(&line, &linesize, a->f) == -1) {
5319 if (ferror(a->f))
5320 err = got_error_from_errno("getline");
5321 break;
5324 committer = bline->committer;
5325 smallerthan = strchr(committer, '<');
5326 if (smallerthan && smallerthan[1] != '\0')
5327 committer = smallerthan + 1;
5328 at = strchr(committer, '@');
5329 if (at)
5330 *at = '\0';
5331 len = strlen(committer);
5332 if (len >= 9)
5333 committer[8] = '\0';
5335 nl = strchr(line, '\n');
5336 if (nl)
5337 *nl = '\0';
5338 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5339 bline->id_str, bline->datebuf, committer, line);
5341 a->lineno_cur++;
5342 bline = &a->lines[a->lineno_cur - 1];
5344 done:
5345 free(line);
5346 return err;
5349 static const struct got_error *
5350 cmd_blame(int argc, char *argv[])
5352 const struct got_error *error;
5353 struct got_repository *repo = NULL;
5354 struct got_worktree *worktree = NULL;
5355 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5356 char *link_target = NULL;
5357 struct got_object_id *obj_id = NULL;
5358 struct got_object_id *commit_id = NULL;
5359 struct got_commit_object *commit = NULL;
5360 struct got_blob_object *blob = NULL;
5361 char *commit_id_str = NULL;
5362 struct blame_cb_args bca;
5363 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5364 off_t filesize;
5365 int *pack_fds = NULL;
5366 FILE *f1 = NULL, *f2 = NULL;
5368 fd1 = got_opentempfd();
5369 if (fd1 == -1)
5370 return got_error_from_errno("got_opentempfd");
5372 memset(&bca, 0, sizeof(bca));
5374 #ifndef PROFILE
5375 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5376 NULL) == -1)
5377 err(1, "pledge");
5378 #endif
5380 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5381 switch (ch) {
5382 case 'c':
5383 commit_id_str = optarg;
5384 break;
5385 case 'r':
5386 repo_path = realpath(optarg, NULL);
5387 if (repo_path == NULL)
5388 return got_error_from_errno2("realpath",
5389 optarg);
5390 got_path_strip_trailing_slashes(repo_path);
5391 break;
5392 default:
5393 usage_blame();
5394 /* NOTREACHED */
5398 argc -= optind;
5399 argv += optind;
5401 if (argc == 1)
5402 path = argv[0];
5403 else
5404 usage_blame();
5406 cwd = getcwd(NULL, 0);
5407 if (cwd == NULL) {
5408 error = got_error_from_errno("getcwd");
5409 goto done;
5412 error = got_repo_pack_fds_open(&pack_fds);
5413 if (error != NULL)
5414 goto done;
5416 if (repo_path == NULL) {
5417 error = got_worktree_open(&worktree, cwd);
5418 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5419 goto done;
5420 else
5421 error = NULL;
5422 if (worktree) {
5423 repo_path =
5424 strdup(got_worktree_get_repo_path(worktree));
5425 if (repo_path == NULL) {
5426 error = got_error_from_errno("strdup");
5427 if (error)
5428 goto done;
5430 } else {
5431 repo_path = strdup(cwd);
5432 if (repo_path == NULL) {
5433 error = got_error_from_errno("strdup");
5434 goto done;
5439 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5440 if (error != NULL)
5441 goto done;
5443 if (worktree) {
5444 const char *prefix = got_worktree_get_path_prefix(worktree);
5445 char *p;
5447 error = got_worktree_resolve_path(&p, worktree, path);
5448 if (error)
5449 goto done;
5450 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5451 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5452 p) == -1) {
5453 error = got_error_from_errno("asprintf");
5454 free(p);
5455 goto done;
5457 free(p);
5458 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5459 } else {
5460 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5461 if (error)
5462 goto done;
5463 error = got_repo_map_path(&in_repo_path, repo, path);
5465 if (error)
5466 goto done;
5468 if (commit_id_str == NULL) {
5469 struct got_reference *head_ref;
5470 error = got_ref_open(&head_ref, repo, worktree ?
5471 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5472 if (error != NULL)
5473 goto done;
5474 error = got_ref_resolve(&commit_id, repo, head_ref);
5475 got_ref_close(head_ref);
5476 if (error != NULL)
5477 goto done;
5478 } else {
5479 struct got_reflist_head refs;
5480 TAILQ_INIT(&refs);
5481 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5482 NULL);
5483 if (error)
5484 goto done;
5485 error = got_repo_match_object_id(&commit_id, NULL,
5486 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5487 got_ref_list_free(&refs);
5488 if (error)
5489 goto done;
5492 if (worktree) {
5493 /* Release work tree lock. */
5494 got_worktree_close(worktree);
5495 worktree = NULL;
5498 error = got_object_open_as_commit(&commit, repo, commit_id);
5499 if (error)
5500 goto done;
5502 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5503 commit, repo);
5504 if (error)
5505 goto done;
5507 error = got_object_id_by_path(&obj_id, repo, commit,
5508 link_target ? link_target : in_repo_path);
5509 if (error)
5510 goto done;
5512 error = got_object_get_type(&obj_type, repo, obj_id);
5513 if (error)
5514 goto done;
5516 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5517 error = got_error_path(link_target ? link_target : in_repo_path,
5518 GOT_ERR_OBJ_TYPE);
5519 goto done;
5522 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5523 if (error)
5524 goto done;
5525 bca.f = got_opentemp();
5526 if (bca.f == NULL) {
5527 error = got_error_from_errno("got_opentemp");
5528 goto done;
5530 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5531 &bca.line_offsets, bca.f, blob);
5532 if (error || bca.nlines == 0)
5533 goto done;
5535 /* Don't include \n at EOF in the blame line count. */
5536 if (bca.line_offsets[bca.nlines - 1] == filesize)
5537 bca.nlines--;
5539 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5540 if (bca.lines == NULL) {
5541 error = got_error_from_errno("calloc");
5542 goto done;
5544 bca.lineno_cur = 1;
5545 bca.nlines_prec = 0;
5546 i = bca.nlines;
5547 while (i > 0) {
5548 i /= 10;
5549 bca.nlines_prec++;
5551 bca.repo = repo;
5553 fd2 = got_opentempfd();
5554 if (fd2 == -1) {
5555 error = got_error_from_errno("got_opentempfd");
5556 goto done;
5558 fd3 = got_opentempfd();
5559 if (fd3 == -1) {
5560 error = got_error_from_errno("got_opentempfd");
5561 goto done;
5563 f1 = got_opentemp();
5564 if (f1 == NULL) {
5565 error = got_error_from_errno("got_opentemp");
5566 goto done;
5568 f2 = got_opentemp();
5569 if (f2 == NULL) {
5570 error = got_error_from_errno("got_opentemp");
5571 goto done;
5573 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5574 repo, blame_cb, &bca, check_cancelled, NULL, fd2, fd3, f1, f2);
5575 done:
5576 free(in_repo_path);
5577 free(link_target);
5578 free(repo_path);
5579 free(cwd);
5580 free(commit_id);
5581 free(obj_id);
5582 if (commit)
5583 got_object_commit_close(commit);
5585 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5586 error = got_error_from_errno("close");
5587 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5588 error = got_error_from_errno("close");
5589 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5590 error = got_error_from_errno("close");
5591 if (f1 && fclose(f1) == EOF && error == NULL)
5592 error = got_error_from_errno("fclose");
5593 if (f2 && fclose(f2) == EOF && error == NULL)
5594 error = got_error_from_errno("fclose");
5596 if (blob)
5597 got_object_blob_close(blob);
5598 if (worktree)
5599 got_worktree_close(worktree);
5600 if (repo) {
5601 const struct got_error *close_err = got_repo_close(repo);
5602 if (error == NULL)
5603 error = close_err;
5605 if (pack_fds) {
5606 const struct got_error *pack_err =
5607 got_repo_pack_fds_close(pack_fds);
5608 if (error == NULL)
5609 error = pack_err;
5611 if (bca.lines) {
5612 for (i = 0; i < bca.nlines; i++) {
5613 struct blame_line *bline = &bca.lines[i];
5614 free(bline->id_str);
5615 free(bline->committer);
5617 free(bca.lines);
5619 free(bca.line_offsets);
5620 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5621 error = got_error_from_errno("fclose");
5622 return error;
5625 __dead static void
5626 usage_tree(void)
5628 fprintf(stderr,
5629 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5630 getprogname());
5631 exit(1);
5634 static const struct got_error *
5635 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5636 const char *root_path, struct got_repository *repo)
5638 const struct got_error *err = NULL;
5639 int is_root_path = (strcmp(path, root_path) == 0);
5640 const char *modestr = "";
5641 mode_t mode = got_tree_entry_get_mode(te);
5642 char *link_target = NULL;
5644 path += strlen(root_path);
5645 while (path[0] == '/')
5646 path++;
5648 if (got_object_tree_entry_is_submodule(te))
5649 modestr = "$";
5650 else if (S_ISLNK(mode)) {
5651 int i;
5653 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5654 if (err)
5655 return err;
5656 for (i = 0; i < strlen(link_target); i++) {
5657 if (!isprint((unsigned char)link_target[i]))
5658 link_target[i] = '?';
5661 modestr = "@";
5663 else if (S_ISDIR(mode))
5664 modestr = "/";
5665 else if (mode & S_IXUSR)
5666 modestr = "*";
5668 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5669 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5670 link_target ? " -> ": "", link_target ? link_target : "");
5672 free(link_target);
5673 return NULL;
5676 static const struct got_error *
5677 print_tree(const char *path, struct got_commit_object *commit,
5678 int show_ids, int recurse, const char *root_path,
5679 struct got_repository *repo)
5681 const struct got_error *err = NULL;
5682 struct got_object_id *tree_id = NULL;
5683 struct got_tree_object *tree = NULL;
5684 int nentries, i;
5686 err = got_object_id_by_path(&tree_id, repo, commit, path);
5687 if (err)
5688 goto done;
5690 err = got_object_open_as_tree(&tree, repo, tree_id);
5691 if (err)
5692 goto done;
5693 nentries = got_object_tree_get_nentries(tree);
5694 for (i = 0; i < nentries; i++) {
5695 struct got_tree_entry *te;
5696 char *id = NULL;
5698 if (sigint_received || sigpipe_received)
5699 break;
5701 te = got_object_tree_get_entry(tree, i);
5702 if (show_ids) {
5703 char *id_str;
5704 err = got_object_id_str(&id_str,
5705 got_tree_entry_get_id(te));
5706 if (err)
5707 goto done;
5708 if (asprintf(&id, "%s ", id_str) == -1) {
5709 err = got_error_from_errno("asprintf");
5710 free(id_str);
5711 goto done;
5713 free(id_str);
5715 err = print_entry(te, id, path, root_path, repo);
5716 free(id);
5717 if (err)
5718 goto done;
5720 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5721 char *child_path;
5722 if (asprintf(&child_path, "%s%s%s", path,
5723 path[0] == '/' && path[1] == '\0' ? "" : "/",
5724 got_tree_entry_get_name(te)) == -1) {
5725 err = got_error_from_errno("asprintf");
5726 goto done;
5728 err = print_tree(child_path, commit, show_ids, 1,
5729 root_path, repo);
5730 free(child_path);
5731 if (err)
5732 goto done;
5735 done:
5736 if (tree)
5737 got_object_tree_close(tree);
5738 free(tree_id);
5739 return err;
5742 static const struct got_error *
5743 cmd_tree(int argc, char *argv[])
5745 const struct got_error *error;
5746 struct got_repository *repo = NULL;
5747 struct got_worktree *worktree = NULL;
5748 const char *path, *refname = NULL;
5749 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5750 struct got_object_id *commit_id = NULL;
5751 struct got_commit_object *commit = NULL;
5752 char *commit_id_str = NULL;
5753 int show_ids = 0, recurse = 0;
5754 int ch;
5755 int *pack_fds = NULL;
5757 #ifndef PROFILE
5758 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5759 NULL) == -1)
5760 err(1, "pledge");
5761 #endif
5763 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5764 switch (ch) {
5765 case 'c':
5766 commit_id_str = optarg;
5767 break;
5768 case 'r':
5769 repo_path = realpath(optarg, NULL);
5770 if (repo_path == NULL)
5771 return got_error_from_errno2("realpath",
5772 optarg);
5773 got_path_strip_trailing_slashes(repo_path);
5774 break;
5775 case 'i':
5776 show_ids = 1;
5777 break;
5778 case 'R':
5779 recurse = 1;
5780 break;
5781 default:
5782 usage_tree();
5783 /* NOTREACHED */
5787 argc -= optind;
5788 argv += optind;
5790 if (argc == 1)
5791 path = argv[0];
5792 else if (argc > 1)
5793 usage_tree();
5794 else
5795 path = NULL;
5797 cwd = getcwd(NULL, 0);
5798 if (cwd == NULL) {
5799 error = got_error_from_errno("getcwd");
5800 goto done;
5803 error = got_repo_pack_fds_open(&pack_fds);
5804 if (error != NULL)
5805 goto done;
5807 if (repo_path == NULL) {
5808 error = got_worktree_open(&worktree, cwd);
5809 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5810 goto done;
5811 else
5812 error = NULL;
5813 if (worktree) {
5814 repo_path =
5815 strdup(got_worktree_get_repo_path(worktree));
5816 if (repo_path == NULL)
5817 error = got_error_from_errno("strdup");
5818 if (error)
5819 goto done;
5820 } else {
5821 repo_path = strdup(cwd);
5822 if (repo_path == NULL) {
5823 error = got_error_from_errno("strdup");
5824 goto done;
5829 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5830 if (error != NULL)
5831 goto done;
5833 if (worktree) {
5834 const char *prefix = got_worktree_get_path_prefix(worktree);
5835 char *p;
5837 if (path == NULL)
5838 path = "";
5839 error = got_worktree_resolve_path(&p, worktree, path);
5840 if (error)
5841 goto done;
5842 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5843 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5844 p) == -1) {
5845 error = got_error_from_errno("asprintf");
5846 free(p);
5847 goto done;
5849 free(p);
5850 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5851 if (error)
5852 goto done;
5853 } else {
5854 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5855 if (error)
5856 goto done;
5857 if (path == NULL)
5858 path = "/";
5859 error = got_repo_map_path(&in_repo_path, repo, path);
5860 if (error != NULL)
5861 goto done;
5864 if (commit_id_str == NULL) {
5865 struct got_reference *head_ref;
5866 if (worktree)
5867 refname = got_worktree_get_head_ref_name(worktree);
5868 else
5869 refname = GOT_REF_HEAD;
5870 error = got_ref_open(&head_ref, repo, refname, 0);
5871 if (error != NULL)
5872 goto done;
5873 error = got_ref_resolve(&commit_id, repo, head_ref);
5874 got_ref_close(head_ref);
5875 if (error != NULL)
5876 goto done;
5877 } else {
5878 struct got_reflist_head refs;
5879 TAILQ_INIT(&refs);
5880 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5881 NULL);
5882 if (error)
5883 goto done;
5884 error = got_repo_match_object_id(&commit_id, NULL,
5885 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5886 got_ref_list_free(&refs);
5887 if (error)
5888 goto done;
5891 if (worktree) {
5892 /* Release work tree lock. */
5893 got_worktree_close(worktree);
5894 worktree = NULL;
5897 error = got_object_open_as_commit(&commit, repo, commit_id);
5898 if (error)
5899 goto done;
5901 error = print_tree(in_repo_path, commit, show_ids, recurse,
5902 in_repo_path, repo);
5903 done:
5904 free(in_repo_path);
5905 free(repo_path);
5906 free(cwd);
5907 free(commit_id);
5908 if (commit)
5909 got_object_commit_close(commit);
5910 if (worktree)
5911 got_worktree_close(worktree);
5912 if (repo) {
5913 const struct got_error *close_err = got_repo_close(repo);
5914 if (error == NULL)
5915 error = close_err;
5917 if (pack_fds) {
5918 const struct got_error *pack_err =
5919 got_repo_pack_fds_close(pack_fds);
5920 if (error == NULL)
5921 error = pack_err;
5923 return error;
5926 __dead static void
5927 usage_status(void)
5929 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5930 "[-S status-codes] [path ...]\n", getprogname());
5931 exit(1);
5934 struct got_status_arg {
5935 char *status_codes;
5936 int suppress;
5939 static const struct got_error *
5940 print_status(void *arg, unsigned char status, unsigned char staged_status,
5941 const char *path, struct got_object_id *blob_id,
5942 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5943 int dirfd, const char *de_name)
5945 struct got_status_arg *st = arg;
5947 if (status == staged_status && (status == GOT_STATUS_DELETE))
5948 status = GOT_STATUS_NO_CHANGE;
5949 if (st != NULL && st->status_codes) {
5950 size_t ncodes = strlen(st->status_codes);
5951 int i, j = 0;
5953 for (i = 0; i < ncodes ; i++) {
5954 if (st->suppress) {
5955 if (status == st->status_codes[i] ||
5956 staged_status == st->status_codes[i]) {
5957 j++;
5958 continue;
5960 } else {
5961 if (status == st->status_codes[i] ||
5962 staged_status == st->status_codes[i])
5963 break;
5967 if (st->suppress && j == 0)
5968 goto print;
5970 if (i == ncodes)
5971 return NULL;
5973 print:
5974 printf("%c%c %s\n", status, staged_status, path);
5975 return NULL;
5978 static const struct got_error *
5979 cmd_status(int argc, char *argv[])
5981 const struct got_error *error = NULL;
5982 struct got_repository *repo = NULL;
5983 struct got_worktree *worktree = NULL;
5984 struct got_status_arg st;
5985 char *cwd = NULL;
5986 struct got_pathlist_head paths;
5987 struct got_pathlist_entry *pe;
5988 int ch, i, no_ignores = 0;
5989 int *pack_fds = NULL;
5991 TAILQ_INIT(&paths);
5993 memset(&st, 0, sizeof(st));
5994 st.status_codes = NULL;
5995 st.suppress = 0;
5997 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5998 switch (ch) {
5999 case 'I':
6000 no_ignores = 1;
6001 break;
6002 case 'S':
6003 if (st.status_codes != NULL && st.suppress == 0)
6004 option_conflict('S', 's');
6005 st.suppress = 1;
6006 /* fallthrough */
6007 case 's':
6008 for (i = 0; i < strlen(optarg); i++) {
6009 switch (optarg[i]) {
6010 case GOT_STATUS_MODIFY:
6011 case GOT_STATUS_ADD:
6012 case GOT_STATUS_DELETE:
6013 case GOT_STATUS_CONFLICT:
6014 case GOT_STATUS_MISSING:
6015 case GOT_STATUS_OBSTRUCTED:
6016 case GOT_STATUS_UNVERSIONED:
6017 case GOT_STATUS_MODE_CHANGE:
6018 case GOT_STATUS_NONEXISTENT:
6019 break;
6020 default:
6021 errx(1, "invalid status code '%c'",
6022 optarg[i]);
6025 if (ch == 's' && st.suppress)
6026 option_conflict('s', 'S');
6027 st.status_codes = optarg;
6028 break;
6029 default:
6030 usage_status();
6031 /* NOTREACHED */
6035 argc -= optind;
6036 argv += optind;
6038 #ifndef PROFILE
6039 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6040 NULL) == -1)
6041 err(1, "pledge");
6042 #endif
6043 cwd = getcwd(NULL, 0);
6044 if (cwd == NULL) {
6045 error = got_error_from_errno("getcwd");
6046 goto done;
6049 error = got_repo_pack_fds_open(&pack_fds);
6050 if (error != NULL)
6051 goto done;
6053 error = got_worktree_open(&worktree, cwd);
6054 if (error) {
6055 if (error->code == GOT_ERR_NOT_WORKTREE)
6056 error = wrap_not_worktree_error(error, "status", cwd);
6057 goto done;
6060 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6061 NULL, pack_fds);
6062 if (error != NULL)
6063 goto done;
6065 error = apply_unveil(got_repo_get_path(repo), 1,
6066 got_worktree_get_root_path(worktree));
6067 if (error)
6068 goto done;
6070 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6071 if (error)
6072 goto done;
6074 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6075 print_status, &st, check_cancelled, NULL);
6076 done:
6077 if (pack_fds) {
6078 const struct got_error *pack_err =
6079 got_repo_pack_fds_close(pack_fds);
6080 if (error == NULL)
6081 error = pack_err;
6084 TAILQ_FOREACH(pe, &paths, entry)
6085 free((char *)pe->path);
6086 got_pathlist_free(&paths);
6087 free(cwd);
6088 return error;
6091 __dead static void
6092 usage_ref(void)
6094 fprintf(stderr,
6095 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6096 "[-s reference] [-d] [name]\n",
6097 getprogname());
6098 exit(1);
6101 static const struct got_error *
6102 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6104 static const struct got_error *err = NULL;
6105 struct got_reflist_head refs;
6106 struct got_reflist_entry *re;
6108 TAILQ_INIT(&refs);
6109 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6110 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6111 repo);
6112 if (err)
6113 return err;
6115 TAILQ_FOREACH(re, &refs, entry) {
6116 char *refstr;
6117 refstr = got_ref_to_str(re->ref);
6118 if (refstr == NULL) {
6119 err = got_error_from_errno("got_ref_to_str");
6120 break;
6122 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6123 free(refstr);
6126 got_ref_list_free(&refs);
6127 return err;
6130 static const struct got_error *
6131 delete_ref_by_name(struct got_repository *repo, const char *refname)
6133 const struct got_error *err;
6134 struct got_reference *ref;
6136 err = got_ref_open(&ref, repo, refname, 0);
6137 if (err)
6138 return err;
6140 err = delete_ref(repo, ref);
6141 got_ref_close(ref);
6142 return err;
6145 static const struct got_error *
6146 add_ref(struct got_repository *repo, const char *refname, const char *target)
6148 const struct got_error *err = NULL;
6149 struct got_object_id *id = NULL;
6150 struct got_reference *ref = NULL;
6151 struct got_reflist_head refs;
6154 * Don't let the user create a reference name with a leading '-'.
6155 * While technically a valid reference name, this case is usually
6156 * an unintended typo.
6158 if (refname[0] == '-')
6159 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6161 TAILQ_INIT(&refs);
6162 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6163 if (err)
6164 goto done;
6165 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6166 &refs, repo);
6167 got_ref_list_free(&refs);
6168 if (err)
6169 goto done;
6171 err = got_ref_alloc(&ref, refname, id);
6172 if (err)
6173 goto done;
6175 err = got_ref_write(ref, repo);
6176 done:
6177 if (ref)
6178 got_ref_close(ref);
6179 free(id);
6180 return err;
6183 static const struct got_error *
6184 add_symref(struct got_repository *repo, const char *refname, const char *target)
6186 const struct got_error *err = NULL;
6187 struct got_reference *ref = NULL;
6188 struct got_reference *target_ref = NULL;
6191 * Don't let the user create a reference name with a leading '-'.
6192 * While technically a valid reference name, this case is usually
6193 * an unintended typo.
6195 if (refname[0] == '-')
6196 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6198 err = got_ref_open(&target_ref, repo, target, 0);
6199 if (err)
6200 return err;
6202 err = got_ref_alloc_symref(&ref, refname, target_ref);
6203 if (err)
6204 goto done;
6206 err = got_ref_write(ref, repo);
6207 done:
6208 if (target_ref)
6209 got_ref_close(target_ref);
6210 if (ref)
6211 got_ref_close(ref);
6212 return err;
6215 static const struct got_error *
6216 cmd_ref(int argc, char *argv[])
6218 const struct got_error *error = NULL;
6219 struct got_repository *repo = NULL;
6220 struct got_worktree *worktree = NULL;
6221 char *cwd = NULL, *repo_path = NULL;
6222 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6223 const char *obj_arg = NULL, *symref_target= NULL;
6224 char *refname = NULL;
6225 int *pack_fds = NULL;
6227 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6228 switch (ch) {
6229 case 'c':
6230 obj_arg = optarg;
6231 break;
6232 case 'd':
6233 do_delete = 1;
6234 break;
6235 case 'r':
6236 repo_path = realpath(optarg, NULL);
6237 if (repo_path == NULL)
6238 return got_error_from_errno2("realpath",
6239 optarg);
6240 got_path_strip_trailing_slashes(repo_path);
6241 break;
6242 case 'l':
6243 do_list = 1;
6244 break;
6245 case 's':
6246 symref_target = optarg;
6247 break;
6248 case 't':
6249 sort_by_time = 1;
6250 break;
6251 default:
6252 usage_ref();
6253 /* NOTREACHED */
6257 if (obj_arg && do_list)
6258 option_conflict('c', 'l');
6259 if (obj_arg && do_delete)
6260 option_conflict('c', 'd');
6261 if (obj_arg && symref_target)
6262 option_conflict('c', 's');
6263 if (symref_target && do_delete)
6264 option_conflict('s', 'd');
6265 if (symref_target && do_list)
6266 option_conflict('s', 'l');
6267 if (do_delete && do_list)
6268 option_conflict('d', 'l');
6269 if (sort_by_time && !do_list)
6270 errx(1, "-t option requires -l option");
6272 argc -= optind;
6273 argv += optind;
6275 if (do_list) {
6276 if (argc != 0 && argc != 1)
6277 usage_ref();
6278 if (argc == 1) {
6279 refname = strdup(argv[0]);
6280 if (refname == NULL) {
6281 error = got_error_from_errno("strdup");
6282 goto done;
6285 } else {
6286 if (argc != 1)
6287 usage_ref();
6288 refname = strdup(argv[0]);
6289 if (refname == NULL) {
6290 error = got_error_from_errno("strdup");
6291 goto done;
6295 if (refname)
6296 got_path_strip_trailing_slashes(refname);
6298 #ifndef PROFILE
6299 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6300 "sendfd unveil", NULL) == -1)
6301 err(1, "pledge");
6302 #endif
6303 cwd = getcwd(NULL, 0);
6304 if (cwd == NULL) {
6305 error = got_error_from_errno("getcwd");
6306 goto done;
6309 error = got_repo_pack_fds_open(&pack_fds);
6310 if (error != NULL)
6311 goto done;
6313 if (repo_path == NULL) {
6314 error = got_worktree_open(&worktree, cwd);
6315 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6316 goto done;
6317 else
6318 error = NULL;
6319 if (worktree) {
6320 repo_path =
6321 strdup(got_worktree_get_repo_path(worktree));
6322 if (repo_path == NULL)
6323 error = got_error_from_errno("strdup");
6324 if (error)
6325 goto done;
6326 } else {
6327 repo_path = strdup(cwd);
6328 if (repo_path == NULL) {
6329 error = got_error_from_errno("strdup");
6330 goto done;
6335 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6336 if (error != NULL)
6337 goto done;
6339 #ifndef PROFILE
6340 if (do_list) {
6341 /* Remove "cpath" promise. */
6342 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6343 NULL) == -1)
6344 err(1, "pledge");
6346 #endif
6348 error = apply_unveil(got_repo_get_path(repo), do_list,
6349 worktree ? got_worktree_get_root_path(worktree) : NULL);
6350 if (error)
6351 goto done;
6353 if (do_list)
6354 error = list_refs(repo, refname, sort_by_time);
6355 else if (do_delete)
6356 error = delete_ref_by_name(repo, refname);
6357 else if (symref_target)
6358 error = add_symref(repo, refname, symref_target);
6359 else {
6360 if (obj_arg == NULL)
6361 usage_ref();
6362 error = add_ref(repo, refname, obj_arg);
6364 done:
6365 free(refname);
6366 if (repo) {
6367 const struct got_error *close_err = got_repo_close(repo);
6368 if (error == NULL)
6369 error = close_err;
6371 if (worktree)
6372 got_worktree_close(worktree);
6373 if (pack_fds) {
6374 const struct got_error *pack_err =
6375 got_repo_pack_fds_close(pack_fds);
6376 if (error == NULL)
6377 error = pack_err;
6379 free(cwd);
6380 free(repo_path);
6381 return error;
6384 __dead static void
6385 usage_branch(void)
6387 fprintf(stderr,
6388 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6389 "[-n] [name]\n", getprogname());
6390 exit(1);
6393 static const struct got_error *
6394 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6395 struct got_reference *ref)
6397 const struct got_error *err = NULL;
6398 const char *refname, *marker = " ";
6399 char *refstr;
6401 refname = got_ref_get_name(ref);
6402 if (worktree && strcmp(refname,
6403 got_worktree_get_head_ref_name(worktree)) == 0) {
6404 struct got_object_id *id = NULL;
6406 err = got_ref_resolve(&id, repo, ref);
6407 if (err)
6408 return err;
6409 if (got_object_id_cmp(id,
6410 got_worktree_get_base_commit_id(worktree)) == 0)
6411 marker = "* ";
6412 else
6413 marker = "~ ";
6414 free(id);
6417 if (strncmp(refname, "refs/heads/", 11) == 0)
6418 refname += 11;
6419 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6420 refname += 18;
6421 if (strncmp(refname, "refs/remotes/", 13) == 0)
6422 refname += 13;
6424 refstr = got_ref_to_str(ref);
6425 if (refstr == NULL)
6426 return got_error_from_errno("got_ref_to_str");
6428 printf("%s%s: %s\n", marker, refname, refstr);
6429 free(refstr);
6430 return NULL;
6433 static const struct got_error *
6434 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6436 const char *refname;
6438 if (worktree == NULL)
6439 return got_error(GOT_ERR_NOT_WORKTREE);
6441 refname = got_worktree_get_head_ref_name(worktree);
6443 if (strncmp(refname, "refs/heads/", 11) == 0)
6444 refname += 11;
6445 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6446 refname += 18;
6448 printf("%s\n", refname);
6450 return NULL;
6453 static const struct got_error *
6454 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6455 int sort_by_time)
6457 static const struct got_error *err = NULL;
6458 struct got_reflist_head refs;
6459 struct got_reflist_entry *re;
6460 struct got_reference *temp_ref = NULL;
6461 int rebase_in_progress, histedit_in_progress;
6463 TAILQ_INIT(&refs);
6465 if (worktree) {
6466 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6467 worktree);
6468 if (err)
6469 return err;
6471 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6472 worktree);
6473 if (err)
6474 return err;
6476 if (rebase_in_progress || histedit_in_progress) {
6477 err = got_ref_open(&temp_ref, repo,
6478 got_worktree_get_head_ref_name(worktree), 0);
6479 if (err)
6480 return err;
6481 list_branch(repo, worktree, temp_ref);
6482 got_ref_close(temp_ref);
6486 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6487 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6488 repo);
6489 if (err)
6490 return err;
6492 TAILQ_FOREACH(re, &refs, entry)
6493 list_branch(repo, worktree, re->ref);
6495 got_ref_list_free(&refs);
6497 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6498 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6499 repo);
6500 if (err)
6501 return err;
6503 TAILQ_FOREACH(re, &refs, entry)
6504 list_branch(repo, worktree, re->ref);
6506 got_ref_list_free(&refs);
6508 return NULL;
6511 static const struct got_error *
6512 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6513 const char *branch_name)
6515 const struct got_error *err = NULL;
6516 struct got_reference *ref = NULL;
6517 char *refname, *remote_refname = NULL;
6519 if (strncmp(branch_name, "refs/", 5) == 0)
6520 branch_name += 5;
6521 if (strncmp(branch_name, "heads/", 6) == 0)
6522 branch_name += 6;
6523 else if (strncmp(branch_name, "remotes/", 8) == 0)
6524 branch_name += 8;
6526 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6527 return got_error_from_errno("asprintf");
6529 if (asprintf(&remote_refname, "refs/remotes/%s",
6530 branch_name) == -1) {
6531 err = got_error_from_errno("asprintf");
6532 goto done;
6535 err = got_ref_open(&ref, repo, refname, 0);
6536 if (err) {
6537 const struct got_error *err2;
6538 if (err->code != GOT_ERR_NOT_REF)
6539 goto done;
6541 * Keep 'err' intact such that if neither branch exists
6542 * we report "refs/heads" rather than "refs/remotes" in
6543 * our error message.
6545 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6546 if (err2)
6547 goto done;
6548 err = NULL;
6551 if (worktree &&
6552 strcmp(got_worktree_get_head_ref_name(worktree),
6553 got_ref_get_name(ref)) == 0) {
6554 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6555 "will not delete this work tree's current branch");
6556 goto done;
6559 err = delete_ref(repo, ref);
6560 done:
6561 if (ref)
6562 got_ref_close(ref);
6563 free(refname);
6564 free(remote_refname);
6565 return err;
6568 static const struct got_error *
6569 add_branch(struct got_repository *repo, const char *branch_name,
6570 struct got_object_id *base_commit_id)
6572 const struct got_error *err = NULL;
6573 struct got_reference *ref = NULL;
6574 char *base_refname = NULL, *refname = NULL;
6577 * Don't let the user create a branch name with a leading '-'.
6578 * While technically a valid reference name, this case is usually
6579 * an unintended typo.
6581 if (branch_name[0] == '-')
6582 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6584 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6585 branch_name += 11;
6587 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6588 err = got_error_from_errno("asprintf");
6589 goto done;
6592 err = got_ref_open(&ref, repo, refname, 0);
6593 if (err == NULL) {
6594 err = got_error(GOT_ERR_BRANCH_EXISTS);
6595 goto done;
6596 } else if (err->code != GOT_ERR_NOT_REF)
6597 goto done;
6599 err = got_ref_alloc(&ref, refname, base_commit_id);
6600 if (err)
6601 goto done;
6603 err = got_ref_write(ref, repo);
6604 done:
6605 if (ref)
6606 got_ref_close(ref);
6607 free(base_refname);
6608 free(refname);
6609 return err;
6612 static const struct got_error *
6613 cmd_branch(int argc, char *argv[])
6615 const struct got_error *error = NULL;
6616 struct got_repository *repo = NULL;
6617 struct got_worktree *worktree = NULL;
6618 char *cwd = NULL, *repo_path = NULL;
6619 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6620 const char *delref = NULL, *commit_id_arg = NULL;
6621 struct got_reference *ref = NULL;
6622 struct got_pathlist_head paths;
6623 struct got_pathlist_entry *pe;
6624 struct got_object_id *commit_id = NULL;
6625 char *commit_id_str = NULL;
6626 int *pack_fds = NULL;
6628 TAILQ_INIT(&paths);
6630 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6631 switch (ch) {
6632 case 'c':
6633 commit_id_arg = optarg;
6634 break;
6635 case 'd':
6636 delref = optarg;
6637 break;
6638 case 'r':
6639 repo_path = realpath(optarg, NULL);
6640 if (repo_path == NULL)
6641 return got_error_from_errno2("realpath",
6642 optarg);
6643 got_path_strip_trailing_slashes(repo_path);
6644 break;
6645 case 'l':
6646 do_list = 1;
6647 break;
6648 case 'n':
6649 do_update = 0;
6650 break;
6651 case 't':
6652 sort_by_time = 1;
6653 break;
6654 default:
6655 usage_branch();
6656 /* NOTREACHED */
6660 if (do_list && delref)
6661 option_conflict('l', 'd');
6662 if (sort_by_time && !do_list)
6663 errx(1, "-t option requires -l option");
6665 argc -= optind;
6666 argv += optind;
6668 if (!do_list && !delref && argc == 0)
6669 do_show = 1;
6671 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6672 errx(1, "-c option can only be used when creating a branch");
6674 if (do_list || delref) {
6675 if (argc > 0)
6676 usage_branch();
6677 } else if (!do_show && argc != 1)
6678 usage_branch();
6680 #ifndef PROFILE
6681 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6682 "sendfd unveil", NULL) == -1)
6683 err(1, "pledge");
6684 #endif
6685 cwd = getcwd(NULL, 0);
6686 if (cwd == NULL) {
6687 error = got_error_from_errno("getcwd");
6688 goto done;
6691 error = got_repo_pack_fds_open(&pack_fds);
6692 if (error != NULL)
6693 goto done;
6695 if (repo_path == NULL) {
6696 error = got_worktree_open(&worktree, cwd);
6697 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6698 goto done;
6699 else
6700 error = NULL;
6701 if (worktree) {
6702 repo_path =
6703 strdup(got_worktree_get_repo_path(worktree));
6704 if (repo_path == NULL)
6705 error = got_error_from_errno("strdup");
6706 if (error)
6707 goto done;
6708 } else {
6709 repo_path = strdup(cwd);
6710 if (repo_path == NULL) {
6711 error = got_error_from_errno("strdup");
6712 goto done;
6717 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6718 if (error != NULL)
6719 goto done;
6721 #ifndef PROFILE
6722 if (do_list || do_show) {
6723 /* Remove "cpath" promise. */
6724 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6725 NULL) == -1)
6726 err(1, "pledge");
6728 #endif
6730 error = apply_unveil(got_repo_get_path(repo), do_list,
6731 worktree ? got_worktree_get_root_path(worktree) : NULL);
6732 if (error)
6733 goto done;
6735 if (do_show)
6736 error = show_current_branch(repo, worktree);
6737 else if (do_list)
6738 error = list_branches(repo, worktree, sort_by_time);
6739 else if (delref)
6740 error = delete_branch(repo, worktree, delref);
6741 else {
6742 struct got_reflist_head refs;
6743 TAILQ_INIT(&refs);
6744 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6745 NULL);
6746 if (error)
6747 goto done;
6748 if (commit_id_arg == NULL)
6749 commit_id_arg = worktree ?
6750 got_worktree_get_head_ref_name(worktree) :
6751 GOT_REF_HEAD;
6752 error = got_repo_match_object_id(&commit_id, NULL,
6753 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6754 got_ref_list_free(&refs);
6755 if (error)
6756 goto done;
6757 error = add_branch(repo, argv[0], commit_id);
6758 if (error)
6759 goto done;
6760 if (worktree && do_update) {
6761 struct got_update_progress_arg upa;
6762 char *branch_refname = NULL;
6764 error = got_object_id_str(&commit_id_str, commit_id);
6765 if (error)
6766 goto done;
6767 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6768 worktree);
6769 if (error)
6770 goto done;
6771 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6772 == -1) {
6773 error = got_error_from_errno("asprintf");
6774 goto done;
6776 error = got_ref_open(&ref, repo, branch_refname, 0);
6777 free(branch_refname);
6778 if (error)
6779 goto done;
6780 error = switch_head_ref(ref, commit_id, worktree,
6781 repo);
6782 if (error)
6783 goto done;
6784 error = got_worktree_set_base_commit_id(worktree, repo,
6785 commit_id);
6786 if (error)
6787 goto done;
6788 memset(&upa, 0, sizeof(upa));
6789 error = got_worktree_checkout_files(worktree, &paths,
6790 repo, update_progress, &upa, check_cancelled,
6791 NULL);
6792 if (error)
6793 goto done;
6794 if (upa.did_something) {
6795 printf("Updated to %s: %s\n",
6796 got_worktree_get_head_ref_name(worktree),
6797 commit_id_str);
6799 print_update_progress_stats(&upa);
6802 done:
6803 if (ref)
6804 got_ref_close(ref);
6805 if (repo) {
6806 const struct got_error *close_err = got_repo_close(repo);
6807 if (error == NULL)
6808 error = close_err;
6810 if (worktree)
6811 got_worktree_close(worktree);
6812 if (pack_fds) {
6813 const struct got_error *pack_err =
6814 got_repo_pack_fds_close(pack_fds);
6815 if (error == NULL)
6816 error = pack_err;
6818 free(cwd);
6819 free(repo_path);
6820 free(commit_id);
6821 free(commit_id_str);
6822 TAILQ_FOREACH(pe, &paths, entry)
6823 free((char *)pe->path);
6824 got_pathlist_free(&paths);
6825 return error;
6829 __dead static void
6830 usage_tag(void)
6832 fprintf(stderr,
6833 "usage: %s tag [-c commit] [-r repository] [-l] "
6834 "[-m message] name\n", getprogname());
6835 exit(1);
6838 #if 0
6839 static const struct got_error *
6840 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6842 const struct got_error *err = NULL;
6843 struct got_reflist_entry *re, *se, *new;
6844 struct got_object_id *re_id, *se_id;
6845 struct got_tag_object *re_tag, *se_tag;
6846 time_t re_time, se_time;
6848 STAILQ_FOREACH(re, tags, entry) {
6849 se = STAILQ_FIRST(sorted);
6850 if (se == NULL) {
6851 err = got_reflist_entry_dup(&new, re);
6852 if (err)
6853 return err;
6854 STAILQ_INSERT_HEAD(sorted, new, entry);
6855 continue;
6856 } else {
6857 err = got_ref_resolve(&re_id, repo, re->ref);
6858 if (err)
6859 break;
6860 err = got_object_open_as_tag(&re_tag, repo, re_id);
6861 free(re_id);
6862 if (err)
6863 break;
6864 re_time = got_object_tag_get_tagger_time(re_tag);
6865 got_object_tag_close(re_tag);
6868 while (se) {
6869 err = got_ref_resolve(&se_id, repo, re->ref);
6870 if (err)
6871 break;
6872 err = got_object_open_as_tag(&se_tag, repo, se_id);
6873 free(se_id);
6874 if (err)
6875 break;
6876 se_time = got_object_tag_get_tagger_time(se_tag);
6877 got_object_tag_close(se_tag);
6879 if (se_time > re_time) {
6880 err = got_reflist_entry_dup(&new, re);
6881 if (err)
6882 return err;
6883 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6884 break;
6886 se = STAILQ_NEXT(se, entry);
6887 continue;
6890 done:
6891 return err;
6893 #endif
6895 static const struct got_error *
6896 get_tag_refname(char **refname, const char *tag_name)
6898 const struct got_error *err;
6900 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6901 *refname = strdup(tag_name);
6902 if (*refname == NULL)
6903 return got_error_from_errno("strdup");
6904 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6905 err = got_error_from_errno("asprintf");
6906 *refname = NULL;
6907 return err;
6910 return NULL;
6913 static const struct got_error *
6914 list_tags(struct got_repository *repo, const char *tag_name)
6916 static const struct got_error *err = NULL;
6917 struct got_reflist_head refs;
6918 struct got_reflist_entry *re;
6919 char *wanted_refname = NULL;
6921 TAILQ_INIT(&refs);
6923 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6924 if (err)
6925 return err;
6927 if (tag_name) {
6928 struct got_reference *ref;
6929 err = get_tag_refname(&wanted_refname, tag_name);
6930 if (err)
6931 goto done;
6932 /* Wanted tag reference should exist. */
6933 err = got_ref_open(&ref, repo, wanted_refname, 0);
6934 if (err)
6935 goto done;
6936 got_ref_close(ref);
6939 TAILQ_FOREACH(re, &refs, entry) {
6940 const char *refname;
6941 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6942 char datebuf[26];
6943 const char *tagger;
6944 time_t tagger_time;
6945 struct got_object_id *id;
6946 struct got_tag_object *tag;
6947 struct got_commit_object *commit = NULL;
6949 refname = got_ref_get_name(re->ref);
6950 if (strncmp(refname, "refs/tags/", 10) != 0 ||
6951 (wanted_refname && strcmp(refname, wanted_refname) != 0))
6952 continue;
6953 refname += 10;
6954 refstr = got_ref_to_str(re->ref);
6955 if (refstr == NULL) {
6956 err = got_error_from_errno("got_ref_to_str");
6957 break;
6959 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6960 free(refstr);
6962 err = got_ref_resolve(&id, repo, re->ref);
6963 if (err)
6964 break;
6965 err = got_object_open_as_tag(&tag, repo, id);
6966 if (err) {
6967 if (err->code != GOT_ERR_OBJ_TYPE) {
6968 free(id);
6969 break;
6971 /* "lightweight" tag */
6972 err = got_object_open_as_commit(&commit, repo, id);
6973 if (err) {
6974 free(id);
6975 break;
6977 tagger = got_object_commit_get_committer(commit);
6978 tagger_time =
6979 got_object_commit_get_committer_time(commit);
6980 err = got_object_id_str(&id_str, id);
6981 free(id);
6982 if (err)
6983 break;
6984 } else {
6985 free(id);
6986 tagger = got_object_tag_get_tagger(tag);
6987 tagger_time = got_object_tag_get_tagger_time(tag);
6988 err = got_object_id_str(&id_str,
6989 got_object_tag_get_object_id(tag));
6990 if (err)
6991 break;
6993 printf("from: %s\n", tagger);
6994 datestr = get_datestr(&tagger_time, datebuf);
6995 if (datestr)
6996 printf("date: %s UTC\n", datestr);
6997 if (commit)
6998 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6999 else {
7000 switch (got_object_tag_get_object_type(tag)) {
7001 case GOT_OBJ_TYPE_BLOB:
7002 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7003 id_str);
7004 break;
7005 case GOT_OBJ_TYPE_TREE:
7006 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7007 id_str);
7008 break;
7009 case GOT_OBJ_TYPE_COMMIT:
7010 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7011 id_str);
7012 break;
7013 case GOT_OBJ_TYPE_TAG:
7014 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7015 id_str);
7016 break;
7017 default:
7018 break;
7021 free(id_str);
7022 if (commit) {
7023 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7024 if (err)
7025 break;
7026 got_object_commit_close(commit);
7027 } else {
7028 tagmsg0 = strdup(got_object_tag_get_message(tag));
7029 got_object_tag_close(tag);
7030 if (tagmsg0 == NULL) {
7031 err = got_error_from_errno("strdup");
7032 break;
7036 tagmsg = tagmsg0;
7037 do {
7038 line = strsep(&tagmsg, "\n");
7039 if (line)
7040 printf(" %s\n", line);
7041 } while (line);
7042 free(tagmsg0);
7044 done:
7045 got_ref_list_free(&refs);
7046 free(wanted_refname);
7047 return err;
7050 static const struct got_error *
7051 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7052 const char *tag_name, const char *repo_path)
7054 const struct got_error *err = NULL;
7055 char *template = NULL, *initial_content = NULL;
7056 char *editor = NULL;
7057 int initial_content_len;
7058 int fd = -1;
7060 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7061 err = got_error_from_errno("asprintf");
7062 goto done;
7065 initial_content_len = asprintf(&initial_content,
7066 "\n# tagging commit %s as %s\n",
7067 commit_id_str, tag_name);
7068 if (initial_content_len == -1) {
7069 err = got_error_from_errno("asprintf");
7070 goto done;
7073 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7074 if (err)
7075 goto done;
7077 if (write(fd, initial_content, initial_content_len) == -1) {
7078 err = got_error_from_errno2("write", *tagmsg_path);
7079 goto done;
7082 err = get_editor(&editor);
7083 if (err)
7084 goto done;
7085 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7086 initial_content_len, 1);
7087 done:
7088 free(initial_content);
7089 free(template);
7090 free(editor);
7092 if (fd != -1 && close(fd) == -1 && err == NULL)
7093 err = got_error_from_errno2("close", *tagmsg_path);
7095 /* Editor is done; we can now apply unveil(2) */
7096 if (err == NULL)
7097 err = apply_unveil(repo_path, 0, NULL);
7098 if (err) {
7099 free(*tagmsg);
7100 *tagmsg = NULL;
7102 return err;
7105 static const struct got_error *
7106 add_tag(struct got_repository *repo, const char *tagger,
7107 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
7109 const struct got_error *err = NULL;
7110 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7111 char *label = NULL, *commit_id_str = NULL;
7112 struct got_reference *ref = NULL;
7113 char *refname = NULL, *tagmsg = NULL;
7114 char *tagmsg_path = NULL, *tag_id_str = NULL;
7115 int preserve_tagmsg = 0;
7116 struct got_reflist_head refs;
7118 TAILQ_INIT(&refs);
7121 * Don't let the user create a tag name with a leading '-'.
7122 * While technically a valid reference name, this case is usually
7123 * an unintended typo.
7125 if (tag_name[0] == '-')
7126 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7128 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7129 if (err)
7130 goto done;
7132 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7133 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7134 if (err)
7135 goto done;
7137 err = got_object_id_str(&commit_id_str, commit_id);
7138 if (err)
7139 goto done;
7141 err = get_tag_refname(&refname, tag_name);
7142 if (err)
7143 goto done;
7144 if (strncmp("refs/tags/", tag_name, 10) == 0)
7145 tag_name += 10;
7147 err = got_ref_open(&ref, repo, refname, 0);
7148 if (err == NULL) {
7149 err = got_error(GOT_ERR_TAG_EXISTS);
7150 goto done;
7151 } else if (err->code != GOT_ERR_NOT_REF)
7152 goto done;
7154 if (tagmsg_arg == NULL) {
7155 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7156 tag_name, got_repo_get_path(repo));
7157 if (err) {
7158 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7159 tagmsg_path != NULL)
7160 preserve_tagmsg = 1;
7161 goto done;
7165 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7166 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7167 if (err) {
7168 if (tagmsg_path)
7169 preserve_tagmsg = 1;
7170 goto done;
7173 err = got_ref_alloc(&ref, refname, tag_id);
7174 if (err) {
7175 if (tagmsg_path)
7176 preserve_tagmsg = 1;
7177 goto done;
7180 err = got_ref_write(ref, repo);
7181 if (err) {
7182 if (tagmsg_path)
7183 preserve_tagmsg = 1;
7184 goto done;
7187 err = got_object_id_str(&tag_id_str, tag_id);
7188 if (err) {
7189 if (tagmsg_path)
7190 preserve_tagmsg = 1;
7191 goto done;
7193 printf("Created tag %s\n", tag_id_str);
7194 done:
7195 if (preserve_tagmsg) {
7196 fprintf(stderr, "%s: tag message preserved in %s\n",
7197 getprogname(), tagmsg_path);
7198 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7199 err = got_error_from_errno2("unlink", tagmsg_path);
7200 free(tag_id_str);
7201 if (ref)
7202 got_ref_close(ref);
7203 free(commit_id);
7204 free(commit_id_str);
7205 free(refname);
7206 free(tagmsg);
7207 free(tagmsg_path);
7208 got_ref_list_free(&refs);
7209 return err;
7212 static const struct got_error *
7213 cmd_tag(int argc, char *argv[])
7215 const struct got_error *error = NULL;
7216 struct got_repository *repo = NULL;
7217 struct got_worktree *worktree = NULL;
7218 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7219 char *gitconfig_path = NULL, *tagger = NULL;
7220 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7221 int ch, do_list = 0;
7222 int *pack_fds = NULL;
7224 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7225 switch (ch) {
7226 case 'c':
7227 commit_id_arg = optarg;
7228 break;
7229 case 'm':
7230 tagmsg = optarg;
7231 break;
7232 case 'r':
7233 repo_path = realpath(optarg, NULL);
7234 if (repo_path == NULL)
7235 return got_error_from_errno2("realpath",
7236 optarg);
7237 got_path_strip_trailing_slashes(repo_path);
7238 break;
7239 case 'l':
7240 do_list = 1;
7241 break;
7242 default:
7243 usage_tag();
7244 /* NOTREACHED */
7248 argc -= optind;
7249 argv += optind;
7251 if (do_list) {
7252 if (commit_id_arg != NULL)
7253 errx(1,
7254 "-c option can only be used when creating a tag");
7255 if (tagmsg)
7256 option_conflict('l', 'm');
7257 if (argc > 1)
7258 usage_tag();
7259 } else if (argc != 1)
7260 usage_tag();
7262 if (argc == 1)
7263 tag_name = argv[0];
7265 #ifndef PROFILE
7266 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7267 "sendfd unveil", NULL) == -1)
7268 err(1, "pledge");
7269 #endif
7270 cwd = getcwd(NULL, 0);
7271 if (cwd == NULL) {
7272 error = got_error_from_errno("getcwd");
7273 goto done;
7276 error = got_repo_pack_fds_open(&pack_fds);
7277 if (error != NULL)
7278 goto done;
7280 if (repo_path == NULL) {
7281 error = got_worktree_open(&worktree, cwd);
7282 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7283 goto done;
7284 else
7285 error = NULL;
7286 if (worktree) {
7287 repo_path =
7288 strdup(got_worktree_get_repo_path(worktree));
7289 if (repo_path == NULL)
7290 error = got_error_from_errno("strdup");
7291 if (error)
7292 goto done;
7293 } else {
7294 repo_path = strdup(cwd);
7295 if (repo_path == NULL) {
7296 error = got_error_from_errno("strdup");
7297 goto done;
7302 if (do_list) {
7303 if (worktree) {
7304 /* Release work tree lock. */
7305 got_worktree_close(worktree);
7306 worktree = NULL;
7308 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7309 if (error != NULL)
7310 goto done;
7312 #ifndef PROFILE
7313 /* Remove "cpath" promise. */
7314 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7315 NULL) == -1)
7316 err(1, "pledge");
7317 #endif
7318 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7319 if (error)
7320 goto done;
7321 error = list_tags(repo, tag_name);
7322 } else {
7323 error = get_gitconfig_path(&gitconfig_path);
7324 if (error)
7325 goto done;
7326 error = got_repo_open(&repo, repo_path, gitconfig_path,
7327 pack_fds);
7328 if (error != NULL)
7329 goto done;
7331 error = get_author(&tagger, repo, worktree);
7332 if (error)
7333 goto done;
7334 if (worktree) {
7335 /* Release work tree lock. */
7336 got_worktree_close(worktree);
7337 worktree = NULL;
7340 if (tagmsg) {
7341 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7342 if (error)
7343 goto done;
7346 if (commit_id_arg == NULL) {
7347 struct got_reference *head_ref;
7348 struct got_object_id *commit_id;
7349 error = got_ref_open(&head_ref, repo,
7350 worktree ? got_worktree_get_head_ref_name(worktree)
7351 : GOT_REF_HEAD, 0);
7352 if (error)
7353 goto done;
7354 error = got_ref_resolve(&commit_id, repo, head_ref);
7355 got_ref_close(head_ref);
7356 if (error)
7357 goto done;
7358 error = got_object_id_str(&commit_id_str, commit_id);
7359 free(commit_id);
7360 if (error)
7361 goto done;
7364 error = add_tag(repo, tagger, tag_name,
7365 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7367 done:
7368 if (repo) {
7369 const struct got_error *close_err = got_repo_close(repo);
7370 if (error == NULL)
7371 error = close_err;
7373 if (worktree)
7374 got_worktree_close(worktree);
7375 if (pack_fds) {
7376 const struct got_error *pack_err =
7377 got_repo_pack_fds_close(pack_fds);
7378 if (error == NULL)
7379 error = pack_err;
7381 free(cwd);
7382 free(repo_path);
7383 free(gitconfig_path);
7384 free(commit_id_str);
7385 free(tagger);
7386 return error;
7389 __dead static void
7390 usage_add(void)
7392 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7393 getprogname());
7394 exit(1);
7397 static const struct got_error *
7398 add_progress(void *arg, unsigned char status, const char *path)
7400 while (path[0] == '/')
7401 path++;
7402 printf("%c %s\n", status, path);
7403 return NULL;
7406 static const struct got_error *
7407 cmd_add(int argc, char *argv[])
7409 const struct got_error *error = NULL;
7410 struct got_repository *repo = NULL;
7411 struct got_worktree *worktree = NULL;
7412 char *cwd = NULL;
7413 struct got_pathlist_head paths;
7414 struct got_pathlist_entry *pe;
7415 int ch, can_recurse = 0, no_ignores = 0;
7416 int *pack_fds = NULL;
7418 TAILQ_INIT(&paths);
7420 while ((ch = getopt(argc, argv, "IR")) != -1) {
7421 switch (ch) {
7422 case 'I':
7423 no_ignores = 1;
7424 break;
7425 case 'R':
7426 can_recurse = 1;
7427 break;
7428 default:
7429 usage_add();
7430 /* NOTREACHED */
7434 argc -= optind;
7435 argv += optind;
7437 #ifndef PROFILE
7438 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7439 NULL) == -1)
7440 err(1, "pledge");
7441 #endif
7442 if (argc < 1)
7443 usage_add();
7445 cwd = getcwd(NULL, 0);
7446 if (cwd == NULL) {
7447 error = got_error_from_errno("getcwd");
7448 goto done;
7451 error = got_repo_pack_fds_open(&pack_fds);
7452 if (error != NULL)
7453 goto done;
7455 error = got_worktree_open(&worktree, cwd);
7456 if (error) {
7457 if (error->code == GOT_ERR_NOT_WORKTREE)
7458 error = wrap_not_worktree_error(error, "add", cwd);
7459 goto done;
7462 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7463 NULL, pack_fds);
7464 if (error != NULL)
7465 goto done;
7467 error = apply_unveil(got_repo_get_path(repo), 1,
7468 got_worktree_get_root_path(worktree));
7469 if (error)
7470 goto done;
7472 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7473 if (error)
7474 goto done;
7476 if (!can_recurse) {
7477 char *ondisk_path;
7478 struct stat sb;
7479 TAILQ_FOREACH(pe, &paths, entry) {
7480 if (asprintf(&ondisk_path, "%s/%s",
7481 got_worktree_get_root_path(worktree),
7482 pe->path) == -1) {
7483 error = got_error_from_errno("asprintf");
7484 goto done;
7486 if (lstat(ondisk_path, &sb) == -1) {
7487 if (errno == ENOENT) {
7488 free(ondisk_path);
7489 continue;
7491 error = got_error_from_errno2("lstat",
7492 ondisk_path);
7493 free(ondisk_path);
7494 goto done;
7496 free(ondisk_path);
7497 if (S_ISDIR(sb.st_mode)) {
7498 error = got_error_msg(GOT_ERR_BAD_PATH,
7499 "adding directories requires -R option");
7500 goto done;
7505 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7506 NULL, repo, no_ignores);
7507 done:
7508 if (repo) {
7509 const struct got_error *close_err = got_repo_close(repo);
7510 if (error == NULL)
7511 error = close_err;
7513 if (worktree)
7514 got_worktree_close(worktree);
7515 if (pack_fds) {
7516 const struct got_error *pack_err =
7517 got_repo_pack_fds_close(pack_fds);
7518 if (error == NULL)
7519 error = pack_err;
7521 TAILQ_FOREACH(pe, &paths, entry)
7522 free((char *)pe->path);
7523 got_pathlist_free(&paths);
7524 free(cwd);
7525 return error;
7528 __dead static void
7529 usage_remove(void)
7531 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7532 "path ...\n", getprogname());
7533 exit(1);
7536 static const struct got_error *
7537 print_remove_status(void *arg, unsigned char status,
7538 unsigned char staged_status, const char *path)
7540 while (path[0] == '/')
7541 path++;
7542 if (status == GOT_STATUS_NONEXISTENT)
7543 return NULL;
7544 if (status == staged_status && (status == GOT_STATUS_DELETE))
7545 status = GOT_STATUS_NO_CHANGE;
7546 printf("%c%c %s\n", status, staged_status, path);
7547 return NULL;
7550 static const struct got_error *
7551 cmd_remove(int argc, char *argv[])
7553 const struct got_error *error = NULL;
7554 struct got_worktree *worktree = NULL;
7555 struct got_repository *repo = NULL;
7556 const char *status_codes = NULL;
7557 char *cwd = NULL;
7558 struct got_pathlist_head paths;
7559 struct got_pathlist_entry *pe;
7560 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7561 int ignore_missing_paths = 0;
7562 int *pack_fds = NULL;
7564 TAILQ_INIT(&paths);
7566 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7567 switch (ch) {
7568 case 'f':
7569 delete_local_mods = 1;
7570 ignore_missing_paths = 1;
7571 break;
7572 case 'k':
7573 keep_on_disk = 1;
7574 break;
7575 case 'R':
7576 can_recurse = 1;
7577 break;
7578 case 's':
7579 for (i = 0; i < strlen(optarg); i++) {
7580 switch (optarg[i]) {
7581 case GOT_STATUS_MODIFY:
7582 delete_local_mods = 1;
7583 break;
7584 case GOT_STATUS_MISSING:
7585 ignore_missing_paths = 1;
7586 break;
7587 default:
7588 errx(1, "invalid status code '%c'",
7589 optarg[i]);
7592 status_codes = optarg;
7593 break;
7594 default:
7595 usage_remove();
7596 /* NOTREACHED */
7600 argc -= optind;
7601 argv += optind;
7603 #ifndef PROFILE
7604 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7605 NULL) == -1)
7606 err(1, "pledge");
7607 #endif
7608 if (argc < 1)
7609 usage_remove();
7611 cwd = getcwd(NULL, 0);
7612 if (cwd == NULL) {
7613 error = got_error_from_errno("getcwd");
7614 goto done;
7617 error = got_repo_pack_fds_open(&pack_fds);
7618 if (error != NULL)
7619 goto done;
7621 error = got_worktree_open(&worktree, cwd);
7622 if (error) {
7623 if (error->code == GOT_ERR_NOT_WORKTREE)
7624 error = wrap_not_worktree_error(error, "remove", cwd);
7625 goto done;
7628 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7629 NULL, pack_fds);
7630 if (error)
7631 goto done;
7633 error = apply_unveil(got_repo_get_path(repo), 1,
7634 got_worktree_get_root_path(worktree));
7635 if (error)
7636 goto done;
7638 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7639 if (error)
7640 goto done;
7642 if (!can_recurse) {
7643 char *ondisk_path;
7644 struct stat sb;
7645 TAILQ_FOREACH(pe, &paths, entry) {
7646 if (asprintf(&ondisk_path, "%s/%s",
7647 got_worktree_get_root_path(worktree),
7648 pe->path) == -1) {
7649 error = got_error_from_errno("asprintf");
7650 goto done;
7652 if (lstat(ondisk_path, &sb) == -1) {
7653 if (errno == ENOENT) {
7654 free(ondisk_path);
7655 continue;
7657 error = got_error_from_errno2("lstat",
7658 ondisk_path);
7659 free(ondisk_path);
7660 goto done;
7662 free(ondisk_path);
7663 if (S_ISDIR(sb.st_mode)) {
7664 error = got_error_msg(GOT_ERR_BAD_PATH,
7665 "removing directories requires -R option");
7666 goto done;
7671 error = got_worktree_schedule_delete(worktree, &paths,
7672 delete_local_mods, status_codes, print_remove_status, NULL,
7673 repo, keep_on_disk, ignore_missing_paths);
7674 done:
7675 if (repo) {
7676 const struct got_error *close_err = got_repo_close(repo);
7677 if (error == NULL)
7678 error = close_err;
7680 if (worktree)
7681 got_worktree_close(worktree);
7682 if (pack_fds) {
7683 const struct got_error *pack_err =
7684 got_repo_pack_fds_close(pack_fds);
7685 if (error == NULL)
7686 error = pack_err;
7688 TAILQ_FOREACH(pe, &paths, entry)
7689 free((char *)pe->path);
7690 got_pathlist_free(&paths);
7691 free(cwd);
7692 return error;
7695 __dead static void
7696 usage_patch(void)
7698 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7699 "[-R] [patchfile]\n", getprogname());
7700 exit(1);
7703 static const struct got_error *
7704 patch_from_stdin(int *patchfd)
7706 const struct got_error *err = NULL;
7707 ssize_t r;
7708 char *path, buf[BUFSIZ];
7709 sig_t sighup, sigint, sigquit;
7711 err = got_opentemp_named_fd(&path, patchfd,
7712 GOT_TMPDIR_STR "/got-patch");
7713 if (err)
7714 return err;
7715 unlink(path);
7716 free(path);
7718 sighup = signal(SIGHUP, SIG_DFL);
7719 sigint = signal(SIGINT, SIG_DFL);
7720 sigquit = signal(SIGQUIT, SIG_DFL);
7722 for (;;) {
7723 r = read(0, buf, sizeof(buf));
7724 if (r == -1) {
7725 err = got_error_from_errno("read");
7726 break;
7728 if (r == 0)
7729 break;
7730 if (write(*patchfd, buf, r) == -1) {
7731 err = got_error_from_errno("write");
7732 break;
7736 signal(SIGHUP, sighup);
7737 signal(SIGINT, sigint);
7738 signal(SIGQUIT, sigquit);
7740 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7741 err = got_error_from_errno("lseek");
7743 if (err != NULL) {
7744 close(*patchfd);
7745 *patchfd = -1;
7748 return err;
7751 static const struct got_error *
7752 patch_progress(void *arg, const char *old, const char *new,
7753 unsigned char status, const struct got_error *error, long old_from,
7754 long old_lines, long new_from, long new_lines, long offset,
7755 const struct got_error *hunk_err)
7757 const char *path = new == NULL ? old : new;
7759 while (*path == '/')
7760 path++;
7762 if (status != 0)
7763 printf("%c %s\n", status, path);
7765 if (error != NULL)
7766 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7768 if (offset != 0 || hunk_err != NULL) {
7769 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7770 old_lines, new_from, new_lines);
7771 if (hunk_err != NULL)
7772 printf("%s\n", hunk_err->msg);
7773 else
7774 printf("applied with offset %ld\n", offset);
7777 return NULL;
7780 static const struct got_error *
7781 cmd_patch(int argc, char *argv[])
7783 const struct got_error *error = NULL, *close_error = NULL;
7784 struct got_worktree *worktree = NULL;
7785 struct got_repository *repo = NULL;
7786 const char *errstr;
7787 char *cwd = NULL;
7788 int ch, nop = 0, strip = -1, reverse = 0;
7789 int patchfd;
7790 int *pack_fds = NULL;
7792 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7793 switch (ch) {
7794 case 'n':
7795 nop = 1;
7796 break;
7797 case 'p':
7798 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7799 if (errstr != NULL)
7800 errx(1, "pathname strip count is %s: %s",
7801 errstr, optarg);
7802 break;
7803 case 'R':
7804 reverse = 1;
7805 break;
7806 default:
7807 usage_patch();
7808 /* NOTREACHED */
7812 argc -= optind;
7813 argv += optind;
7815 if (argc == 0) {
7816 error = patch_from_stdin(&patchfd);
7817 if (error)
7818 return error;
7819 } else if (argc == 1) {
7820 patchfd = open(argv[0], O_RDONLY);
7821 if (patchfd == -1) {
7822 error = got_error_from_errno2("open", argv[0]);
7823 return error;
7825 } else
7826 usage_patch();
7828 if ((cwd = getcwd(NULL, 0)) == NULL) {
7829 error = got_error_from_errno("getcwd");
7830 goto done;
7833 error = got_repo_pack_fds_open(&pack_fds);
7834 if (error != NULL)
7835 goto done;
7837 error = got_worktree_open(&worktree, cwd);
7838 if (error != NULL)
7839 goto done;
7841 const char *repo_path = got_worktree_get_repo_path(worktree);
7842 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7843 if (error != NULL)
7844 goto done;
7846 error = apply_unveil(got_repo_get_path(repo), 0,
7847 got_worktree_get_root_path(worktree));
7848 if (error != NULL)
7849 goto done;
7851 #ifndef PROFILE
7852 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7853 NULL) == -1)
7854 err(1, "pledge");
7855 #endif
7857 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7858 &patch_progress, NULL, check_cancelled, NULL);
7860 done:
7861 if (repo) {
7862 close_error = got_repo_close(repo);
7863 if (error == NULL)
7864 error = close_error;
7866 if (worktree != NULL) {
7867 close_error = got_worktree_close(worktree);
7868 if (error == NULL)
7869 error = close_error;
7871 if (pack_fds) {
7872 const struct got_error *pack_err =
7873 got_repo_pack_fds_close(pack_fds);
7874 if (error == NULL)
7875 error = pack_err;
7877 free(cwd);
7878 return error;
7881 __dead static void
7882 usage_revert(void)
7884 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7885 "path ...\n", getprogname());
7886 exit(1);
7889 static const struct got_error *
7890 revert_progress(void *arg, unsigned char status, const char *path)
7892 if (status == GOT_STATUS_UNVERSIONED)
7893 return NULL;
7895 while (path[0] == '/')
7896 path++;
7897 printf("%c %s\n", status, path);
7898 return NULL;
7901 struct choose_patch_arg {
7902 FILE *patch_script_file;
7903 const char *action;
7906 static const struct got_error *
7907 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7908 int nchanges, const char *action)
7910 const struct got_error *err;
7911 char *line = NULL;
7912 size_t linesize = 0;
7913 ssize_t linelen;
7915 switch (status) {
7916 case GOT_STATUS_ADD:
7917 printf("A %s\n%s this addition? [y/n] ", path, action);
7918 break;
7919 case GOT_STATUS_DELETE:
7920 printf("D %s\n%s this deletion? [y/n] ", path, action);
7921 break;
7922 case GOT_STATUS_MODIFY:
7923 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7924 return got_error_from_errno("fseek");
7925 printf(GOT_COMMIT_SEP_STR);
7926 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7927 printf("%s", line);
7928 if (linelen == -1 && ferror(patch_file)) {
7929 err = got_error_from_errno("getline");
7930 free(line);
7931 return err;
7933 free(line);
7934 printf(GOT_COMMIT_SEP_STR);
7935 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7936 path, n, nchanges, action);
7937 break;
7938 default:
7939 return got_error_path(path, GOT_ERR_FILE_STATUS);
7942 return NULL;
7945 static const struct got_error *
7946 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7947 FILE *patch_file, int n, int nchanges)
7949 const struct got_error *err = NULL;
7950 char *line = NULL;
7951 size_t linesize = 0;
7952 ssize_t linelen;
7953 int resp = ' ';
7954 struct choose_patch_arg *a = arg;
7956 *choice = GOT_PATCH_CHOICE_NONE;
7958 if (a->patch_script_file) {
7959 char *nl;
7960 err = show_change(status, path, patch_file, n, nchanges,
7961 a->action);
7962 if (err)
7963 return err;
7964 linelen = getline(&line, &linesize, a->patch_script_file);
7965 if (linelen == -1) {
7966 if (ferror(a->patch_script_file))
7967 return got_error_from_errno("getline");
7968 return NULL;
7970 nl = strchr(line, '\n');
7971 if (nl)
7972 *nl = '\0';
7973 if (strcmp(line, "y") == 0) {
7974 *choice = GOT_PATCH_CHOICE_YES;
7975 printf("y\n");
7976 } else if (strcmp(line, "n") == 0) {
7977 *choice = GOT_PATCH_CHOICE_NO;
7978 printf("n\n");
7979 } else if (strcmp(line, "q") == 0 &&
7980 status == GOT_STATUS_MODIFY) {
7981 *choice = GOT_PATCH_CHOICE_QUIT;
7982 printf("q\n");
7983 } else
7984 printf("invalid response '%s'\n", line);
7985 free(line);
7986 return NULL;
7989 while (resp != 'y' && resp != 'n' && resp != 'q') {
7990 err = show_change(status, path, patch_file, n, nchanges,
7991 a->action);
7992 if (err)
7993 return err;
7994 resp = getchar();
7995 if (resp == '\n')
7996 resp = getchar();
7997 if (status == GOT_STATUS_MODIFY) {
7998 if (resp != 'y' && resp != 'n' && resp != 'q') {
7999 printf("invalid response '%c'\n", resp);
8000 resp = ' ';
8002 } else if (resp != 'y' && resp != 'n') {
8003 printf("invalid response '%c'\n", resp);
8004 resp = ' ';
8008 if (resp == 'y')
8009 *choice = GOT_PATCH_CHOICE_YES;
8010 else if (resp == 'n')
8011 *choice = GOT_PATCH_CHOICE_NO;
8012 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8013 *choice = GOT_PATCH_CHOICE_QUIT;
8015 return NULL;
8018 static const struct got_error *
8019 cmd_revert(int argc, char *argv[])
8021 const struct got_error *error = NULL;
8022 struct got_worktree *worktree = NULL;
8023 struct got_repository *repo = NULL;
8024 char *cwd = NULL, *path = NULL;
8025 struct got_pathlist_head paths;
8026 struct got_pathlist_entry *pe;
8027 int ch, can_recurse = 0, pflag = 0;
8028 FILE *patch_script_file = NULL;
8029 const char *patch_script_path = NULL;
8030 struct choose_patch_arg cpa;
8031 int *pack_fds = NULL;
8033 TAILQ_INIT(&paths);
8035 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8036 switch (ch) {
8037 case 'p':
8038 pflag = 1;
8039 break;
8040 case 'F':
8041 patch_script_path = optarg;
8042 break;
8043 case 'R':
8044 can_recurse = 1;
8045 break;
8046 default:
8047 usage_revert();
8048 /* NOTREACHED */
8052 argc -= optind;
8053 argv += optind;
8055 #ifndef PROFILE
8056 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8057 "unveil", NULL) == -1)
8058 err(1, "pledge");
8059 #endif
8060 if (argc < 1)
8061 usage_revert();
8062 if (patch_script_path && !pflag)
8063 errx(1, "-F option can only be used together with -p option");
8065 cwd = getcwd(NULL, 0);
8066 if (cwd == NULL) {
8067 error = got_error_from_errno("getcwd");
8068 goto done;
8071 error = got_repo_pack_fds_open(&pack_fds);
8072 if (error != NULL)
8073 goto done;
8075 error = got_worktree_open(&worktree, cwd);
8076 if (error) {
8077 if (error->code == GOT_ERR_NOT_WORKTREE)
8078 error = wrap_not_worktree_error(error, "revert", cwd);
8079 goto done;
8082 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8083 NULL, pack_fds);
8084 if (error != NULL)
8085 goto done;
8087 if (patch_script_path) {
8088 patch_script_file = fopen(patch_script_path, "re");
8089 if (patch_script_file == NULL) {
8090 error = got_error_from_errno2("fopen",
8091 patch_script_path);
8092 goto done;
8095 error = apply_unveil(got_repo_get_path(repo), 1,
8096 got_worktree_get_root_path(worktree));
8097 if (error)
8098 goto done;
8100 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8101 if (error)
8102 goto done;
8104 if (!can_recurse) {
8105 char *ondisk_path;
8106 struct stat sb;
8107 TAILQ_FOREACH(pe, &paths, entry) {
8108 if (asprintf(&ondisk_path, "%s/%s",
8109 got_worktree_get_root_path(worktree),
8110 pe->path) == -1) {
8111 error = got_error_from_errno("asprintf");
8112 goto done;
8114 if (lstat(ondisk_path, &sb) == -1) {
8115 if (errno == ENOENT) {
8116 free(ondisk_path);
8117 continue;
8119 error = got_error_from_errno2("lstat",
8120 ondisk_path);
8121 free(ondisk_path);
8122 goto done;
8124 free(ondisk_path);
8125 if (S_ISDIR(sb.st_mode)) {
8126 error = got_error_msg(GOT_ERR_BAD_PATH,
8127 "reverting directories requires -R option");
8128 goto done;
8133 cpa.patch_script_file = patch_script_file;
8134 cpa.action = "revert";
8135 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8136 pflag ? choose_patch : NULL, &cpa, repo);
8137 done:
8138 if (patch_script_file && fclose(patch_script_file) == EOF &&
8139 error == NULL)
8140 error = got_error_from_errno2("fclose", patch_script_path);
8141 if (repo) {
8142 const struct got_error *close_err = got_repo_close(repo);
8143 if (error == NULL)
8144 error = close_err;
8146 if (worktree)
8147 got_worktree_close(worktree);
8148 if (pack_fds) {
8149 const struct got_error *pack_err =
8150 got_repo_pack_fds_close(pack_fds);
8151 if (error == NULL)
8152 error = pack_err;
8154 free(path);
8155 free(cwd);
8156 return error;
8159 __dead static void
8160 usage_commit(void)
8162 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8163 "[path ...]\n", getprogname());
8164 exit(1);
8167 struct collect_commit_logmsg_arg {
8168 const char *cmdline_log;
8169 const char *prepared_log;
8170 int non_interactive;
8171 const char *editor;
8172 const char *worktree_path;
8173 const char *branch_name;
8174 const char *repo_path;
8175 char *logmsg_path;
8179 static const struct got_error *
8180 read_prepared_logmsg(char **logmsg, const char *path)
8182 const struct got_error *err = NULL;
8183 FILE *f = NULL;
8184 struct stat sb;
8185 size_t r;
8187 *logmsg = NULL;
8188 memset(&sb, 0, sizeof(sb));
8190 f = fopen(path, "re");
8191 if (f == NULL)
8192 return got_error_from_errno2("fopen", path);
8194 if (fstat(fileno(f), &sb) == -1) {
8195 err = got_error_from_errno2("fstat", path);
8196 goto done;
8198 if (sb.st_size == 0) {
8199 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8200 goto done;
8203 *logmsg = malloc(sb.st_size + 1);
8204 if (*logmsg == NULL) {
8205 err = got_error_from_errno("malloc");
8206 goto done;
8209 r = fread(*logmsg, 1, sb.st_size, f);
8210 if (r != sb.st_size) {
8211 if (ferror(f))
8212 err = got_error_from_errno2("fread", path);
8213 else
8214 err = got_error(GOT_ERR_IO);
8215 goto done;
8217 (*logmsg)[sb.st_size] = '\0';
8218 done:
8219 if (fclose(f) == EOF && err == NULL)
8220 err = got_error_from_errno2("fclose", path);
8221 if (err) {
8222 free(*logmsg);
8223 *logmsg = NULL;
8225 return err;
8229 static const struct got_error *
8230 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8231 void *arg)
8233 char *initial_content = NULL;
8234 struct got_pathlist_entry *pe;
8235 const struct got_error *err = NULL;
8236 char *template = NULL;
8237 struct collect_commit_logmsg_arg *a = arg;
8238 int initial_content_len;
8239 int fd = -1;
8240 size_t len;
8242 /* if a message was specified on the command line, just use it */
8243 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8244 len = strlen(a->cmdline_log) + 1;
8245 *logmsg = malloc(len + 1);
8246 if (*logmsg == NULL)
8247 return got_error_from_errno("malloc");
8248 strlcpy(*logmsg, a->cmdline_log, len);
8249 return NULL;
8250 } else if (a->prepared_log != NULL && a->non_interactive)
8251 return read_prepared_logmsg(logmsg, a->prepared_log);
8253 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8254 return got_error_from_errno("asprintf");
8256 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8257 if (err)
8258 goto done;
8260 if (a->prepared_log) {
8261 char *msg;
8262 err = read_prepared_logmsg(&msg, a->prepared_log);
8263 if (err)
8264 goto done;
8265 if (write(fd, msg, strlen(msg)) == -1) {
8266 err = got_error_from_errno2("write", a->logmsg_path);
8267 free(msg);
8268 goto done;
8270 free(msg);
8273 initial_content_len = asprintf(&initial_content,
8274 "\n# changes to be committed on branch %s:\n",
8275 a->branch_name);
8276 if (initial_content_len == -1) {
8277 err = got_error_from_errno("asprintf");
8278 goto done;
8281 if (write(fd, initial_content, initial_content_len) == -1) {
8282 err = got_error_from_errno2("write", a->logmsg_path);
8283 goto done;
8286 TAILQ_FOREACH(pe, commitable_paths, entry) {
8287 struct got_commitable *ct = pe->data;
8288 dprintf(fd, "# %c %s\n",
8289 got_commitable_get_status(ct),
8290 got_commitable_get_path(ct));
8293 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8294 initial_content_len, a->prepared_log ? 0 : 1);
8295 done:
8296 free(initial_content);
8297 free(template);
8299 if (fd != -1 && close(fd) == -1 && err == NULL)
8300 err = got_error_from_errno2("close", a->logmsg_path);
8302 /* Editor is done; we can now apply unveil(2) */
8303 if (err == NULL)
8304 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8305 if (err) {
8306 free(*logmsg);
8307 *logmsg = NULL;
8309 return err;
8312 static const struct got_error *
8313 cmd_commit(int argc, char *argv[])
8315 const struct got_error *error = NULL;
8316 struct got_worktree *worktree = NULL;
8317 struct got_repository *repo = NULL;
8318 char *cwd = NULL, *id_str = NULL;
8319 struct got_object_id *id = NULL;
8320 const char *logmsg = NULL;
8321 char *prepared_logmsg = NULL;
8322 struct collect_commit_logmsg_arg cl_arg;
8323 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8324 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8325 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8326 struct got_pathlist_head paths;
8327 int *pack_fds = NULL;
8329 TAILQ_INIT(&paths);
8330 cl_arg.logmsg_path = NULL;
8332 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8333 switch (ch) {
8334 case 'F':
8335 if (logmsg != NULL)
8336 option_conflict('F', 'm');
8337 prepared_logmsg = realpath(optarg, NULL);
8338 if (prepared_logmsg == NULL)
8339 return got_error_from_errno2("realpath",
8340 optarg);
8341 break;
8342 case 'm':
8343 if (prepared_logmsg)
8344 option_conflict('m', 'F');
8345 logmsg = optarg;
8346 break;
8347 case 'N':
8348 non_interactive = 1;
8349 break;
8350 case 'S':
8351 allow_bad_symlinks = 1;
8352 break;
8353 default:
8354 usage_commit();
8355 /* NOTREACHED */
8359 argc -= optind;
8360 argv += optind;
8362 #ifndef PROFILE
8363 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8364 "unveil", NULL) == -1)
8365 err(1, "pledge");
8366 #endif
8367 cwd = getcwd(NULL, 0);
8368 if (cwd == NULL) {
8369 error = got_error_from_errno("getcwd");
8370 goto done;
8373 error = got_repo_pack_fds_open(&pack_fds);
8374 if (error != NULL)
8375 goto done;
8377 error = got_worktree_open(&worktree, cwd);
8378 if (error) {
8379 if (error->code == GOT_ERR_NOT_WORKTREE)
8380 error = wrap_not_worktree_error(error, "commit", cwd);
8381 goto done;
8384 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8385 if (error)
8386 goto done;
8387 if (rebase_in_progress) {
8388 error = got_error(GOT_ERR_REBASING);
8389 goto done;
8392 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8393 worktree);
8394 if (error)
8395 goto done;
8397 error = get_gitconfig_path(&gitconfig_path);
8398 if (error)
8399 goto done;
8400 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8401 gitconfig_path, pack_fds);
8402 if (error != NULL)
8403 goto done;
8405 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8406 if (error)
8407 goto done;
8408 if (merge_in_progress) {
8409 error = got_error(GOT_ERR_MERGE_BUSY);
8410 goto done;
8413 error = get_author(&author, repo, worktree);
8414 if (error)
8415 return error;
8418 * unveil(2) traverses exec(2); if an editor is used we have
8419 * to apply unveil after the log message has been written.
8421 if (logmsg == NULL || strlen(logmsg) == 0)
8422 error = get_editor(&editor);
8423 else
8424 error = apply_unveil(got_repo_get_path(repo), 0,
8425 got_worktree_get_root_path(worktree));
8426 if (error)
8427 goto done;
8429 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8430 if (error)
8431 goto done;
8433 cl_arg.editor = editor;
8434 cl_arg.cmdline_log = logmsg;
8435 cl_arg.prepared_log = prepared_logmsg;
8436 cl_arg.non_interactive = non_interactive;
8437 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8438 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8439 if (!histedit_in_progress) {
8440 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8441 error = got_error(GOT_ERR_COMMIT_BRANCH);
8442 goto done;
8444 cl_arg.branch_name += 11;
8446 cl_arg.repo_path = got_repo_get_path(repo);
8447 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8448 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8449 print_status, NULL, repo);
8450 if (error) {
8451 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8452 cl_arg.logmsg_path != NULL)
8453 preserve_logmsg = 1;
8454 goto done;
8457 error = got_object_id_str(&id_str, id);
8458 if (error)
8459 goto done;
8460 printf("Created commit %s\n", id_str);
8461 done:
8462 if (preserve_logmsg) {
8463 fprintf(stderr, "%s: log message preserved in %s\n",
8464 getprogname(), cl_arg.logmsg_path);
8465 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8466 error == NULL)
8467 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8468 free(cl_arg.logmsg_path);
8469 if (repo) {
8470 const struct got_error *close_err = got_repo_close(repo);
8471 if (error == NULL)
8472 error = close_err;
8474 if (worktree)
8475 got_worktree_close(worktree);
8476 if (pack_fds) {
8477 const struct got_error *pack_err =
8478 got_repo_pack_fds_close(pack_fds);
8479 if (error == NULL)
8480 error = pack_err;
8482 free(cwd);
8483 free(id_str);
8484 free(gitconfig_path);
8485 free(editor);
8486 free(author);
8487 free(prepared_logmsg);
8488 return error;
8491 __dead static void
8492 usage_send(void)
8494 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8495 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8496 "[remote-repository]\n", getprogname());
8497 exit(1);
8500 static void
8501 print_load_info(int print_colored, int print_found, int print_trees,
8502 int ncolored, int nfound, int ntrees)
8504 if (print_colored) {
8505 printf("%d commit%s colored", ncolored,
8506 ncolored == 1 ? "" : "s");
8508 if (print_found) {
8509 printf("%s%d object%s found",
8510 ncolored > 0 ? "; " : "",
8511 nfound, nfound == 1 ? "" : "s");
8513 if (print_trees) {
8514 printf("; %d tree%s scanned", ntrees,
8515 ntrees == 1 ? "" : "s");
8519 struct got_send_progress_arg {
8520 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8521 int verbosity;
8522 int last_ncolored;
8523 int last_nfound;
8524 int last_ntrees;
8525 int loading_done;
8526 int last_ncommits;
8527 int last_nobj_total;
8528 int last_p_deltify;
8529 int last_p_written;
8530 int last_p_sent;
8531 int printed_something;
8532 int sent_something;
8533 struct got_pathlist_head *delete_branches;
8536 static const struct got_error *
8537 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8538 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8539 int nobj_written, off_t bytes_sent, const char *refname, int success)
8541 struct got_send_progress_arg *a = arg;
8542 char scaled_packsize[FMT_SCALED_STRSIZE];
8543 char scaled_sent[FMT_SCALED_STRSIZE];
8544 int p_deltify = 0, p_written = 0, p_sent = 0;
8545 int print_colored = 0, print_found = 0, print_trees = 0;
8546 int print_searching = 0, print_total = 0;
8547 int print_deltify = 0, print_written = 0, print_sent = 0;
8549 if (a->verbosity < 0)
8550 return NULL;
8552 if (refname) {
8553 const char *status = success ? "accepted" : "rejected";
8555 if (success) {
8556 struct got_pathlist_entry *pe;
8557 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8558 const char *branchname = pe->path;
8559 if (got_path_cmp(branchname, refname,
8560 strlen(branchname), strlen(refname)) == 0) {
8561 status = "deleted";
8562 a->sent_something = 1;
8563 break;
8568 if (a->printed_something)
8569 putchar('\n');
8570 printf("Server has %s %s", status, refname);
8571 a->printed_something = 1;
8572 return NULL;
8575 if (a->last_ncolored != ncolored) {
8576 print_colored = 1;
8577 a->last_ncolored = ncolored;
8580 if (a->last_nfound != nfound) {
8581 print_colored = 1;
8582 print_found = 1;
8583 a->last_nfound = nfound;
8586 if (a->last_ntrees != ntrees) {
8587 print_colored = 1;
8588 print_found = 1;
8589 print_trees = 1;
8590 a->last_ntrees = ntrees;
8593 if ((print_colored || print_found || print_trees) &&
8594 !a->loading_done) {
8595 printf("\r");
8596 print_load_info(print_colored, print_found, print_trees,
8597 ncolored, nfound, ntrees);
8598 a->printed_something = 1;
8599 fflush(stdout);
8600 return NULL;
8601 } else if (!a->loading_done) {
8602 printf("\r");
8603 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8604 printf("\n");
8605 a->loading_done = 1;
8608 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8609 return got_error_from_errno("fmt_scaled");
8610 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8611 return got_error_from_errno("fmt_scaled");
8613 if (a->last_ncommits != ncommits) {
8614 print_searching = 1;
8615 a->last_ncommits = ncommits;
8618 if (a->last_nobj_total != nobj_total) {
8619 print_searching = 1;
8620 print_total = 1;
8621 a->last_nobj_total = nobj_total;
8624 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8625 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8626 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8627 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8628 return got_error(GOT_ERR_NO_SPACE);
8631 if (nobj_deltify > 0 || nobj_written > 0) {
8632 if (nobj_deltify > 0) {
8633 p_deltify = (nobj_deltify * 100) / nobj_total;
8634 if (p_deltify != a->last_p_deltify) {
8635 a->last_p_deltify = p_deltify;
8636 print_searching = 1;
8637 print_total = 1;
8638 print_deltify = 1;
8641 if (nobj_written > 0) {
8642 p_written = (nobj_written * 100) / nobj_total;
8643 if (p_written != a->last_p_written) {
8644 a->last_p_written = p_written;
8645 print_searching = 1;
8646 print_total = 1;
8647 print_deltify = 1;
8648 print_written = 1;
8653 if (bytes_sent > 0) {
8654 p_sent = (bytes_sent * 100) / packfile_size;
8655 if (p_sent != a->last_p_sent) {
8656 a->last_p_sent = p_sent;
8657 print_searching = 1;
8658 print_total = 1;
8659 print_deltify = 1;
8660 print_written = 1;
8661 print_sent = 1;
8663 a->sent_something = 1;
8666 if (print_searching || print_total || print_deltify || print_written ||
8667 print_sent)
8668 printf("\r");
8669 if (print_searching)
8670 printf("packing %d reference%s", ncommits,
8671 ncommits == 1 ? "" : "s");
8672 if (print_total)
8673 printf("; %d object%s", nobj_total,
8674 nobj_total == 1 ? "" : "s");
8675 if (print_deltify)
8676 printf("; deltify: %d%%", p_deltify);
8677 if (print_sent)
8678 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8679 scaled_packsize, p_sent);
8680 else if (print_written)
8681 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8682 scaled_packsize, p_written);
8683 if (print_searching || print_total || print_deltify ||
8684 print_written || print_sent) {
8685 a->printed_something = 1;
8686 fflush(stdout);
8688 return NULL;
8691 static const struct got_error *
8692 cmd_send(int argc, char *argv[])
8694 const struct got_error *error = NULL;
8695 char *cwd = NULL, *repo_path = NULL;
8696 const char *remote_name;
8697 char *proto = NULL, *host = NULL, *port = NULL;
8698 char *repo_name = NULL, *server_path = NULL;
8699 const struct got_remote_repo *remotes, *remote = NULL;
8700 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8701 struct got_repository *repo = NULL;
8702 struct got_worktree *worktree = NULL;
8703 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8704 struct got_pathlist_head branches;
8705 struct got_pathlist_head tags;
8706 struct got_reflist_head all_branches;
8707 struct got_reflist_head all_tags;
8708 struct got_pathlist_head delete_args;
8709 struct got_pathlist_head delete_branches;
8710 struct got_reflist_entry *re;
8711 struct got_pathlist_entry *pe;
8712 int i, ch, sendfd = -1, sendstatus;
8713 pid_t sendpid = -1;
8714 struct got_send_progress_arg spa;
8715 int verbosity = 0, overwrite_refs = 0;
8716 int send_all_branches = 0, send_all_tags = 0;
8717 struct got_reference *ref = NULL;
8718 int *pack_fds = NULL;
8720 TAILQ_INIT(&branches);
8721 TAILQ_INIT(&tags);
8722 TAILQ_INIT(&all_branches);
8723 TAILQ_INIT(&all_tags);
8724 TAILQ_INIT(&delete_args);
8725 TAILQ_INIT(&delete_branches);
8727 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8728 switch (ch) {
8729 case 'a':
8730 send_all_branches = 1;
8731 break;
8732 case 'b':
8733 error = got_pathlist_append(&branches, optarg, NULL);
8734 if (error)
8735 return error;
8736 nbranches++;
8737 break;
8738 case 'd':
8739 error = got_pathlist_append(&delete_args, optarg, NULL);
8740 if (error)
8741 return error;
8742 break;
8743 case 'f':
8744 overwrite_refs = 1;
8745 break;
8746 case 'r':
8747 repo_path = realpath(optarg, NULL);
8748 if (repo_path == NULL)
8749 return got_error_from_errno2("realpath",
8750 optarg);
8751 got_path_strip_trailing_slashes(repo_path);
8752 break;
8753 case 't':
8754 error = got_pathlist_append(&tags, optarg, NULL);
8755 if (error)
8756 return error;
8757 ntags++;
8758 break;
8759 case 'T':
8760 send_all_tags = 1;
8761 break;
8762 case 'v':
8763 if (verbosity < 0)
8764 verbosity = 0;
8765 else if (verbosity < 3)
8766 verbosity++;
8767 break;
8768 case 'q':
8769 verbosity = -1;
8770 break;
8771 default:
8772 usage_send();
8773 /* NOTREACHED */
8776 argc -= optind;
8777 argv += optind;
8779 if (send_all_branches && !TAILQ_EMPTY(&branches))
8780 option_conflict('a', 'b');
8781 if (send_all_tags && !TAILQ_EMPTY(&tags))
8782 option_conflict('T', 't');
8785 if (argc == 0)
8786 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8787 else if (argc == 1)
8788 remote_name = argv[0];
8789 else
8790 usage_send();
8792 cwd = getcwd(NULL, 0);
8793 if (cwd == NULL) {
8794 error = got_error_from_errno("getcwd");
8795 goto done;
8798 error = got_repo_pack_fds_open(&pack_fds);
8799 if (error != NULL)
8800 goto done;
8802 if (repo_path == NULL) {
8803 error = got_worktree_open(&worktree, cwd);
8804 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8805 goto done;
8806 else
8807 error = NULL;
8808 if (worktree) {
8809 repo_path =
8810 strdup(got_worktree_get_repo_path(worktree));
8811 if (repo_path == NULL)
8812 error = got_error_from_errno("strdup");
8813 if (error)
8814 goto done;
8815 } else {
8816 repo_path = strdup(cwd);
8817 if (repo_path == NULL) {
8818 error = got_error_from_errno("strdup");
8819 goto done;
8824 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8825 if (error)
8826 goto done;
8828 if (worktree) {
8829 worktree_conf = got_worktree_get_gotconfig(worktree);
8830 if (worktree_conf) {
8831 got_gotconfig_get_remotes(&nremotes, &remotes,
8832 worktree_conf);
8833 for (i = 0; i < nremotes; i++) {
8834 if (strcmp(remotes[i].name, remote_name) == 0) {
8835 remote = &remotes[i];
8836 break;
8841 if (remote == NULL) {
8842 repo_conf = got_repo_get_gotconfig(repo);
8843 if (repo_conf) {
8844 got_gotconfig_get_remotes(&nremotes, &remotes,
8845 repo_conf);
8846 for (i = 0; i < nremotes; i++) {
8847 if (strcmp(remotes[i].name, remote_name) == 0) {
8848 remote = &remotes[i];
8849 break;
8854 if (remote == NULL) {
8855 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8856 for (i = 0; i < nremotes; i++) {
8857 if (strcmp(remotes[i].name, remote_name) == 0) {
8858 remote = &remotes[i];
8859 break;
8863 if (remote == NULL) {
8864 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8865 goto done;
8868 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8869 &repo_name, remote->send_url);
8870 if (error)
8871 goto done;
8873 if (strcmp(proto, "git") == 0) {
8874 #ifndef PROFILE
8875 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8876 "sendfd dns inet unveil", NULL) == -1)
8877 err(1, "pledge");
8878 #endif
8879 } else if (strcmp(proto, "git+ssh") == 0 ||
8880 strcmp(proto, "ssh") == 0) {
8881 #ifndef PROFILE
8882 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8883 "sendfd unveil", NULL) == -1)
8884 err(1, "pledge");
8885 #endif
8886 } else if (strcmp(proto, "http") == 0 ||
8887 strcmp(proto, "git+http") == 0) {
8888 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8889 goto done;
8890 } else {
8891 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8892 goto done;
8895 error = got_dial_apply_unveil(proto);
8896 if (error)
8897 goto done;
8899 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8900 if (error)
8901 goto done;
8903 if (send_all_branches) {
8904 error = got_ref_list(&all_branches, repo, "refs/heads",
8905 got_ref_cmp_by_name, NULL);
8906 if (error)
8907 goto done;
8908 TAILQ_FOREACH(re, &all_branches, entry) {
8909 const char *branchname = got_ref_get_name(re->ref);
8910 error = got_pathlist_append(&branches,
8911 branchname, NULL);
8912 if (error)
8913 goto done;
8914 nbranches++;
8916 } else if (nbranches == 0) {
8917 for (i = 0; i < remote->nsend_branches; i++) {
8918 got_pathlist_append(&branches,
8919 remote->send_branches[i], NULL);
8923 if (send_all_tags) {
8924 error = got_ref_list(&all_tags, repo, "refs/tags",
8925 got_ref_cmp_by_name, NULL);
8926 if (error)
8927 goto done;
8928 TAILQ_FOREACH(re, &all_tags, entry) {
8929 const char *tagname = got_ref_get_name(re->ref);
8930 error = got_pathlist_append(&tags,
8931 tagname, NULL);
8932 if (error)
8933 goto done;
8934 ntags++;
8939 * To prevent accidents only branches in refs/heads/ can be deleted
8940 * with 'got send -d'.
8941 * Deleting anything else requires local repository access or Git.
8943 TAILQ_FOREACH(pe, &delete_args, entry) {
8944 const char *branchname = pe->path;
8945 char *s;
8946 struct got_pathlist_entry *new;
8947 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8948 s = strdup(branchname);
8949 if (s == NULL) {
8950 error = got_error_from_errno("strdup");
8951 goto done;
8953 } else {
8954 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8955 error = got_error_from_errno("asprintf");
8956 goto done;
8959 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8960 if (error || new == NULL /* duplicate */)
8961 free(s);
8962 if (error)
8963 goto done;
8964 ndelete_branches++;
8967 if (nbranches == 0 && ndelete_branches == 0) {
8968 struct got_reference *head_ref;
8969 if (worktree)
8970 error = got_ref_open(&head_ref, repo,
8971 got_worktree_get_head_ref_name(worktree), 0);
8972 else
8973 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8974 if (error)
8975 goto done;
8976 if (got_ref_is_symbolic(head_ref)) {
8977 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8978 got_ref_close(head_ref);
8979 if (error)
8980 goto done;
8981 } else
8982 ref = head_ref;
8983 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8984 NULL);
8985 if (error)
8986 goto done;
8987 nbranches++;
8990 if (verbosity >= 0)
8991 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8992 port ? ":" : "", port ? port : "");
8994 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8995 server_path, verbosity);
8996 if (error)
8997 goto done;
8999 memset(&spa, 0, sizeof(spa));
9000 spa.last_scaled_packsize[0] = '\0';
9001 spa.last_p_deltify = -1;
9002 spa.last_p_written = -1;
9003 spa.verbosity = verbosity;
9004 spa.delete_branches = &delete_branches;
9005 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9006 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9007 check_cancelled, NULL);
9008 if (spa.printed_something)
9009 putchar('\n');
9010 if (error)
9011 goto done;
9012 if (!spa.sent_something && verbosity >= 0)
9013 printf("Already up-to-date\n");
9014 done:
9015 if (sendpid > 0) {
9016 if (kill(sendpid, SIGTERM) == -1)
9017 error = got_error_from_errno("kill");
9018 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9019 error = got_error_from_errno("waitpid");
9021 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9022 error = got_error_from_errno("close");
9023 if (repo) {
9024 const struct got_error *close_err = got_repo_close(repo);
9025 if (error == NULL)
9026 error = close_err;
9028 if (worktree)
9029 got_worktree_close(worktree);
9030 if (pack_fds) {
9031 const struct got_error *pack_err =
9032 got_repo_pack_fds_close(pack_fds);
9033 if (error == NULL)
9034 error = pack_err;
9036 if (ref)
9037 got_ref_close(ref);
9038 got_pathlist_free(&branches);
9039 got_pathlist_free(&tags);
9040 got_ref_list_free(&all_branches);
9041 got_ref_list_free(&all_tags);
9042 got_pathlist_free(&delete_args);
9043 TAILQ_FOREACH(pe, &delete_branches, entry)
9044 free((char *)pe->path);
9045 got_pathlist_free(&delete_branches);
9046 free(cwd);
9047 free(repo_path);
9048 free(proto);
9049 free(host);
9050 free(port);
9051 free(server_path);
9052 free(repo_name);
9053 return error;
9056 __dead static void
9057 usage_cherrypick(void)
9059 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9060 exit(1);
9063 static const struct got_error *
9064 cmd_cherrypick(int argc, char *argv[])
9066 const struct got_error *error = NULL;
9067 struct got_worktree *worktree = NULL;
9068 struct got_repository *repo = NULL;
9069 char *cwd = NULL, *commit_id_str = NULL;
9070 struct got_object_id *commit_id = NULL;
9071 struct got_commit_object *commit = NULL;
9072 struct got_object_qid *pid;
9073 int ch;
9074 struct got_update_progress_arg upa;
9075 int *pack_fds = NULL;
9077 while ((ch = getopt(argc, argv, "")) != -1) {
9078 switch (ch) {
9079 default:
9080 usage_cherrypick();
9081 /* NOTREACHED */
9085 argc -= optind;
9086 argv += optind;
9088 #ifndef PROFILE
9089 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9090 "unveil", NULL) == -1)
9091 err(1, "pledge");
9092 #endif
9093 if (argc != 1)
9094 usage_cherrypick();
9096 cwd = getcwd(NULL, 0);
9097 if (cwd == NULL) {
9098 error = got_error_from_errno("getcwd");
9099 goto done;
9102 error = got_repo_pack_fds_open(&pack_fds);
9103 if (error != NULL)
9104 goto done;
9106 error = got_worktree_open(&worktree, cwd);
9107 if (error) {
9108 if (error->code == GOT_ERR_NOT_WORKTREE)
9109 error = wrap_not_worktree_error(error, "cherrypick",
9110 cwd);
9111 goto done;
9114 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9115 NULL, pack_fds);
9116 if (error != NULL)
9117 goto done;
9119 error = apply_unveil(got_repo_get_path(repo), 0,
9120 got_worktree_get_root_path(worktree));
9121 if (error)
9122 goto done;
9124 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9125 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9126 if (error)
9127 goto done;
9128 error = got_object_id_str(&commit_id_str, commit_id);
9129 if (error)
9130 goto done;
9132 error = got_object_open_as_commit(&commit, repo, commit_id);
9133 if (error)
9134 goto done;
9135 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9136 memset(&upa, 0, sizeof(upa));
9137 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9138 commit_id, repo, update_progress, &upa, check_cancelled,
9139 NULL);
9140 if (error != NULL)
9141 goto done;
9143 if (upa.did_something)
9144 printf("Merged commit %s\n", commit_id_str);
9145 print_merge_progress_stats(&upa);
9146 done:
9147 if (commit)
9148 got_object_commit_close(commit);
9149 free(commit_id_str);
9150 if (worktree)
9151 got_worktree_close(worktree);
9152 if (repo) {
9153 const struct got_error *close_err = got_repo_close(repo);
9154 if (error == NULL)
9155 error = close_err;
9157 if (pack_fds) {
9158 const struct got_error *pack_err =
9159 got_repo_pack_fds_close(pack_fds);
9160 if (error == NULL)
9161 error = pack_err;
9164 return error;
9167 __dead static void
9168 usage_backout(void)
9170 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9171 exit(1);
9174 static const struct got_error *
9175 cmd_backout(int argc, char *argv[])
9177 const struct got_error *error = NULL;
9178 struct got_worktree *worktree = NULL;
9179 struct got_repository *repo = NULL;
9180 char *cwd = NULL, *commit_id_str = NULL;
9181 struct got_object_id *commit_id = NULL;
9182 struct got_commit_object *commit = NULL;
9183 struct got_object_qid *pid;
9184 int ch;
9185 struct got_update_progress_arg upa;
9186 int *pack_fds = NULL;
9188 while ((ch = getopt(argc, argv, "")) != -1) {
9189 switch (ch) {
9190 default:
9191 usage_backout();
9192 /* NOTREACHED */
9196 argc -= optind;
9197 argv += optind;
9199 #ifndef PROFILE
9200 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9201 "unveil", NULL) == -1)
9202 err(1, "pledge");
9203 #endif
9204 if (argc != 1)
9205 usage_backout();
9207 cwd = getcwd(NULL, 0);
9208 if (cwd == NULL) {
9209 error = got_error_from_errno("getcwd");
9210 goto done;
9213 error = got_repo_pack_fds_open(&pack_fds);
9214 if (error != NULL)
9215 goto done;
9217 error = got_worktree_open(&worktree, cwd);
9218 if (error) {
9219 if (error->code == GOT_ERR_NOT_WORKTREE)
9220 error = wrap_not_worktree_error(error, "backout", cwd);
9221 goto done;
9224 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9225 NULL, pack_fds);
9226 if (error != NULL)
9227 goto done;
9229 error = apply_unveil(got_repo_get_path(repo), 0,
9230 got_worktree_get_root_path(worktree));
9231 if (error)
9232 goto done;
9234 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9235 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9236 if (error)
9237 goto done;
9238 error = got_object_id_str(&commit_id_str, commit_id);
9239 if (error)
9240 goto done;
9242 error = got_object_open_as_commit(&commit, repo, commit_id);
9243 if (error)
9244 goto done;
9245 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9246 if (pid == NULL) {
9247 error = got_error(GOT_ERR_ROOT_COMMIT);
9248 goto done;
9251 memset(&upa, 0, sizeof(upa));
9252 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9253 repo, update_progress, &upa, check_cancelled, NULL);
9254 if (error != NULL)
9255 goto done;
9257 if (upa.did_something)
9258 printf("Backed out commit %s\n", commit_id_str);
9259 print_merge_progress_stats(&upa);
9260 done:
9261 if (commit)
9262 got_object_commit_close(commit);
9263 free(commit_id_str);
9264 if (worktree)
9265 got_worktree_close(worktree);
9266 if (repo) {
9267 const struct got_error *close_err = got_repo_close(repo);
9268 if (error == NULL)
9269 error = close_err;
9271 if (pack_fds) {
9272 const struct got_error *pack_err =
9273 got_repo_pack_fds_close(pack_fds);
9274 if (error == NULL)
9275 error = pack_err;
9277 return error;
9280 __dead static void
9281 usage_rebase(void)
9283 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9284 getprogname());
9285 exit(1);
9288 static void
9289 trim_logmsg(char *logmsg, int limit)
9291 char *nl;
9292 size_t len;
9294 len = strlen(logmsg);
9295 if (len > limit)
9296 len = limit;
9297 logmsg[len] = '\0';
9298 nl = strchr(logmsg, '\n');
9299 if (nl)
9300 *nl = '\0';
9303 static const struct got_error *
9304 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9306 const struct got_error *err;
9307 char *logmsg0 = NULL;
9308 const char *s;
9310 err = got_object_commit_get_logmsg(&logmsg0, commit);
9311 if (err)
9312 return err;
9314 s = logmsg0;
9315 while (isspace((unsigned char)s[0]))
9316 s++;
9318 *logmsg = strdup(s);
9319 if (*logmsg == NULL) {
9320 err = got_error_from_errno("strdup");
9321 goto done;
9324 trim_logmsg(*logmsg, limit);
9325 done:
9326 free(logmsg0);
9327 return err;
9330 static const struct got_error *
9331 show_rebase_merge_conflict(struct got_object_id *id,
9332 struct got_repository *repo)
9334 const struct got_error *err;
9335 struct got_commit_object *commit = NULL;
9336 char *id_str = NULL, *logmsg = NULL;
9338 err = got_object_open_as_commit(&commit, repo, id);
9339 if (err)
9340 return err;
9342 err = got_object_id_str(&id_str, id);
9343 if (err)
9344 goto done;
9346 id_str[12] = '\0';
9348 err = get_short_logmsg(&logmsg, 42, commit);
9349 if (err)
9350 goto done;
9352 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9353 done:
9354 free(id_str);
9355 got_object_commit_close(commit);
9356 free(logmsg);
9357 return err;
9360 static const struct got_error *
9361 show_rebase_progress(struct got_commit_object *commit,
9362 struct got_object_id *old_id, struct got_object_id *new_id)
9364 const struct got_error *err;
9365 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9367 err = got_object_id_str(&old_id_str, old_id);
9368 if (err)
9369 goto done;
9371 if (new_id) {
9372 err = got_object_id_str(&new_id_str, new_id);
9373 if (err)
9374 goto done;
9377 old_id_str[12] = '\0';
9378 if (new_id_str)
9379 new_id_str[12] = '\0';
9381 err = get_short_logmsg(&logmsg, 42, commit);
9382 if (err)
9383 goto done;
9385 printf("%s -> %s: %s\n", old_id_str,
9386 new_id_str ? new_id_str : "no-op change", logmsg);
9387 done:
9388 free(old_id_str);
9389 free(new_id_str);
9390 free(logmsg);
9391 return err;
9394 static const struct got_error *
9395 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9396 struct got_reference *branch, struct got_reference *new_base_branch,
9397 struct got_reference *tmp_branch, struct got_repository *repo,
9398 int create_backup)
9400 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9401 return got_worktree_rebase_complete(worktree, fileindex,
9402 new_base_branch, tmp_branch, branch, repo, create_backup);
9405 static const struct got_error *
9406 rebase_commit(struct got_pathlist_head *merged_paths,
9407 struct got_worktree *worktree, struct got_fileindex *fileindex,
9408 struct got_reference *tmp_branch,
9409 struct got_object_id *commit_id, struct got_repository *repo)
9411 const struct got_error *error;
9412 struct got_commit_object *commit;
9413 struct got_object_id *new_commit_id;
9415 error = got_object_open_as_commit(&commit, repo, commit_id);
9416 if (error)
9417 return error;
9419 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9420 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9421 if (error) {
9422 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9423 goto done;
9424 error = show_rebase_progress(commit, commit_id, NULL);
9425 } else {
9426 error = show_rebase_progress(commit, commit_id, new_commit_id);
9427 free(new_commit_id);
9429 done:
9430 got_object_commit_close(commit);
9431 return error;
9434 struct check_path_prefix_arg {
9435 const char *path_prefix;
9436 size_t len;
9437 int errcode;
9440 static const struct got_error *
9441 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9442 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9443 struct got_object_id *id1, struct got_object_id *id2,
9444 const char *path1, const char *path2,
9445 mode_t mode1, mode_t mode2, struct got_repository *repo)
9447 struct check_path_prefix_arg *a = arg;
9449 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9450 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9451 return got_error(a->errcode);
9453 return NULL;
9456 static const struct got_error *
9457 check_path_prefix(struct got_object_id *parent_id,
9458 struct got_object_id *commit_id, const char *path_prefix,
9459 int errcode, struct got_repository *repo)
9461 const struct got_error *err;
9462 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9463 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9464 struct check_path_prefix_arg cpp_arg;
9466 if (got_path_is_root_dir(path_prefix))
9467 return NULL;
9469 err = got_object_open_as_commit(&commit, repo, commit_id);
9470 if (err)
9471 goto done;
9473 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9474 if (err)
9475 goto done;
9477 err = got_object_open_as_tree(&tree1, repo,
9478 got_object_commit_get_tree_id(parent_commit));
9479 if (err)
9480 goto done;
9482 err = got_object_open_as_tree(&tree2, repo,
9483 got_object_commit_get_tree_id(commit));
9484 if (err)
9485 goto done;
9487 cpp_arg.path_prefix = path_prefix;
9488 while (cpp_arg.path_prefix[0] == '/')
9489 cpp_arg.path_prefix++;
9490 cpp_arg.len = strlen(cpp_arg.path_prefix);
9491 cpp_arg.errcode = errcode;
9492 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9493 check_path_prefix_in_diff, &cpp_arg, 0);
9494 done:
9495 if (tree1)
9496 got_object_tree_close(tree1);
9497 if (tree2)
9498 got_object_tree_close(tree2);
9499 if (commit)
9500 got_object_commit_close(commit);
9501 if (parent_commit)
9502 got_object_commit_close(parent_commit);
9503 return err;
9506 static const struct got_error *
9507 collect_commits(struct got_object_id_queue *commits,
9508 struct got_object_id *initial_commit_id,
9509 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9510 const char *path_prefix, int path_prefix_errcode,
9511 struct got_repository *repo)
9513 const struct got_error *err = NULL;
9514 struct got_commit_graph *graph = NULL;
9515 struct got_object_id *parent_id = NULL;
9516 struct got_object_qid *qid;
9517 struct got_object_id *commit_id = initial_commit_id;
9519 err = got_commit_graph_open(&graph, "/", 1);
9520 if (err)
9521 return err;
9523 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9524 check_cancelled, NULL);
9525 if (err)
9526 goto done;
9527 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9528 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9529 check_cancelled, NULL);
9530 if (err) {
9531 if (err->code == GOT_ERR_ITER_COMPLETED) {
9532 err = got_error_msg(GOT_ERR_ANCESTRY,
9533 "ran out of commits to rebase before "
9534 "youngest common ancestor commit has "
9535 "been reached?!?");
9537 goto done;
9538 } else {
9539 err = check_path_prefix(parent_id, commit_id,
9540 path_prefix, path_prefix_errcode, repo);
9541 if (err)
9542 goto done;
9544 err = got_object_qid_alloc(&qid, commit_id);
9545 if (err)
9546 goto done;
9547 STAILQ_INSERT_HEAD(commits, qid, entry);
9548 commit_id = parent_id;
9551 done:
9552 got_commit_graph_close(graph);
9553 return err;
9556 static const struct got_error *
9557 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9559 const struct got_error *err = NULL;
9560 time_t committer_time;
9561 struct tm tm;
9562 char datebuf[11]; /* YYYY-MM-DD + NUL */
9563 char *author0 = NULL, *author, *smallerthan;
9564 char *logmsg0 = NULL, *logmsg, *newline;
9566 committer_time = got_object_commit_get_committer_time(commit);
9567 if (gmtime_r(&committer_time, &tm) == NULL)
9568 return got_error_from_errno("gmtime_r");
9569 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9570 return got_error(GOT_ERR_NO_SPACE);
9572 author0 = strdup(got_object_commit_get_author(commit));
9573 if (author0 == NULL)
9574 return got_error_from_errno("strdup");
9575 author = author0;
9576 smallerthan = strchr(author, '<');
9577 if (smallerthan && smallerthan[1] != '\0')
9578 author = smallerthan + 1;
9579 author[strcspn(author, "@>")] = '\0';
9581 err = got_object_commit_get_logmsg(&logmsg0, commit);
9582 if (err)
9583 goto done;
9584 logmsg = logmsg0;
9585 while (*logmsg == '\n')
9586 logmsg++;
9587 newline = strchr(logmsg, '\n');
9588 if (newline)
9589 *newline = '\0';
9591 if (asprintf(brief_str, "%s %s %s",
9592 datebuf, author, logmsg) == -1)
9593 err = got_error_from_errno("asprintf");
9594 done:
9595 free(author0);
9596 free(logmsg0);
9597 return err;
9600 static const struct got_error *
9601 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9602 struct got_repository *repo)
9604 const struct got_error *err;
9605 char *id_str;
9607 err = got_object_id_str(&id_str, id);
9608 if (err)
9609 return err;
9611 err = got_ref_delete(ref, repo);
9612 if (err)
9613 goto done;
9615 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9616 done:
9617 free(id_str);
9618 return err;
9621 static const struct got_error *
9622 print_backup_ref(const char *branch_name, const char *new_id_str,
9623 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9624 struct got_reflist_object_id_map *refs_idmap,
9625 struct got_repository *repo)
9627 const struct got_error *err = NULL;
9628 struct got_reflist_head *refs;
9629 char *refs_str = NULL;
9630 struct got_object_id *new_commit_id = NULL;
9631 struct got_commit_object *new_commit = NULL;
9632 char *new_commit_brief_str = NULL;
9633 struct got_object_id *yca_id = NULL;
9634 struct got_commit_object *yca_commit = NULL;
9635 char *yca_id_str = NULL, *yca_brief_str = NULL;
9636 char *custom_refs_str;
9638 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9639 return got_error_from_errno("asprintf");
9641 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9642 0, 0, refs_idmap, custom_refs_str);
9643 if (err)
9644 goto done;
9646 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9647 if (err)
9648 goto done;
9650 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9651 if (refs) {
9652 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9653 if (err)
9654 goto done;
9657 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9658 if (err)
9659 goto done;
9661 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9662 if (err)
9663 goto done;
9665 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9666 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9667 if (err)
9668 goto done;
9670 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9671 refs_str ? " (" : "", refs_str ? refs_str : "",
9672 refs_str ? ")" : "", new_commit_brief_str);
9673 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9674 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9675 free(refs_str);
9676 refs_str = NULL;
9678 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9679 if (err)
9680 goto done;
9682 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9683 if (err)
9684 goto done;
9686 err = got_object_id_str(&yca_id_str, yca_id);
9687 if (err)
9688 goto done;
9690 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9691 if (refs) {
9692 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9693 if (err)
9694 goto done;
9696 printf("history forked at %s%s%s%s\n %s\n",
9697 yca_id_str,
9698 refs_str ? " (" : "", refs_str ? refs_str : "",
9699 refs_str ? ")" : "", yca_brief_str);
9701 done:
9702 free(custom_refs_str);
9703 free(new_commit_id);
9704 free(refs_str);
9705 free(yca_id);
9706 free(yca_id_str);
9707 free(yca_brief_str);
9708 if (new_commit)
9709 got_object_commit_close(new_commit);
9710 if (yca_commit)
9711 got_object_commit_close(yca_commit);
9713 return NULL;
9716 static const struct got_error *
9717 process_backup_refs(const char *backup_ref_prefix,
9718 const char *wanted_branch_name,
9719 int delete, struct got_repository *repo)
9721 const struct got_error *err;
9722 struct got_reflist_head refs, backup_refs;
9723 struct got_reflist_entry *re;
9724 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9725 struct got_object_id *old_commit_id = NULL;
9726 char *branch_name = NULL;
9727 struct got_commit_object *old_commit = NULL;
9728 struct got_reflist_object_id_map *refs_idmap = NULL;
9729 int wanted_branch_found = 0;
9731 TAILQ_INIT(&refs);
9732 TAILQ_INIT(&backup_refs);
9734 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9735 if (err)
9736 return err;
9738 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9739 if (err)
9740 goto done;
9742 if (wanted_branch_name) {
9743 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9744 wanted_branch_name += 11;
9747 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9748 got_ref_cmp_by_commit_timestamp_descending, repo);
9749 if (err)
9750 goto done;
9752 TAILQ_FOREACH(re, &backup_refs, entry) {
9753 const char *refname = got_ref_get_name(re->ref);
9754 char *slash;
9756 err = check_cancelled(NULL);
9757 if (err)
9758 break;
9760 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9761 if (err)
9762 break;
9764 err = got_object_open_as_commit(&old_commit, repo,
9765 old_commit_id);
9766 if (err)
9767 break;
9769 if (strncmp(backup_ref_prefix, refname,
9770 backup_ref_prefix_len) == 0)
9771 refname += backup_ref_prefix_len;
9773 while (refname[0] == '/')
9774 refname++;
9776 branch_name = strdup(refname);
9777 if (branch_name == NULL) {
9778 err = got_error_from_errno("strdup");
9779 break;
9781 slash = strrchr(branch_name, '/');
9782 if (slash) {
9783 *slash = '\0';
9784 refname += strlen(branch_name) + 1;
9787 if (wanted_branch_name == NULL ||
9788 strcmp(wanted_branch_name, branch_name) == 0) {
9789 wanted_branch_found = 1;
9790 if (delete) {
9791 err = delete_backup_ref(re->ref,
9792 old_commit_id, repo);
9793 } else {
9794 err = print_backup_ref(branch_name, refname,
9795 old_commit_id, old_commit, refs_idmap,
9796 repo);
9798 if (err)
9799 break;
9802 free(old_commit_id);
9803 old_commit_id = NULL;
9804 free(branch_name);
9805 branch_name = NULL;
9806 got_object_commit_close(old_commit);
9807 old_commit = NULL;
9810 if (wanted_branch_name && !wanted_branch_found) {
9811 err = got_error_fmt(GOT_ERR_NOT_REF,
9812 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9814 done:
9815 if (refs_idmap)
9816 got_reflist_object_id_map_free(refs_idmap);
9817 got_ref_list_free(&refs);
9818 got_ref_list_free(&backup_refs);
9819 free(old_commit_id);
9820 free(branch_name);
9821 if (old_commit)
9822 got_object_commit_close(old_commit);
9823 return err;
9826 static const struct got_error *
9827 abort_progress(void *arg, unsigned char status, const char *path)
9830 * Unversioned files should not clutter progress output when
9831 * an operation is aborted.
9833 if (status == GOT_STATUS_UNVERSIONED)
9834 return NULL;
9836 return update_progress(arg, status, path);
9839 static const struct got_error *
9840 cmd_rebase(int argc, char *argv[])
9842 const struct got_error *error = NULL;
9843 struct got_worktree *worktree = NULL;
9844 struct got_repository *repo = NULL;
9845 struct got_fileindex *fileindex = NULL;
9846 char *cwd = NULL;
9847 struct got_reference *branch = NULL;
9848 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9849 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9850 struct got_object_id *resume_commit_id = NULL;
9851 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9852 struct got_commit_object *commit = NULL;
9853 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9854 int histedit_in_progress = 0, merge_in_progress = 0;
9855 int create_backup = 1, list_backups = 0, delete_backups = 0;
9856 struct got_object_id_queue commits;
9857 struct got_pathlist_head merged_paths;
9858 const struct got_object_id_queue *parent_ids;
9859 struct got_object_qid *qid, *pid;
9860 struct got_update_progress_arg upa;
9861 int *pack_fds = NULL;
9863 STAILQ_INIT(&commits);
9864 TAILQ_INIT(&merged_paths);
9865 memset(&upa, 0, sizeof(upa));
9867 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9868 switch (ch) {
9869 case 'a':
9870 abort_rebase = 1;
9871 break;
9872 case 'c':
9873 continue_rebase = 1;
9874 break;
9875 case 'l':
9876 list_backups = 1;
9877 break;
9878 case 'X':
9879 delete_backups = 1;
9880 break;
9881 default:
9882 usage_rebase();
9883 /* NOTREACHED */
9887 argc -= optind;
9888 argv += optind;
9890 #ifndef PROFILE
9891 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9892 "unveil", NULL) == -1)
9893 err(1, "pledge");
9894 #endif
9895 if (list_backups) {
9896 if (abort_rebase)
9897 option_conflict('l', 'a');
9898 if (continue_rebase)
9899 option_conflict('l', 'c');
9900 if (delete_backups)
9901 option_conflict('l', 'X');
9902 if (argc != 0 && argc != 1)
9903 usage_rebase();
9904 } else if (delete_backups) {
9905 if (abort_rebase)
9906 option_conflict('X', 'a');
9907 if (continue_rebase)
9908 option_conflict('X', 'c');
9909 if (list_backups)
9910 option_conflict('l', 'X');
9911 if (argc != 0 && argc != 1)
9912 usage_rebase();
9913 } else {
9914 if (abort_rebase && continue_rebase)
9915 usage_rebase();
9916 else if (abort_rebase || continue_rebase) {
9917 if (argc != 0)
9918 usage_rebase();
9919 } else if (argc != 1)
9920 usage_rebase();
9923 cwd = getcwd(NULL, 0);
9924 if (cwd == NULL) {
9925 error = got_error_from_errno("getcwd");
9926 goto done;
9929 error = got_repo_pack_fds_open(&pack_fds);
9930 if (error != NULL)
9931 goto done;
9933 error = got_worktree_open(&worktree, cwd);
9934 if (error) {
9935 if (list_backups || delete_backups) {
9936 if (error->code != GOT_ERR_NOT_WORKTREE)
9937 goto done;
9938 } else {
9939 if (error->code == GOT_ERR_NOT_WORKTREE)
9940 error = wrap_not_worktree_error(error,
9941 "rebase", cwd);
9942 goto done;
9946 error = got_repo_open(&repo,
9947 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9948 pack_fds);
9949 if (error != NULL)
9950 goto done;
9952 error = apply_unveil(got_repo_get_path(repo), 0,
9953 worktree ? got_worktree_get_root_path(worktree) : NULL);
9954 if (error)
9955 goto done;
9957 if (list_backups || delete_backups) {
9958 error = process_backup_refs(
9959 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9960 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9961 goto done; /* nothing else to do */
9964 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9965 worktree);
9966 if (error)
9967 goto done;
9968 if (histedit_in_progress) {
9969 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9970 goto done;
9973 error = got_worktree_merge_in_progress(&merge_in_progress,
9974 worktree, repo);
9975 if (error)
9976 goto done;
9977 if (merge_in_progress) {
9978 error = got_error(GOT_ERR_MERGE_BUSY);
9979 goto done;
9982 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9983 if (error)
9984 goto done;
9986 if (abort_rebase) {
9987 if (!rebase_in_progress) {
9988 error = got_error(GOT_ERR_NOT_REBASING);
9989 goto done;
9991 error = got_worktree_rebase_continue(&resume_commit_id,
9992 &new_base_branch, &tmp_branch, &branch, &fileindex,
9993 worktree, repo);
9994 if (error)
9995 goto done;
9996 printf("Switching work tree to %s\n",
9997 got_ref_get_symref_target(new_base_branch));
9998 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9999 new_base_branch, abort_progress, &upa);
10000 if (error)
10001 goto done;
10002 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10003 print_merge_progress_stats(&upa);
10004 goto done; /* nothing else to do */
10007 if (continue_rebase) {
10008 if (!rebase_in_progress) {
10009 error = got_error(GOT_ERR_NOT_REBASING);
10010 goto done;
10012 error = got_worktree_rebase_continue(&resume_commit_id,
10013 &new_base_branch, &tmp_branch, &branch, &fileindex,
10014 worktree, repo);
10015 if (error)
10016 goto done;
10018 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10019 resume_commit_id, repo);
10020 if (error)
10021 goto done;
10023 yca_id = got_object_id_dup(resume_commit_id);
10024 if (yca_id == NULL) {
10025 error = got_error_from_errno("got_object_id_dup");
10026 goto done;
10028 } else {
10029 error = got_ref_open(&branch, repo, argv[0], 0);
10030 if (error != NULL)
10031 goto done;
10034 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10035 if (error)
10036 goto done;
10038 if (!continue_rebase) {
10039 struct got_object_id *base_commit_id;
10041 base_commit_id = got_worktree_get_base_commit_id(worktree);
10042 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10043 base_commit_id, branch_head_commit_id, 1, repo,
10044 check_cancelled, NULL);
10045 if (error)
10046 goto done;
10047 if (yca_id == NULL) {
10048 error = got_error_msg(GOT_ERR_ANCESTRY,
10049 "specified branch shares no common ancestry "
10050 "with work tree's branch");
10051 goto done;
10054 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10055 if (error) {
10056 if (error->code != GOT_ERR_ANCESTRY)
10057 goto done;
10058 error = NULL;
10059 } else {
10060 struct got_pathlist_head paths;
10061 printf("%s is already based on %s\n",
10062 got_ref_get_name(branch),
10063 got_worktree_get_head_ref_name(worktree));
10064 error = switch_head_ref(branch, branch_head_commit_id,
10065 worktree, repo);
10066 if (error)
10067 goto done;
10068 error = got_worktree_set_base_commit_id(worktree, repo,
10069 branch_head_commit_id);
10070 if (error)
10071 goto done;
10072 TAILQ_INIT(&paths);
10073 error = got_pathlist_append(&paths, "", NULL);
10074 if (error)
10075 goto done;
10076 error = got_worktree_checkout_files(worktree,
10077 &paths, repo, update_progress, &upa,
10078 check_cancelled, NULL);
10079 got_pathlist_free(&paths);
10080 if (error)
10081 goto done;
10082 if (upa.did_something) {
10083 char *id_str;
10084 error = got_object_id_str(&id_str,
10085 branch_head_commit_id);
10086 if (error)
10087 goto done;
10088 printf("Updated to %s: %s\n",
10089 got_worktree_get_head_ref_name(worktree),
10090 id_str);
10091 free(id_str);
10092 } else
10093 printf("Already up-to-date\n");
10094 print_update_progress_stats(&upa);
10095 goto done;
10099 commit_id = branch_head_commit_id;
10100 error = got_object_open_as_commit(&commit, repo, commit_id);
10101 if (error)
10102 goto done;
10104 parent_ids = got_object_commit_get_parent_ids(commit);
10105 pid = STAILQ_FIRST(parent_ids);
10106 if (pid == NULL) {
10107 error = got_error(GOT_ERR_EMPTY_REBASE);
10108 goto done;
10110 error = collect_commits(&commits, commit_id, &pid->id,
10111 yca_id, got_worktree_get_path_prefix(worktree),
10112 GOT_ERR_REBASE_PATH, repo);
10113 got_object_commit_close(commit);
10114 commit = NULL;
10115 if (error)
10116 goto done;
10118 if (!continue_rebase) {
10119 error = got_worktree_rebase_prepare(&new_base_branch,
10120 &tmp_branch, &fileindex, worktree, branch, repo);
10121 if (error)
10122 goto done;
10125 if (STAILQ_EMPTY(&commits)) {
10126 if (continue_rebase) {
10127 error = rebase_complete(worktree, fileindex,
10128 branch, new_base_branch, tmp_branch, repo,
10129 create_backup);
10130 goto done;
10131 } else {
10132 /* Fast-forward the reference of the branch. */
10133 struct got_object_id *new_head_commit_id;
10134 char *id_str;
10135 error = got_ref_resolve(&new_head_commit_id, repo,
10136 new_base_branch);
10137 if (error)
10138 goto done;
10139 error = got_object_id_str(&id_str, new_head_commit_id);
10140 printf("Forwarding %s to commit %s\n",
10141 got_ref_get_name(branch), id_str);
10142 free(id_str);
10143 error = got_ref_change_ref(branch,
10144 new_head_commit_id);
10145 if (error)
10146 goto done;
10147 /* No backup needed since objects did not change. */
10148 create_backup = 0;
10152 pid = NULL;
10153 STAILQ_FOREACH(qid, &commits, entry) {
10155 commit_id = &qid->id;
10156 parent_id = pid ? &pid->id : yca_id;
10157 pid = qid;
10159 memset(&upa, 0, sizeof(upa));
10160 error = got_worktree_rebase_merge_files(&merged_paths,
10161 worktree, fileindex, parent_id, commit_id, repo,
10162 update_progress, &upa, check_cancelled, NULL);
10163 if (error)
10164 goto done;
10166 print_merge_progress_stats(&upa);
10167 if (upa.conflicts > 0 || upa.missing > 0 ||
10168 upa.not_deleted > 0 || upa.unversioned > 0) {
10169 if (upa.conflicts > 0) {
10170 error = show_rebase_merge_conflict(&qid->id,
10171 repo);
10172 if (error)
10173 goto done;
10175 got_worktree_rebase_pathlist_free(&merged_paths);
10176 break;
10179 error = rebase_commit(&merged_paths, worktree, fileindex,
10180 tmp_branch, commit_id, repo);
10181 got_worktree_rebase_pathlist_free(&merged_paths);
10182 if (error)
10183 goto done;
10186 if (upa.conflicts > 0 || upa.missing > 0 ||
10187 upa.not_deleted > 0 || upa.unversioned > 0) {
10188 error = got_worktree_rebase_postpone(worktree, fileindex);
10189 if (error)
10190 goto done;
10191 if (upa.conflicts > 0 && upa.missing == 0 &&
10192 upa.not_deleted == 0 && upa.unversioned == 0) {
10193 error = got_error_msg(GOT_ERR_CONFLICTS,
10194 "conflicts must be resolved before rebasing "
10195 "can continue");
10196 } else if (upa.conflicts > 0) {
10197 error = got_error_msg(GOT_ERR_CONFLICTS,
10198 "conflicts must be resolved before rebasing "
10199 "can continue; changes destined for some "
10200 "files were not yet merged and should be "
10201 "merged manually if required before the "
10202 "rebase operation is continued");
10203 } else {
10204 error = got_error_msg(GOT_ERR_CONFLICTS,
10205 "changes destined for some files were not "
10206 "yet merged and should be merged manually "
10207 "if required before the rebase operation "
10208 "is continued");
10210 } else
10211 error = rebase_complete(worktree, fileindex, branch,
10212 new_base_branch, tmp_branch, repo, create_backup);
10213 done:
10214 got_object_id_queue_free(&commits);
10215 free(branch_head_commit_id);
10216 free(resume_commit_id);
10217 free(yca_id);
10218 if (commit)
10219 got_object_commit_close(commit);
10220 if (branch)
10221 got_ref_close(branch);
10222 if (new_base_branch)
10223 got_ref_close(new_base_branch);
10224 if (tmp_branch)
10225 got_ref_close(tmp_branch);
10226 if (worktree)
10227 got_worktree_close(worktree);
10228 if (repo) {
10229 const struct got_error *close_err = got_repo_close(repo);
10230 if (error == NULL)
10231 error = close_err;
10233 if (pack_fds) {
10234 const struct got_error *pack_err =
10235 got_repo_pack_fds_close(pack_fds);
10236 if (error == NULL)
10237 error = pack_err;
10239 return error;
10242 __dead static void
10243 usage_histedit(void)
10245 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10246 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10247 getprogname());
10248 exit(1);
10251 #define GOT_HISTEDIT_PICK 'p'
10252 #define GOT_HISTEDIT_EDIT 'e'
10253 #define GOT_HISTEDIT_FOLD 'f'
10254 #define GOT_HISTEDIT_DROP 'd'
10255 #define GOT_HISTEDIT_MESG 'm'
10257 static const struct got_histedit_cmd {
10258 unsigned char code;
10259 const char *name;
10260 const char *desc;
10261 } got_histedit_cmds[] = {
10262 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10263 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10264 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10265 "be used" },
10266 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10267 { GOT_HISTEDIT_MESG, "mesg",
10268 "single-line log message for commit above (open editor if empty)" },
10271 struct got_histedit_list_entry {
10272 TAILQ_ENTRY(got_histedit_list_entry) entry;
10273 struct got_object_id *commit_id;
10274 const struct got_histedit_cmd *cmd;
10275 char *logmsg;
10277 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10279 static const struct got_error *
10280 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10281 FILE *f, struct got_repository *repo)
10283 const struct got_error *err = NULL;
10284 char *logmsg = NULL, *id_str = NULL;
10285 struct got_commit_object *commit = NULL;
10286 int n;
10288 err = got_object_open_as_commit(&commit, repo, commit_id);
10289 if (err)
10290 goto done;
10292 err = get_short_logmsg(&logmsg, 34, commit);
10293 if (err)
10294 goto done;
10296 err = got_object_id_str(&id_str, commit_id);
10297 if (err)
10298 goto done;
10300 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10301 if (n < 0)
10302 err = got_ferror(f, GOT_ERR_IO);
10303 done:
10304 if (commit)
10305 got_object_commit_close(commit);
10306 free(id_str);
10307 free(logmsg);
10308 return err;
10311 static const struct got_error *
10312 histedit_write_commit_list(struct got_object_id_queue *commits,
10313 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10314 struct got_repository *repo)
10316 const struct got_error *err = NULL;
10317 struct got_object_qid *qid;
10318 const char *histedit_cmd = NULL;
10320 if (STAILQ_EMPTY(commits))
10321 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10323 STAILQ_FOREACH(qid, commits, entry) {
10324 histedit_cmd = got_histedit_cmds[0].name;
10325 if (edit_only)
10326 histedit_cmd = "edit";
10327 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10328 histedit_cmd = "fold";
10329 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10330 if (err)
10331 break;
10332 if (edit_logmsg_only) {
10333 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10334 if (n < 0) {
10335 err = got_ferror(f, GOT_ERR_IO);
10336 break;
10341 return err;
10344 static const struct got_error *
10345 write_cmd_list(FILE *f, const char *branch_name,
10346 struct got_object_id_queue *commits)
10348 const struct got_error *err = NULL;
10349 size_t i;
10350 int n;
10351 char *id_str;
10352 struct got_object_qid *qid;
10354 qid = STAILQ_FIRST(commits);
10355 err = got_object_id_str(&id_str, &qid->id);
10356 if (err)
10357 return err;
10359 n = fprintf(f,
10360 "# Editing the history of branch '%s' starting at\n"
10361 "# commit %s\n"
10362 "# Commits will be processed in order from top to "
10363 "bottom of this file.\n", branch_name, id_str);
10364 if (n < 0) {
10365 err = got_ferror(f, GOT_ERR_IO);
10366 goto done;
10369 n = fprintf(f, "# Available histedit commands:\n");
10370 if (n < 0) {
10371 err = got_ferror(f, GOT_ERR_IO);
10372 goto done;
10375 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10376 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10377 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10378 cmd->desc);
10379 if (n < 0) {
10380 err = got_ferror(f, GOT_ERR_IO);
10381 break;
10384 done:
10385 free(id_str);
10386 return err;
10389 static const struct got_error *
10390 histedit_syntax_error(int lineno)
10392 static char msg[42];
10393 int ret;
10395 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10396 lineno);
10397 if (ret == -1 || ret >= sizeof(msg))
10398 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10400 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10403 static const struct got_error *
10404 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10405 char *logmsg, struct got_repository *repo)
10407 const struct got_error *err;
10408 struct got_commit_object *folded_commit = NULL;
10409 char *id_str, *folded_logmsg = NULL;
10411 err = got_object_id_str(&id_str, hle->commit_id);
10412 if (err)
10413 return err;
10415 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10416 if (err)
10417 goto done;
10419 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10420 if (err)
10421 goto done;
10422 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10423 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10424 folded_logmsg) == -1) {
10425 err = got_error_from_errno("asprintf");
10427 done:
10428 if (folded_commit)
10429 got_object_commit_close(folded_commit);
10430 free(id_str);
10431 free(folded_logmsg);
10432 return err;
10435 static struct got_histedit_list_entry *
10436 get_folded_commits(struct got_histedit_list_entry *hle)
10438 struct got_histedit_list_entry *prev, *folded = NULL;
10440 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10441 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10442 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10443 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10444 folded = prev;
10445 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10448 return folded;
10451 static const struct got_error *
10452 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10453 struct got_repository *repo)
10455 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10456 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10457 const struct got_error *err = NULL;
10458 struct got_commit_object *commit = NULL;
10459 int logmsg_len;
10460 int fd;
10461 struct got_histedit_list_entry *folded = NULL;
10463 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10464 if (err)
10465 return err;
10467 folded = get_folded_commits(hle);
10468 if (folded) {
10469 while (folded != hle) {
10470 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10471 folded = TAILQ_NEXT(folded, entry);
10472 continue;
10474 err = append_folded_commit_msg(&new_msg, folded,
10475 logmsg, repo);
10476 if (err)
10477 goto done;
10478 free(logmsg);
10479 logmsg = new_msg;
10480 folded = TAILQ_NEXT(folded, entry);
10484 err = got_object_id_str(&id_str, hle->commit_id);
10485 if (err)
10486 goto done;
10487 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10488 if (err)
10489 goto done;
10490 logmsg_len = asprintf(&new_msg,
10491 "%s\n# original log message of commit %s: %s",
10492 logmsg ? logmsg : "", id_str, orig_logmsg);
10493 if (logmsg_len == -1) {
10494 err = got_error_from_errno("asprintf");
10495 goto done;
10497 free(logmsg);
10498 logmsg = new_msg;
10500 err = got_object_id_str(&id_str, hle->commit_id);
10501 if (err)
10502 goto done;
10504 err = got_opentemp_named_fd(&logmsg_path, &fd,
10505 GOT_TMPDIR_STR "/got-logmsg");
10506 if (err)
10507 goto done;
10509 write(fd, logmsg, logmsg_len);
10510 close(fd);
10512 err = get_editor(&editor);
10513 if (err)
10514 goto done;
10516 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10517 logmsg_len, 0);
10518 if (err) {
10519 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10520 goto done;
10521 err = NULL;
10522 hle->logmsg = strdup(new_msg);
10523 if (hle->logmsg == NULL)
10524 err = got_error_from_errno("strdup");
10526 done:
10527 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10528 err = got_error_from_errno2("unlink", logmsg_path);
10529 free(logmsg_path);
10530 free(logmsg);
10531 free(orig_logmsg);
10532 free(editor);
10533 if (commit)
10534 got_object_commit_close(commit);
10535 return err;
10538 static const struct got_error *
10539 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10540 FILE *f, struct got_repository *repo)
10542 const struct got_error *err = NULL;
10543 char *line = NULL, *p, *end;
10544 size_t i, size;
10545 ssize_t len;
10546 int lineno = 0;
10547 const struct got_histedit_cmd *cmd;
10548 struct got_object_id *commit_id = NULL;
10549 struct got_histedit_list_entry *hle = NULL;
10551 for (;;) {
10552 len = getline(&line, &size, f);
10553 if (len == -1) {
10554 const struct got_error *getline_err;
10555 if (feof(f))
10556 break;
10557 getline_err = got_error_from_errno("getline");
10558 err = got_ferror(f, getline_err->code);
10559 break;
10561 lineno++;
10562 p = line;
10563 while (isspace((unsigned char)p[0]))
10564 p++;
10565 if (p[0] == '#' || p[0] == '\0') {
10566 free(line);
10567 line = NULL;
10568 continue;
10570 cmd = NULL;
10571 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10572 cmd = &got_histedit_cmds[i];
10573 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10574 isspace((unsigned char)p[strlen(cmd->name)])) {
10575 p += strlen(cmd->name);
10576 break;
10578 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10579 p++;
10580 break;
10583 if (i == nitems(got_histedit_cmds)) {
10584 err = histedit_syntax_error(lineno);
10585 break;
10587 while (isspace((unsigned char)p[0]))
10588 p++;
10589 if (cmd->code == GOT_HISTEDIT_MESG) {
10590 if (hle == NULL || hle->logmsg != NULL) {
10591 err = got_error(GOT_ERR_HISTEDIT_CMD);
10592 break;
10594 if (p[0] == '\0') {
10595 err = histedit_edit_logmsg(hle, repo);
10596 if (err)
10597 break;
10598 } else {
10599 hle->logmsg = strdup(p);
10600 if (hle->logmsg == NULL) {
10601 err = got_error_from_errno("strdup");
10602 break;
10605 free(line);
10606 line = NULL;
10607 continue;
10608 } else {
10609 end = p;
10610 while (end[0] && !isspace((unsigned char)end[0]))
10611 end++;
10612 *end = '\0';
10614 err = got_object_resolve_id_str(&commit_id, repo, p);
10615 if (err) {
10616 /* override error code */
10617 err = histedit_syntax_error(lineno);
10618 break;
10621 hle = malloc(sizeof(*hle));
10622 if (hle == NULL) {
10623 err = got_error_from_errno("malloc");
10624 break;
10626 hle->cmd = cmd;
10627 hle->commit_id = commit_id;
10628 hle->logmsg = NULL;
10629 commit_id = NULL;
10630 free(line);
10631 line = NULL;
10632 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10635 free(line);
10636 free(commit_id);
10637 return err;
10640 static const struct got_error *
10641 histedit_check_script(struct got_histedit_list *histedit_cmds,
10642 struct got_object_id_queue *commits, struct got_repository *repo)
10644 const struct got_error *err = NULL;
10645 struct got_object_qid *qid;
10646 struct got_histedit_list_entry *hle;
10647 static char msg[92];
10648 char *id_str;
10650 if (TAILQ_EMPTY(histedit_cmds))
10651 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10652 "histedit script contains no commands");
10653 if (STAILQ_EMPTY(commits))
10654 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10656 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10657 struct got_histedit_list_entry *hle2;
10658 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10659 if (hle == hle2)
10660 continue;
10661 if (got_object_id_cmp(hle->commit_id,
10662 hle2->commit_id) != 0)
10663 continue;
10664 err = got_object_id_str(&id_str, hle->commit_id);
10665 if (err)
10666 return err;
10667 snprintf(msg, sizeof(msg), "commit %s is listed "
10668 "more than once in histedit script", id_str);
10669 free(id_str);
10670 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10674 STAILQ_FOREACH(qid, commits, entry) {
10675 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10676 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10677 break;
10679 if (hle == NULL) {
10680 err = got_object_id_str(&id_str, &qid->id);
10681 if (err)
10682 return err;
10683 snprintf(msg, sizeof(msg),
10684 "commit %s missing from histedit script", id_str);
10685 free(id_str);
10686 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10690 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10691 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10692 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10693 "last commit in histedit script cannot be folded");
10695 return NULL;
10698 static const struct got_error *
10699 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10700 const char *path, struct got_object_id_queue *commits,
10701 struct got_repository *repo)
10703 const struct got_error *err = NULL;
10704 char *editor;
10705 FILE *f = NULL;
10707 err = get_editor(&editor);
10708 if (err)
10709 return err;
10711 if (spawn_editor(editor, path) == -1) {
10712 err = got_error_from_errno("failed spawning editor");
10713 goto done;
10716 f = fopen(path, "re");
10717 if (f == NULL) {
10718 err = got_error_from_errno("fopen");
10719 goto done;
10721 err = histedit_parse_list(histedit_cmds, f, repo);
10722 if (err)
10723 goto done;
10725 err = histedit_check_script(histedit_cmds, commits, repo);
10726 done:
10727 if (f && fclose(f) == EOF && err == NULL)
10728 err = got_error_from_errno("fclose");
10729 free(editor);
10730 return err;
10733 static const struct got_error *
10734 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10735 struct got_object_id_queue *, const char *, const char *,
10736 struct got_repository *);
10738 static const struct got_error *
10739 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10740 struct got_object_id_queue *commits, const char *branch_name,
10741 int edit_logmsg_only, int fold_only, int edit_only,
10742 struct got_repository *repo)
10744 const struct got_error *err;
10745 FILE *f = NULL;
10746 char *path = NULL;
10748 err = got_opentemp_named(&path, &f, "got-histedit");
10749 if (err)
10750 return err;
10752 err = write_cmd_list(f, branch_name, commits);
10753 if (err)
10754 goto done;
10756 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10757 fold_only, edit_only, repo);
10758 if (err)
10759 goto done;
10761 if (edit_logmsg_only || fold_only || edit_only) {
10762 rewind(f);
10763 err = histedit_parse_list(histedit_cmds, f, repo);
10764 } else {
10765 if (fclose(f) == EOF) {
10766 err = got_error_from_errno("fclose");
10767 goto done;
10769 f = NULL;
10770 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10771 if (err) {
10772 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10773 err->code != GOT_ERR_HISTEDIT_CMD)
10774 goto done;
10775 err = histedit_edit_list_retry(histedit_cmds, err,
10776 commits, path, branch_name, repo);
10779 done:
10780 if (f && fclose(f) == EOF && err == NULL)
10781 err = got_error_from_errno("fclose");
10782 if (path && unlink(path) != 0 && err == NULL)
10783 err = got_error_from_errno2("unlink", path);
10784 free(path);
10785 return err;
10788 static const struct got_error *
10789 histedit_save_list(struct got_histedit_list *histedit_cmds,
10790 struct got_worktree *worktree, struct got_repository *repo)
10792 const struct got_error *err = NULL;
10793 char *path = NULL;
10794 FILE *f = NULL;
10795 struct got_histedit_list_entry *hle;
10796 struct got_commit_object *commit = NULL;
10798 err = got_worktree_get_histedit_script_path(&path, worktree);
10799 if (err)
10800 return err;
10802 f = fopen(path, "we");
10803 if (f == NULL) {
10804 err = got_error_from_errno2("fopen", path);
10805 goto done;
10807 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10808 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10809 repo);
10810 if (err)
10811 break;
10813 if (hle->logmsg) {
10814 int n = fprintf(f, "%c %s\n",
10815 GOT_HISTEDIT_MESG, hle->logmsg);
10816 if (n < 0) {
10817 err = got_ferror(f, GOT_ERR_IO);
10818 break;
10822 done:
10823 if (f && fclose(f) == EOF && err == NULL)
10824 err = got_error_from_errno("fclose");
10825 free(path);
10826 if (commit)
10827 got_object_commit_close(commit);
10828 return err;
10831 static void
10832 histedit_free_list(struct got_histedit_list *histedit_cmds)
10834 struct got_histedit_list_entry *hle;
10836 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10837 TAILQ_REMOVE(histedit_cmds, hle, entry);
10838 free(hle);
10842 static const struct got_error *
10843 histedit_load_list(struct got_histedit_list *histedit_cmds,
10844 const char *path, struct got_repository *repo)
10846 const struct got_error *err = NULL;
10847 FILE *f = NULL;
10849 f = fopen(path, "re");
10850 if (f == NULL) {
10851 err = got_error_from_errno2("fopen", path);
10852 goto done;
10855 err = histedit_parse_list(histedit_cmds, f, repo);
10856 done:
10857 if (f && fclose(f) == EOF && err == NULL)
10858 err = got_error_from_errno("fclose");
10859 return err;
10862 static const struct got_error *
10863 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10864 const struct got_error *edit_err, struct got_object_id_queue *commits,
10865 const char *path, const char *branch_name, struct got_repository *repo)
10867 const struct got_error *err = NULL, *prev_err = edit_err;
10868 int resp = ' ';
10870 while (resp != 'c' && resp != 'r' && resp != 'a') {
10871 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10872 "or (a)bort: ", getprogname(), prev_err->msg);
10873 resp = getchar();
10874 if (resp == '\n')
10875 resp = getchar();
10876 if (resp == 'c') {
10877 histedit_free_list(histedit_cmds);
10878 err = histedit_run_editor(histedit_cmds, path, commits,
10879 repo);
10880 if (err) {
10881 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10882 err->code != GOT_ERR_HISTEDIT_CMD)
10883 break;
10884 prev_err = err;
10885 resp = ' ';
10886 continue;
10888 break;
10889 } else if (resp == 'r') {
10890 histedit_free_list(histedit_cmds);
10891 err = histedit_edit_script(histedit_cmds,
10892 commits, branch_name, 0, 0, 0, repo);
10893 if (err) {
10894 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10895 err->code != GOT_ERR_HISTEDIT_CMD)
10896 break;
10897 prev_err = err;
10898 resp = ' ';
10899 continue;
10901 break;
10902 } else if (resp == 'a') {
10903 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10904 break;
10905 } else
10906 printf("invalid response '%c'\n", resp);
10909 return err;
10912 static const struct got_error *
10913 histedit_complete(struct got_worktree *worktree,
10914 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10915 struct got_reference *branch, struct got_repository *repo)
10917 printf("Switching work tree to %s\n",
10918 got_ref_get_symref_target(branch));
10919 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10920 branch, repo);
10923 static const struct got_error *
10924 show_histedit_progress(struct got_commit_object *commit,
10925 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10927 const struct got_error *err;
10928 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10930 err = got_object_id_str(&old_id_str, hle->commit_id);
10931 if (err)
10932 goto done;
10934 if (new_id) {
10935 err = got_object_id_str(&new_id_str, new_id);
10936 if (err)
10937 goto done;
10940 old_id_str[12] = '\0';
10941 if (new_id_str)
10942 new_id_str[12] = '\0';
10944 if (hle->logmsg) {
10945 logmsg = strdup(hle->logmsg);
10946 if (logmsg == NULL) {
10947 err = got_error_from_errno("strdup");
10948 goto done;
10950 trim_logmsg(logmsg, 42);
10951 } else {
10952 err = get_short_logmsg(&logmsg, 42, commit);
10953 if (err)
10954 goto done;
10957 switch (hle->cmd->code) {
10958 case GOT_HISTEDIT_PICK:
10959 case GOT_HISTEDIT_EDIT:
10960 printf("%s -> %s: %s\n", old_id_str,
10961 new_id_str ? new_id_str : "no-op change", logmsg);
10962 break;
10963 case GOT_HISTEDIT_DROP:
10964 case GOT_HISTEDIT_FOLD:
10965 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10966 logmsg);
10967 break;
10968 default:
10969 break;
10971 done:
10972 free(old_id_str);
10973 free(new_id_str);
10974 return err;
10977 static const struct got_error *
10978 histedit_commit(struct got_pathlist_head *merged_paths,
10979 struct got_worktree *worktree, struct got_fileindex *fileindex,
10980 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10981 struct got_repository *repo)
10983 const struct got_error *err;
10984 struct got_commit_object *commit;
10985 struct got_object_id *new_commit_id;
10987 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10988 && hle->logmsg == NULL) {
10989 err = histedit_edit_logmsg(hle, repo);
10990 if (err)
10991 return err;
10994 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10995 if (err)
10996 return err;
10998 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10999 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11000 hle->logmsg, repo);
11001 if (err) {
11002 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11003 goto done;
11004 err = show_histedit_progress(commit, hle, NULL);
11005 } else {
11006 err = show_histedit_progress(commit, hle, new_commit_id);
11007 free(new_commit_id);
11009 done:
11010 got_object_commit_close(commit);
11011 return err;
11014 static const struct got_error *
11015 histedit_skip_commit(struct got_histedit_list_entry *hle,
11016 struct got_worktree *worktree, struct got_repository *repo)
11018 const struct got_error *error;
11019 struct got_commit_object *commit;
11021 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11022 repo);
11023 if (error)
11024 return error;
11026 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11027 if (error)
11028 return error;
11030 error = show_histedit_progress(commit, hle, NULL);
11031 got_object_commit_close(commit);
11032 return error;
11035 static const struct got_error *
11036 check_local_changes(void *arg, unsigned char status,
11037 unsigned char staged_status, const char *path,
11038 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11039 struct got_object_id *commit_id, int dirfd, const char *de_name)
11041 int *have_local_changes = arg;
11043 switch (status) {
11044 case GOT_STATUS_ADD:
11045 case GOT_STATUS_DELETE:
11046 case GOT_STATUS_MODIFY:
11047 case GOT_STATUS_CONFLICT:
11048 *have_local_changes = 1;
11049 return got_error(GOT_ERR_CANCELLED);
11050 default:
11051 break;
11054 switch (staged_status) {
11055 case GOT_STATUS_ADD:
11056 case GOT_STATUS_DELETE:
11057 case GOT_STATUS_MODIFY:
11058 *have_local_changes = 1;
11059 return got_error(GOT_ERR_CANCELLED);
11060 default:
11061 break;
11064 return NULL;
11067 static const struct got_error *
11068 cmd_histedit(int argc, char *argv[])
11070 const struct got_error *error = NULL;
11071 struct got_worktree *worktree = NULL;
11072 struct got_fileindex *fileindex = NULL;
11073 struct got_repository *repo = NULL;
11074 char *cwd = NULL;
11075 struct got_reference *branch = NULL;
11076 struct got_reference *tmp_branch = NULL;
11077 struct got_object_id *resume_commit_id = NULL;
11078 struct got_object_id *base_commit_id = NULL;
11079 struct got_object_id *head_commit_id = NULL;
11080 struct got_commit_object *commit = NULL;
11081 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11082 struct got_update_progress_arg upa;
11083 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11084 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11085 int list_backups = 0, delete_backups = 0;
11086 const char *edit_script_path = NULL;
11087 struct got_object_id_queue commits;
11088 struct got_pathlist_head merged_paths;
11089 const struct got_object_id_queue *parent_ids;
11090 struct got_object_qid *pid;
11091 struct got_histedit_list histedit_cmds;
11092 struct got_histedit_list_entry *hle;
11093 int *pack_fds = NULL;
11095 STAILQ_INIT(&commits);
11096 TAILQ_INIT(&histedit_cmds);
11097 TAILQ_INIT(&merged_paths);
11098 memset(&upa, 0, sizeof(upa));
11100 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11101 switch (ch) {
11102 case 'a':
11103 abort_edit = 1;
11104 break;
11105 case 'c':
11106 continue_edit = 1;
11107 break;
11108 case 'e':
11109 edit_only = 1;
11110 break;
11111 case 'f':
11112 fold_only = 1;
11113 break;
11114 case 'F':
11115 edit_script_path = optarg;
11116 break;
11117 case 'm':
11118 edit_logmsg_only = 1;
11119 break;
11120 case 'l':
11121 list_backups = 1;
11122 break;
11123 case 'X':
11124 delete_backups = 1;
11125 break;
11126 default:
11127 usage_histedit();
11128 /* NOTREACHED */
11132 argc -= optind;
11133 argv += optind;
11135 #ifndef PROFILE
11136 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11137 "unveil", NULL) == -1)
11138 err(1, "pledge");
11139 #endif
11140 if (abort_edit && continue_edit)
11141 option_conflict('a', 'c');
11142 if (edit_script_path && edit_logmsg_only)
11143 option_conflict('F', 'm');
11144 if (abort_edit && edit_logmsg_only)
11145 option_conflict('a', 'm');
11146 if (continue_edit && edit_logmsg_only)
11147 option_conflict('c', 'm');
11148 if (abort_edit && fold_only)
11149 option_conflict('a', 'f');
11150 if (continue_edit && fold_only)
11151 option_conflict('c', 'f');
11152 if (fold_only && edit_logmsg_only)
11153 option_conflict('f', 'm');
11154 if (edit_script_path && fold_only)
11155 option_conflict('F', 'f');
11156 if (abort_edit && edit_only)
11157 option_conflict('a', 'e');
11158 if (continue_edit && edit_only)
11159 option_conflict('c', 'e');
11160 if (edit_only && edit_logmsg_only)
11161 option_conflict('e', 'm');
11162 if (edit_script_path && edit_only)
11163 option_conflict('F', 'e');
11164 if (list_backups) {
11165 if (abort_edit)
11166 option_conflict('l', 'a');
11167 if (continue_edit)
11168 option_conflict('l', 'c');
11169 if (edit_script_path)
11170 option_conflict('l', 'F');
11171 if (edit_logmsg_only)
11172 option_conflict('l', 'm');
11173 if (fold_only)
11174 option_conflict('l', 'f');
11175 if (edit_only)
11176 option_conflict('l', 'e');
11177 if (delete_backups)
11178 option_conflict('l', 'X');
11179 if (argc != 0 && argc != 1)
11180 usage_histedit();
11181 } else if (delete_backups) {
11182 if (abort_edit)
11183 option_conflict('X', 'a');
11184 if (continue_edit)
11185 option_conflict('X', 'c');
11186 if (edit_script_path)
11187 option_conflict('X', 'F');
11188 if (edit_logmsg_only)
11189 option_conflict('X', 'm');
11190 if (fold_only)
11191 option_conflict('X', 'f');
11192 if (edit_only)
11193 option_conflict('X', 'e');
11194 if (list_backups)
11195 option_conflict('X', 'l');
11196 if (argc != 0 && argc != 1)
11197 usage_histedit();
11198 } else if (argc != 0)
11199 usage_histedit();
11202 * This command cannot apply unveil(2) in all cases because the
11203 * user may choose to run an editor to edit the histedit script
11204 * and to edit individual commit log messages.
11205 * unveil(2) traverses exec(2); if an editor is used we have to
11206 * apply unveil after edit script and log messages have been written.
11207 * XXX TODO: Make use of unveil(2) where possible.
11210 cwd = getcwd(NULL, 0);
11211 if (cwd == NULL) {
11212 error = got_error_from_errno("getcwd");
11213 goto done;
11216 error = got_repo_pack_fds_open(&pack_fds);
11217 if (error != NULL)
11218 goto done;
11220 error = got_worktree_open(&worktree, cwd);
11221 if (error) {
11222 if (list_backups || delete_backups) {
11223 if (error->code != GOT_ERR_NOT_WORKTREE)
11224 goto done;
11225 } else {
11226 if (error->code == GOT_ERR_NOT_WORKTREE)
11227 error = wrap_not_worktree_error(error,
11228 "histedit", cwd);
11229 goto done;
11233 if (list_backups || delete_backups) {
11234 error = got_repo_open(&repo,
11235 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11236 NULL, pack_fds);
11237 if (error != NULL)
11238 goto done;
11239 error = apply_unveil(got_repo_get_path(repo), 0,
11240 worktree ? got_worktree_get_root_path(worktree) : NULL);
11241 if (error)
11242 goto done;
11243 error = process_backup_refs(
11244 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11245 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11246 goto done; /* nothing else to do */
11249 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11250 NULL, pack_fds);
11251 if (error != NULL)
11252 goto done;
11254 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11255 if (error)
11256 goto done;
11257 if (rebase_in_progress) {
11258 error = got_error(GOT_ERR_REBASING);
11259 goto done;
11262 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11263 repo);
11264 if (error)
11265 goto done;
11266 if (merge_in_progress) {
11267 error = got_error(GOT_ERR_MERGE_BUSY);
11268 goto done;
11271 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11272 if (error)
11273 goto done;
11275 if (edit_in_progress && edit_logmsg_only) {
11276 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11277 "histedit operation is in progress in this "
11278 "work tree and must be continued or aborted "
11279 "before the -m option can be used");
11280 goto done;
11282 if (edit_in_progress && fold_only) {
11283 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11284 "histedit operation is in progress in this "
11285 "work tree and must be continued or aborted "
11286 "before the -f option can be used");
11287 goto done;
11289 if (edit_in_progress && edit_only) {
11290 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11291 "histedit operation is in progress in this "
11292 "work tree and must be continued or aborted "
11293 "before the -e option can be used");
11294 goto done;
11297 if (edit_in_progress && abort_edit) {
11298 error = got_worktree_histedit_continue(&resume_commit_id,
11299 &tmp_branch, &branch, &base_commit_id, &fileindex,
11300 worktree, repo);
11301 if (error)
11302 goto done;
11303 printf("Switching work tree to %s\n",
11304 got_ref_get_symref_target(branch));
11305 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11306 branch, base_commit_id, abort_progress, &upa);
11307 if (error)
11308 goto done;
11309 printf("Histedit of %s aborted\n",
11310 got_ref_get_symref_target(branch));
11311 print_merge_progress_stats(&upa);
11312 goto done; /* nothing else to do */
11313 } else if (abort_edit) {
11314 error = got_error(GOT_ERR_NOT_HISTEDIT);
11315 goto done;
11318 if (continue_edit) {
11319 char *path;
11321 if (!edit_in_progress) {
11322 error = got_error(GOT_ERR_NOT_HISTEDIT);
11323 goto done;
11326 error = got_worktree_get_histedit_script_path(&path, worktree);
11327 if (error)
11328 goto done;
11330 error = histedit_load_list(&histedit_cmds, path, repo);
11331 free(path);
11332 if (error)
11333 goto done;
11335 error = got_worktree_histedit_continue(&resume_commit_id,
11336 &tmp_branch, &branch, &base_commit_id, &fileindex,
11337 worktree, repo);
11338 if (error)
11339 goto done;
11341 error = got_ref_resolve(&head_commit_id, repo, branch);
11342 if (error)
11343 goto done;
11345 error = got_object_open_as_commit(&commit, repo,
11346 head_commit_id);
11347 if (error)
11348 goto done;
11349 parent_ids = got_object_commit_get_parent_ids(commit);
11350 pid = STAILQ_FIRST(parent_ids);
11351 if (pid == NULL) {
11352 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11353 goto done;
11355 error = collect_commits(&commits, head_commit_id, &pid->id,
11356 base_commit_id, got_worktree_get_path_prefix(worktree),
11357 GOT_ERR_HISTEDIT_PATH, repo);
11358 got_object_commit_close(commit);
11359 commit = NULL;
11360 if (error)
11361 goto done;
11362 } else {
11363 if (edit_in_progress) {
11364 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11365 goto done;
11368 error = got_ref_open(&branch, repo,
11369 got_worktree_get_head_ref_name(worktree), 0);
11370 if (error != NULL)
11371 goto done;
11373 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11374 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11375 "will not edit commit history of a branch outside "
11376 "the \"refs/heads/\" reference namespace");
11377 goto done;
11380 error = got_ref_resolve(&head_commit_id, repo, branch);
11381 got_ref_close(branch);
11382 branch = NULL;
11383 if (error)
11384 goto done;
11386 error = got_object_open_as_commit(&commit, repo,
11387 head_commit_id);
11388 if (error)
11389 goto done;
11390 parent_ids = got_object_commit_get_parent_ids(commit);
11391 pid = STAILQ_FIRST(parent_ids);
11392 if (pid == NULL) {
11393 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11394 goto done;
11396 error = collect_commits(&commits, head_commit_id, &pid->id,
11397 got_worktree_get_base_commit_id(worktree),
11398 got_worktree_get_path_prefix(worktree),
11399 GOT_ERR_HISTEDIT_PATH, repo);
11400 got_object_commit_close(commit);
11401 commit = NULL;
11402 if (error)
11403 goto done;
11405 if (STAILQ_EMPTY(&commits)) {
11406 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11407 goto done;
11410 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11411 &base_commit_id, &fileindex, worktree, repo);
11412 if (error)
11413 goto done;
11415 if (edit_script_path) {
11416 error = histedit_load_list(&histedit_cmds,
11417 edit_script_path, repo);
11418 if (error) {
11419 got_worktree_histedit_abort(worktree, fileindex,
11420 repo, branch, base_commit_id,
11421 abort_progress, &upa);
11422 print_merge_progress_stats(&upa);
11423 goto done;
11425 } else {
11426 const char *branch_name;
11427 branch_name = got_ref_get_symref_target(branch);
11428 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11429 branch_name += 11;
11430 error = histedit_edit_script(&histedit_cmds, &commits,
11431 branch_name, edit_logmsg_only, fold_only,
11432 edit_only, repo);
11433 if (error) {
11434 got_worktree_histedit_abort(worktree, fileindex,
11435 repo, branch, base_commit_id,
11436 abort_progress, &upa);
11437 print_merge_progress_stats(&upa);
11438 goto done;
11443 error = histedit_save_list(&histedit_cmds, worktree,
11444 repo);
11445 if (error) {
11446 got_worktree_histedit_abort(worktree, fileindex,
11447 repo, branch, base_commit_id,
11448 abort_progress, &upa);
11449 print_merge_progress_stats(&upa);
11450 goto done;
11455 error = histedit_check_script(&histedit_cmds, &commits, repo);
11456 if (error)
11457 goto done;
11459 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11460 if (resume_commit_id) {
11461 if (got_object_id_cmp(hle->commit_id,
11462 resume_commit_id) != 0)
11463 continue;
11465 resume_commit_id = NULL;
11466 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11467 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11468 error = histedit_skip_commit(hle, worktree,
11469 repo);
11470 if (error)
11471 goto done;
11472 } else {
11473 struct got_pathlist_head paths;
11474 int have_changes = 0;
11476 TAILQ_INIT(&paths);
11477 error = got_pathlist_append(&paths, "", NULL);
11478 if (error)
11479 goto done;
11480 error = got_worktree_status(worktree, &paths,
11481 repo, 0, check_local_changes, &have_changes,
11482 check_cancelled, NULL);
11483 got_pathlist_free(&paths);
11484 if (error) {
11485 if (error->code != GOT_ERR_CANCELLED)
11486 goto done;
11487 if (sigint_received || sigpipe_received)
11488 goto done;
11490 if (have_changes) {
11491 error = histedit_commit(NULL, worktree,
11492 fileindex, tmp_branch, hle, repo);
11493 if (error)
11494 goto done;
11495 } else {
11496 error = got_object_open_as_commit(
11497 &commit, repo, hle->commit_id);
11498 if (error)
11499 goto done;
11500 error = show_histedit_progress(commit,
11501 hle, NULL);
11502 got_object_commit_close(commit);
11503 commit = NULL;
11504 if (error)
11505 goto done;
11508 continue;
11511 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11512 error = histedit_skip_commit(hle, worktree, repo);
11513 if (error)
11514 goto done;
11515 continue;
11518 error = got_object_open_as_commit(&commit, repo,
11519 hle->commit_id);
11520 if (error)
11521 goto done;
11522 parent_ids = got_object_commit_get_parent_ids(commit);
11523 pid = STAILQ_FIRST(parent_ids);
11525 error = got_worktree_histedit_merge_files(&merged_paths,
11526 worktree, fileindex, &pid->id, hle->commit_id, repo,
11527 update_progress, &upa, check_cancelled, NULL);
11528 if (error)
11529 goto done;
11530 got_object_commit_close(commit);
11531 commit = NULL;
11533 print_merge_progress_stats(&upa);
11534 if (upa.conflicts > 0 || upa.missing > 0 ||
11535 upa.not_deleted > 0 || upa.unversioned > 0) {
11536 if (upa.conflicts > 0) {
11537 error = show_rebase_merge_conflict(
11538 hle->commit_id, repo);
11539 if (error)
11540 goto done;
11542 got_worktree_rebase_pathlist_free(&merged_paths);
11543 break;
11546 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11547 char *id_str;
11548 error = got_object_id_str(&id_str, hle->commit_id);
11549 if (error)
11550 goto done;
11551 printf("Stopping histedit for amending commit %s\n",
11552 id_str);
11553 free(id_str);
11554 got_worktree_rebase_pathlist_free(&merged_paths);
11555 error = got_worktree_histedit_postpone(worktree,
11556 fileindex);
11557 goto done;
11560 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11561 error = histedit_skip_commit(hle, worktree, repo);
11562 if (error)
11563 goto done;
11564 continue;
11567 error = histedit_commit(&merged_paths, worktree, fileindex,
11568 tmp_branch, hle, repo);
11569 got_worktree_rebase_pathlist_free(&merged_paths);
11570 if (error)
11571 goto done;
11574 if (upa.conflicts > 0 || upa.missing > 0 ||
11575 upa.not_deleted > 0 || upa.unversioned > 0) {
11576 error = got_worktree_histedit_postpone(worktree, fileindex);
11577 if (error)
11578 goto done;
11579 if (upa.conflicts > 0 && upa.missing == 0 &&
11580 upa.not_deleted == 0 && upa.unversioned == 0) {
11581 error = got_error_msg(GOT_ERR_CONFLICTS,
11582 "conflicts must be resolved before histedit "
11583 "can continue");
11584 } else if (upa.conflicts > 0) {
11585 error = got_error_msg(GOT_ERR_CONFLICTS,
11586 "conflicts must be resolved before histedit "
11587 "can continue; changes destined for some "
11588 "files were not yet merged and should be "
11589 "merged manually if required before the "
11590 "histedit operation is continued");
11591 } else {
11592 error = got_error_msg(GOT_ERR_CONFLICTS,
11593 "changes destined for some files were not "
11594 "yet merged and should be merged manually "
11595 "if required before the histedit operation "
11596 "is continued");
11598 } else
11599 error = histedit_complete(worktree, fileindex, tmp_branch,
11600 branch, repo);
11601 done:
11602 got_object_id_queue_free(&commits);
11603 histedit_free_list(&histedit_cmds);
11604 free(head_commit_id);
11605 free(base_commit_id);
11606 free(resume_commit_id);
11607 if (commit)
11608 got_object_commit_close(commit);
11609 if (branch)
11610 got_ref_close(branch);
11611 if (tmp_branch)
11612 got_ref_close(tmp_branch);
11613 if (worktree)
11614 got_worktree_close(worktree);
11615 if (repo) {
11616 const struct got_error *close_err = got_repo_close(repo);
11617 if (error == NULL)
11618 error = close_err;
11620 if (pack_fds) {
11621 const struct got_error *pack_err =
11622 got_repo_pack_fds_close(pack_fds);
11623 if (error == NULL)
11624 error = pack_err;
11626 return error;
11629 __dead static void
11630 usage_integrate(void)
11632 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11633 exit(1);
11636 static const struct got_error *
11637 cmd_integrate(int argc, char *argv[])
11639 const struct got_error *error = NULL;
11640 struct got_repository *repo = NULL;
11641 struct got_worktree *worktree = NULL;
11642 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11643 const char *branch_arg = NULL;
11644 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11645 struct got_fileindex *fileindex = NULL;
11646 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11647 int ch;
11648 struct got_update_progress_arg upa;
11649 int *pack_fds = NULL;
11651 while ((ch = getopt(argc, argv, "")) != -1) {
11652 switch (ch) {
11653 default:
11654 usage_integrate();
11655 /* NOTREACHED */
11659 argc -= optind;
11660 argv += optind;
11662 if (argc != 1)
11663 usage_integrate();
11664 branch_arg = argv[0];
11665 #ifndef PROFILE
11666 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11667 "unveil", NULL) == -1)
11668 err(1, "pledge");
11669 #endif
11670 cwd = getcwd(NULL, 0);
11671 if (cwd == NULL) {
11672 error = got_error_from_errno("getcwd");
11673 goto done;
11676 error = got_repo_pack_fds_open(&pack_fds);
11677 if (error != NULL)
11678 goto done;
11680 error = got_worktree_open(&worktree, cwd);
11681 if (error) {
11682 if (error->code == GOT_ERR_NOT_WORKTREE)
11683 error = wrap_not_worktree_error(error, "integrate",
11684 cwd);
11685 goto done;
11688 error = check_rebase_or_histedit_in_progress(worktree);
11689 if (error)
11690 goto done;
11692 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11693 NULL, pack_fds);
11694 if (error != NULL)
11695 goto done;
11697 error = apply_unveil(got_repo_get_path(repo), 0,
11698 got_worktree_get_root_path(worktree));
11699 if (error)
11700 goto done;
11702 error = check_merge_in_progress(worktree, repo);
11703 if (error)
11704 goto done;
11706 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11707 error = got_error_from_errno("asprintf");
11708 goto done;
11711 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11712 &base_branch_ref, worktree, refname, repo);
11713 if (error)
11714 goto done;
11716 refname = strdup(got_ref_get_name(branch_ref));
11717 if (refname == NULL) {
11718 error = got_error_from_errno("strdup");
11719 got_worktree_integrate_abort(worktree, fileindex, repo,
11720 branch_ref, base_branch_ref);
11721 goto done;
11723 base_refname = strdup(got_ref_get_name(base_branch_ref));
11724 if (base_refname == NULL) {
11725 error = got_error_from_errno("strdup");
11726 got_worktree_integrate_abort(worktree, fileindex, repo,
11727 branch_ref, base_branch_ref);
11728 goto done;
11731 error = got_ref_resolve(&commit_id, repo, branch_ref);
11732 if (error)
11733 goto done;
11735 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11736 if (error)
11737 goto done;
11739 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11740 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11741 "specified branch has already been integrated");
11742 got_worktree_integrate_abort(worktree, fileindex, repo,
11743 branch_ref, base_branch_ref);
11744 goto done;
11747 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11748 if (error) {
11749 if (error->code == GOT_ERR_ANCESTRY)
11750 error = got_error(GOT_ERR_REBASE_REQUIRED);
11751 got_worktree_integrate_abort(worktree, fileindex, repo,
11752 branch_ref, base_branch_ref);
11753 goto done;
11756 memset(&upa, 0, sizeof(upa));
11757 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11758 branch_ref, base_branch_ref, update_progress, &upa,
11759 check_cancelled, NULL);
11760 if (error)
11761 goto done;
11763 printf("Integrated %s into %s\n", refname, base_refname);
11764 print_update_progress_stats(&upa);
11765 done:
11766 if (repo) {
11767 const struct got_error *close_err = got_repo_close(repo);
11768 if (error == NULL)
11769 error = close_err;
11771 if (worktree)
11772 got_worktree_close(worktree);
11773 if (pack_fds) {
11774 const struct got_error *pack_err =
11775 got_repo_pack_fds_close(pack_fds);
11776 if (error == NULL)
11777 error = pack_err;
11779 free(cwd);
11780 free(base_commit_id);
11781 free(commit_id);
11782 free(refname);
11783 free(base_refname);
11784 return error;
11787 __dead static void
11788 usage_merge(void)
11790 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11791 getprogname());
11792 exit(1);
11795 static const struct got_error *
11796 cmd_merge(int argc, char *argv[])
11798 const struct got_error *error = NULL;
11799 struct got_worktree *worktree = NULL;
11800 struct got_repository *repo = NULL;
11801 struct got_fileindex *fileindex = NULL;
11802 char *cwd = NULL, *id_str = NULL, *author = NULL;
11803 struct got_reference *branch = NULL, *wt_branch = NULL;
11804 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11805 struct got_object_id *wt_branch_tip = NULL;
11806 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11807 int interrupt_merge = 0;
11808 struct got_update_progress_arg upa;
11809 struct got_object_id *merge_commit_id = NULL;
11810 char *branch_name = NULL;
11811 int *pack_fds = NULL;
11813 memset(&upa, 0, sizeof(upa));
11815 while ((ch = getopt(argc, argv, "acn")) != -1) {
11816 switch (ch) {
11817 case 'a':
11818 abort_merge = 1;
11819 break;
11820 case 'c':
11821 continue_merge = 1;
11822 break;
11823 case 'n':
11824 interrupt_merge = 1;
11825 break;
11826 default:
11827 usage_rebase();
11828 /* NOTREACHED */
11832 argc -= optind;
11833 argv += optind;
11835 #ifndef PROFILE
11836 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11837 "unveil", NULL) == -1)
11838 err(1, "pledge");
11839 #endif
11841 if (abort_merge && continue_merge)
11842 option_conflict('a', 'c');
11843 if (abort_merge || continue_merge) {
11844 if (argc != 0)
11845 usage_merge();
11846 } else if (argc != 1)
11847 usage_merge();
11849 cwd = getcwd(NULL, 0);
11850 if (cwd == NULL) {
11851 error = got_error_from_errno("getcwd");
11852 goto done;
11855 error = got_repo_pack_fds_open(&pack_fds);
11856 if (error != NULL)
11857 goto done;
11859 error = got_worktree_open(&worktree, cwd);
11860 if (error) {
11861 if (error->code == GOT_ERR_NOT_WORKTREE)
11862 error = wrap_not_worktree_error(error,
11863 "merge", cwd);
11864 goto done;
11867 error = got_repo_open(&repo,
11868 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11869 pack_fds);
11870 if (error != NULL)
11871 goto done;
11873 error = apply_unveil(got_repo_get_path(repo), 0,
11874 worktree ? got_worktree_get_root_path(worktree) : NULL);
11875 if (error)
11876 goto done;
11878 error = check_rebase_or_histedit_in_progress(worktree);
11879 if (error)
11880 goto done;
11882 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11883 repo);
11884 if (error)
11885 goto done;
11887 if (abort_merge) {
11888 if (!merge_in_progress) {
11889 error = got_error(GOT_ERR_NOT_MERGING);
11890 goto done;
11892 error = got_worktree_merge_continue(&branch_name,
11893 &branch_tip, &fileindex, worktree, repo);
11894 if (error)
11895 goto done;
11896 error = got_worktree_merge_abort(worktree, fileindex, repo,
11897 abort_progress, &upa);
11898 if (error)
11899 goto done;
11900 printf("Merge of %s aborted\n", branch_name);
11901 goto done; /* nothing else to do */
11904 error = get_author(&author, repo, worktree);
11905 if (error)
11906 goto done;
11908 if (continue_merge) {
11909 if (!merge_in_progress) {
11910 error = got_error(GOT_ERR_NOT_MERGING);
11911 goto done;
11913 error = got_worktree_merge_continue(&branch_name,
11914 &branch_tip, &fileindex, worktree, repo);
11915 if (error)
11916 goto done;
11917 } else {
11918 error = got_ref_open(&branch, repo, argv[0], 0);
11919 if (error != NULL)
11920 goto done;
11921 branch_name = strdup(got_ref_get_name(branch));
11922 if (branch_name == NULL) {
11923 error = got_error_from_errno("strdup");
11924 goto done;
11926 error = got_ref_resolve(&branch_tip, repo, branch);
11927 if (error)
11928 goto done;
11931 error = got_ref_open(&wt_branch, repo,
11932 got_worktree_get_head_ref_name(worktree), 0);
11933 if (error)
11934 goto done;
11935 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11936 if (error)
11937 goto done;
11938 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11939 wt_branch_tip, branch_tip, 0, repo,
11940 check_cancelled, NULL);
11941 if (error && error->code != GOT_ERR_ANCESTRY)
11942 goto done;
11944 if (!continue_merge) {
11945 error = check_path_prefix(wt_branch_tip, branch_tip,
11946 got_worktree_get_path_prefix(worktree),
11947 GOT_ERR_MERGE_PATH, repo);
11948 if (error)
11949 goto done;
11950 if (yca_id) {
11951 error = check_same_branch(wt_branch_tip, branch,
11952 yca_id, repo);
11953 if (error) {
11954 if (error->code != GOT_ERR_ANCESTRY)
11955 goto done;
11956 error = NULL;
11957 } else {
11958 static char msg[512];
11959 snprintf(msg, sizeof(msg),
11960 "cannot create a merge commit because "
11961 "%s is based on %s; %s can be integrated "
11962 "with 'got integrate' instead", branch_name,
11963 got_worktree_get_head_ref_name(worktree),
11964 branch_name);
11965 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11966 goto done;
11969 error = got_worktree_merge_prepare(&fileindex, worktree,
11970 branch, repo);
11971 if (error)
11972 goto done;
11974 error = got_worktree_merge_branch(worktree, fileindex,
11975 yca_id, branch_tip, repo, update_progress, &upa,
11976 check_cancelled, NULL);
11977 if (error)
11978 goto done;
11979 print_merge_progress_stats(&upa);
11980 if (!upa.did_something) {
11981 error = got_worktree_merge_abort(worktree, fileindex,
11982 repo, abort_progress, &upa);
11983 if (error)
11984 goto done;
11985 printf("Already up-to-date\n");
11986 goto done;
11990 if (interrupt_merge) {
11991 error = got_worktree_merge_postpone(worktree, fileindex);
11992 if (error)
11993 goto done;
11994 printf("Merge of %s interrupted on request\n", branch_name);
11995 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11996 upa.not_deleted > 0 || upa.unversioned > 0) {
11997 error = got_worktree_merge_postpone(worktree, fileindex);
11998 if (error)
11999 goto done;
12000 if (upa.conflicts > 0 && upa.missing == 0 &&
12001 upa.not_deleted == 0 && upa.unversioned == 0) {
12002 error = got_error_msg(GOT_ERR_CONFLICTS,
12003 "conflicts must be resolved before merging "
12004 "can continue");
12005 } else if (upa.conflicts > 0) {
12006 error = got_error_msg(GOT_ERR_CONFLICTS,
12007 "conflicts must be resolved before merging "
12008 "can continue; changes destined for some "
12009 "files were not yet merged and "
12010 "should be merged manually if required before the "
12011 "merge operation is continued");
12012 } else {
12013 error = got_error_msg(GOT_ERR_CONFLICTS,
12014 "changes destined for some "
12015 "files were not yet merged and should be "
12016 "merged manually if required before the "
12017 "merge operation is continued");
12019 goto done;
12020 } else {
12021 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12022 fileindex, author, NULL, 1, branch_tip, branch_name,
12023 repo, continue_merge ? print_status : NULL, NULL);
12024 if (error)
12025 goto done;
12026 error = got_worktree_merge_complete(worktree, fileindex, repo);
12027 if (error)
12028 goto done;
12029 error = got_object_id_str(&id_str, merge_commit_id);
12030 if (error)
12031 goto done;
12032 printf("Merged %s into %s: %s\n", branch_name,
12033 got_worktree_get_head_ref_name(worktree),
12034 id_str);
12037 done:
12038 free(id_str);
12039 free(merge_commit_id);
12040 free(author);
12041 free(branch_tip);
12042 free(branch_name);
12043 free(yca_id);
12044 if (branch)
12045 got_ref_close(branch);
12046 if (wt_branch)
12047 got_ref_close(wt_branch);
12048 if (worktree)
12049 got_worktree_close(worktree);
12050 if (repo) {
12051 const struct got_error *close_err = got_repo_close(repo);
12052 if (error == NULL)
12053 error = close_err;
12055 if (pack_fds) {
12056 const struct got_error *pack_err =
12057 got_repo_pack_fds_close(pack_fds);
12058 if (error == NULL)
12059 error = pack_err;
12061 return error;
12064 __dead static void
12065 usage_stage(void)
12067 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12068 "[-S] [file-path ...]\n",
12069 getprogname());
12070 exit(1);
12073 static const struct got_error *
12074 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12075 const char *path, struct got_object_id *blob_id,
12076 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12077 int dirfd, const char *de_name)
12079 const struct got_error *err = NULL;
12080 char *id_str = NULL;
12082 if (staged_status != GOT_STATUS_ADD &&
12083 staged_status != GOT_STATUS_MODIFY &&
12084 staged_status != GOT_STATUS_DELETE)
12085 return NULL;
12087 if (staged_status == GOT_STATUS_ADD ||
12088 staged_status == GOT_STATUS_MODIFY)
12089 err = got_object_id_str(&id_str, staged_blob_id);
12090 else
12091 err = got_object_id_str(&id_str, blob_id);
12092 if (err)
12093 return err;
12095 printf("%s %c %s\n", id_str, staged_status, path);
12096 free(id_str);
12097 return NULL;
12100 static const struct got_error *
12101 cmd_stage(int argc, char *argv[])
12103 const struct got_error *error = NULL;
12104 struct got_repository *repo = NULL;
12105 struct got_worktree *worktree = NULL;
12106 char *cwd = NULL;
12107 struct got_pathlist_head paths;
12108 struct got_pathlist_entry *pe;
12109 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12110 FILE *patch_script_file = NULL;
12111 const char *patch_script_path = NULL;
12112 struct choose_patch_arg cpa;
12113 int *pack_fds = NULL;
12115 TAILQ_INIT(&paths);
12117 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12118 switch (ch) {
12119 case 'l':
12120 list_stage = 1;
12121 break;
12122 case 'p':
12123 pflag = 1;
12124 break;
12125 case 'F':
12126 patch_script_path = optarg;
12127 break;
12128 case 'S':
12129 allow_bad_symlinks = 1;
12130 break;
12131 default:
12132 usage_stage();
12133 /* NOTREACHED */
12137 argc -= optind;
12138 argv += optind;
12140 #ifndef PROFILE
12141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12142 "unveil", NULL) == -1)
12143 err(1, "pledge");
12144 #endif
12145 if (list_stage && (pflag || patch_script_path))
12146 errx(1, "-l option cannot be used with other options");
12147 if (patch_script_path && !pflag)
12148 errx(1, "-F option can only be used together with -p option");
12150 cwd = getcwd(NULL, 0);
12151 if (cwd == NULL) {
12152 error = got_error_from_errno("getcwd");
12153 goto done;
12156 error = got_repo_pack_fds_open(&pack_fds);
12157 if (error != NULL)
12158 goto done;
12160 error = got_worktree_open(&worktree, cwd);
12161 if (error) {
12162 if (error->code == GOT_ERR_NOT_WORKTREE)
12163 error = wrap_not_worktree_error(error, "stage", cwd);
12164 goto done;
12167 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12168 NULL, pack_fds);
12169 if (error != NULL)
12170 goto done;
12172 if (patch_script_path) {
12173 patch_script_file = fopen(patch_script_path, "re");
12174 if (patch_script_file == NULL) {
12175 error = got_error_from_errno2("fopen",
12176 patch_script_path);
12177 goto done;
12180 error = apply_unveil(got_repo_get_path(repo), 0,
12181 got_worktree_get_root_path(worktree));
12182 if (error)
12183 goto done;
12185 error = check_merge_in_progress(worktree, repo);
12186 if (error)
12187 goto done;
12189 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12190 if (error)
12191 goto done;
12193 if (list_stage)
12194 error = got_worktree_status(worktree, &paths, repo, 0,
12195 print_stage, NULL, check_cancelled, NULL);
12196 else {
12197 cpa.patch_script_file = patch_script_file;
12198 cpa.action = "stage";
12199 error = got_worktree_stage(worktree, &paths,
12200 pflag ? NULL : print_status, NULL,
12201 pflag ? choose_patch : NULL, &cpa,
12202 allow_bad_symlinks, repo);
12204 done:
12205 if (patch_script_file && fclose(patch_script_file) == EOF &&
12206 error == NULL)
12207 error = got_error_from_errno2("fclose", patch_script_path);
12208 if (repo) {
12209 const struct got_error *close_err = got_repo_close(repo);
12210 if (error == NULL)
12211 error = close_err;
12213 if (worktree)
12214 got_worktree_close(worktree);
12215 if (pack_fds) {
12216 const struct got_error *pack_err =
12217 got_repo_pack_fds_close(pack_fds);
12218 if (error == NULL)
12219 error = pack_err;
12221 TAILQ_FOREACH(pe, &paths, entry)
12222 free((char *)pe->path);
12223 got_pathlist_free(&paths);
12224 free(cwd);
12225 return error;
12228 __dead static void
12229 usage_unstage(void)
12231 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12232 "[file-path ...]\n",
12233 getprogname());
12234 exit(1);
12238 static const struct got_error *
12239 cmd_unstage(int argc, char *argv[])
12241 const struct got_error *error = NULL;
12242 struct got_repository *repo = NULL;
12243 struct got_worktree *worktree = NULL;
12244 char *cwd = NULL;
12245 struct got_pathlist_head paths;
12246 struct got_pathlist_entry *pe;
12247 int ch, pflag = 0;
12248 struct got_update_progress_arg upa;
12249 FILE *patch_script_file = NULL;
12250 const char *patch_script_path = NULL;
12251 struct choose_patch_arg cpa;
12252 int *pack_fds = NULL;
12254 TAILQ_INIT(&paths);
12256 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12257 switch (ch) {
12258 case 'p':
12259 pflag = 1;
12260 break;
12261 case 'F':
12262 patch_script_path = optarg;
12263 break;
12264 default:
12265 usage_unstage();
12266 /* NOTREACHED */
12270 argc -= optind;
12271 argv += optind;
12273 #ifndef PROFILE
12274 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12275 "unveil", NULL) == -1)
12276 err(1, "pledge");
12277 #endif
12278 if (patch_script_path && !pflag)
12279 errx(1, "-F option can only be used together with -p option");
12281 cwd = getcwd(NULL, 0);
12282 if (cwd == NULL) {
12283 error = got_error_from_errno("getcwd");
12284 goto done;
12287 error = got_repo_pack_fds_open(&pack_fds);
12288 if (error != NULL)
12289 goto done;
12291 error = got_worktree_open(&worktree, cwd);
12292 if (error) {
12293 if (error->code == GOT_ERR_NOT_WORKTREE)
12294 error = wrap_not_worktree_error(error, "unstage", cwd);
12295 goto done;
12298 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12299 NULL, pack_fds);
12300 if (error != NULL)
12301 goto done;
12303 if (patch_script_path) {
12304 patch_script_file = fopen(patch_script_path, "re");
12305 if (patch_script_file == NULL) {
12306 error = got_error_from_errno2("fopen",
12307 patch_script_path);
12308 goto done;
12312 error = apply_unveil(got_repo_get_path(repo), 0,
12313 got_worktree_get_root_path(worktree));
12314 if (error)
12315 goto done;
12317 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12318 if (error)
12319 goto done;
12321 cpa.patch_script_file = patch_script_file;
12322 cpa.action = "unstage";
12323 memset(&upa, 0, sizeof(upa));
12324 error = got_worktree_unstage(worktree, &paths, update_progress,
12325 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12326 if (!error)
12327 print_merge_progress_stats(&upa);
12328 done:
12329 if (patch_script_file && fclose(patch_script_file) == EOF &&
12330 error == NULL)
12331 error = got_error_from_errno2("fclose", patch_script_path);
12332 if (repo) {
12333 const struct got_error *close_err = got_repo_close(repo);
12334 if (error == NULL)
12335 error = close_err;
12337 if (worktree)
12338 got_worktree_close(worktree);
12339 if (pack_fds) {
12340 const struct got_error *pack_err =
12341 got_repo_pack_fds_close(pack_fds);
12342 if (error == NULL)
12343 error = pack_err;
12345 TAILQ_FOREACH(pe, &paths, entry)
12346 free((char *)pe->path);
12347 got_pathlist_free(&paths);
12348 free(cwd);
12349 return error;
12352 __dead static void
12353 usage_cat(void)
12355 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12356 "arg1 [arg2 ...]\n", getprogname());
12357 exit(1);
12360 static const struct got_error *
12361 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12363 const struct got_error *err;
12364 struct got_blob_object *blob;
12365 int fd = -1;
12367 fd = got_opentempfd();
12368 if (fd == -1)
12369 return got_error_from_errno("got_opentempfd");
12371 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12372 if (err)
12373 goto done;
12375 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12376 done:
12377 if (fd != -1 && close(fd) == -1 && err == NULL)
12378 err = got_error_from_errno("close");
12379 if (blob)
12380 got_object_blob_close(blob);
12381 return err;
12384 static const struct got_error *
12385 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12387 const struct got_error *err;
12388 struct got_tree_object *tree;
12389 int nentries, i;
12391 err = got_object_open_as_tree(&tree, repo, id);
12392 if (err)
12393 return err;
12395 nentries = got_object_tree_get_nentries(tree);
12396 for (i = 0; i < nentries; i++) {
12397 struct got_tree_entry *te;
12398 char *id_str;
12399 if (sigint_received || sigpipe_received)
12400 break;
12401 te = got_object_tree_get_entry(tree, i);
12402 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12403 if (err)
12404 break;
12405 fprintf(outfile, "%s %.7o %s\n", id_str,
12406 got_tree_entry_get_mode(te),
12407 got_tree_entry_get_name(te));
12408 free(id_str);
12411 got_object_tree_close(tree);
12412 return err;
12415 static void
12416 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12418 long long h, m;
12419 char sign = '+';
12421 if (gmtoff < 0) {
12422 sign = '-';
12423 gmtoff = -gmtoff;
12426 h = (long long)gmtoff / 3600;
12427 m = ((long long)gmtoff - h*3600) / 60;
12428 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12431 static const struct got_error *
12432 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12434 const struct got_error *err;
12435 struct got_commit_object *commit;
12436 const struct got_object_id_queue *parent_ids;
12437 struct got_object_qid *pid;
12438 char *id_str = NULL;
12439 const char *logmsg = NULL;
12440 char gmtoff[6];
12442 err = got_object_open_as_commit(&commit, repo, id);
12443 if (err)
12444 return err;
12446 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12447 if (err)
12448 goto done;
12450 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12451 parent_ids = got_object_commit_get_parent_ids(commit);
12452 fprintf(outfile, "numparents %d\n",
12453 got_object_commit_get_nparents(commit));
12454 STAILQ_FOREACH(pid, parent_ids, entry) {
12455 char *pid_str;
12456 err = got_object_id_str(&pid_str, &pid->id);
12457 if (err)
12458 goto done;
12459 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12460 free(pid_str);
12462 format_gmtoff(gmtoff, sizeof(gmtoff),
12463 got_object_commit_get_author_gmtoff(commit));
12464 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12465 got_object_commit_get_author(commit),
12466 (long long)got_object_commit_get_author_time(commit),
12467 gmtoff);
12469 format_gmtoff(gmtoff, sizeof(gmtoff),
12470 got_object_commit_get_committer_gmtoff(commit));
12471 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12472 got_object_commit_get_author(commit),
12473 (long long)got_object_commit_get_committer_time(commit),
12474 gmtoff);
12476 logmsg = got_object_commit_get_logmsg_raw(commit);
12477 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12478 fprintf(outfile, "%s", logmsg);
12479 done:
12480 free(id_str);
12481 got_object_commit_close(commit);
12482 return err;
12485 static const struct got_error *
12486 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12488 const struct got_error *err;
12489 struct got_tag_object *tag;
12490 char *id_str = NULL;
12491 const char *tagmsg = NULL;
12492 char gmtoff[6];
12494 err = got_object_open_as_tag(&tag, repo, id);
12495 if (err)
12496 return err;
12498 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12499 if (err)
12500 goto done;
12502 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12504 switch (got_object_tag_get_object_type(tag)) {
12505 case GOT_OBJ_TYPE_BLOB:
12506 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12507 GOT_OBJ_LABEL_BLOB);
12508 break;
12509 case GOT_OBJ_TYPE_TREE:
12510 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12511 GOT_OBJ_LABEL_TREE);
12512 break;
12513 case GOT_OBJ_TYPE_COMMIT:
12514 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12515 GOT_OBJ_LABEL_COMMIT);
12516 break;
12517 case GOT_OBJ_TYPE_TAG:
12518 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12519 GOT_OBJ_LABEL_TAG);
12520 break;
12521 default:
12522 break;
12525 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12526 got_object_tag_get_name(tag));
12528 format_gmtoff(gmtoff, sizeof(gmtoff),
12529 got_object_tag_get_tagger_gmtoff(tag));
12530 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12531 got_object_tag_get_tagger(tag),
12532 (long long)got_object_tag_get_tagger_time(tag),
12533 gmtoff);
12535 tagmsg = got_object_tag_get_message(tag);
12536 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12537 fprintf(outfile, "%s", tagmsg);
12538 done:
12539 free(id_str);
12540 got_object_tag_close(tag);
12541 return err;
12544 static const struct got_error *
12545 cmd_cat(int argc, char *argv[])
12547 const struct got_error *error;
12548 struct got_repository *repo = NULL;
12549 struct got_worktree *worktree = NULL;
12550 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12551 const char *commit_id_str = NULL;
12552 struct got_object_id *id = NULL, *commit_id = NULL;
12553 struct got_commit_object *commit = NULL;
12554 int ch, obj_type, i, force_path = 0;
12555 struct got_reflist_head refs;
12556 int *pack_fds = NULL;
12558 TAILQ_INIT(&refs);
12560 #ifndef PROFILE
12561 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12562 NULL) == -1)
12563 err(1, "pledge");
12564 #endif
12566 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12567 switch (ch) {
12568 case 'c':
12569 commit_id_str = optarg;
12570 break;
12571 case 'r':
12572 repo_path = realpath(optarg, NULL);
12573 if (repo_path == NULL)
12574 return got_error_from_errno2("realpath",
12575 optarg);
12576 got_path_strip_trailing_slashes(repo_path);
12577 break;
12578 case 'P':
12579 force_path = 1;
12580 break;
12581 default:
12582 usage_cat();
12583 /* NOTREACHED */
12587 argc -= optind;
12588 argv += optind;
12590 cwd = getcwd(NULL, 0);
12591 if (cwd == NULL) {
12592 error = got_error_from_errno("getcwd");
12593 goto done;
12596 error = got_repo_pack_fds_open(&pack_fds);
12597 if (error != NULL)
12598 goto done;
12600 if (repo_path == NULL) {
12601 error = got_worktree_open(&worktree, cwd);
12602 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12603 goto done;
12604 if (worktree) {
12605 repo_path = strdup(
12606 got_worktree_get_repo_path(worktree));
12607 if (repo_path == NULL) {
12608 error = got_error_from_errno("strdup");
12609 goto done;
12612 /* Release work tree lock. */
12613 got_worktree_close(worktree);
12614 worktree = NULL;
12618 if (repo_path == NULL) {
12619 repo_path = strdup(cwd);
12620 if (repo_path == NULL)
12621 return got_error_from_errno("strdup");
12624 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12625 free(repo_path);
12626 if (error != NULL)
12627 goto done;
12629 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12630 if (error)
12631 goto done;
12633 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12634 if (error)
12635 goto done;
12637 if (commit_id_str == NULL)
12638 commit_id_str = GOT_REF_HEAD;
12639 error = got_repo_match_object_id(&commit_id, NULL,
12640 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12641 if (error)
12642 goto done;
12644 error = got_object_open_as_commit(&commit, repo, commit_id);
12645 if (error)
12646 goto done;
12648 for (i = 0; i < argc; i++) {
12649 if (force_path) {
12650 error = got_object_id_by_path(&id, repo, commit,
12651 argv[i]);
12652 if (error)
12653 break;
12654 } else {
12655 error = got_repo_match_object_id(&id, &label, argv[i],
12656 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12657 repo);
12658 if (error) {
12659 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12660 error->code != GOT_ERR_NOT_REF)
12661 break;
12662 error = got_object_id_by_path(&id, repo,
12663 commit, argv[i]);
12664 if (error)
12665 break;
12669 error = got_object_get_type(&obj_type, repo, id);
12670 if (error)
12671 break;
12673 switch (obj_type) {
12674 case GOT_OBJ_TYPE_BLOB:
12675 error = cat_blob(id, repo, stdout);
12676 break;
12677 case GOT_OBJ_TYPE_TREE:
12678 error = cat_tree(id, repo, stdout);
12679 break;
12680 case GOT_OBJ_TYPE_COMMIT:
12681 error = cat_commit(id, repo, stdout);
12682 break;
12683 case GOT_OBJ_TYPE_TAG:
12684 error = cat_tag(id, repo, stdout);
12685 break;
12686 default:
12687 error = got_error(GOT_ERR_OBJ_TYPE);
12688 break;
12690 if (error)
12691 break;
12692 free(label);
12693 label = NULL;
12694 free(id);
12695 id = NULL;
12697 done:
12698 free(label);
12699 free(id);
12700 free(commit_id);
12701 if (commit)
12702 got_object_commit_close(commit);
12703 if (worktree)
12704 got_worktree_close(worktree);
12705 if (repo) {
12706 const struct got_error *close_err = got_repo_close(repo);
12707 if (error == NULL)
12708 error = close_err;
12710 if (pack_fds) {
12711 const struct got_error *pack_err =
12712 got_repo_pack_fds_close(pack_fds);
12713 if (error == NULL)
12714 error = pack_err;
12717 got_ref_list_free(&refs);
12718 return error;
12721 __dead static void
12722 usage_info(void)
12724 fprintf(stderr, "usage: %s info [path ...]\n",
12725 getprogname());
12726 exit(1);
12729 static const struct got_error *
12730 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12731 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12732 struct got_object_id *commit_id)
12734 const struct got_error *err = NULL;
12735 char *id_str = NULL;
12736 char datebuf[128];
12737 struct tm mytm, *tm;
12738 struct got_pathlist_head *paths = arg;
12739 struct got_pathlist_entry *pe;
12742 * Clear error indication from any of the path arguments which
12743 * would cause this file index entry to be displayed.
12745 TAILQ_FOREACH(pe, paths, entry) {
12746 if (got_path_cmp(path, pe->path, strlen(path),
12747 pe->path_len) == 0 ||
12748 got_path_is_child(path, pe->path, pe->path_len))
12749 pe->data = NULL; /* no error */
12752 printf(GOT_COMMIT_SEP_STR);
12753 if (S_ISLNK(mode))
12754 printf("symlink: %s\n", path);
12755 else if (S_ISREG(mode)) {
12756 printf("file: %s\n", path);
12757 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12758 } else if (S_ISDIR(mode))
12759 printf("directory: %s\n", path);
12760 else
12761 printf("something: %s\n", path);
12763 tm = localtime_r(&mtime, &mytm);
12764 if (tm == NULL)
12765 return NULL;
12766 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12767 return got_error(GOT_ERR_NO_SPACE);
12768 printf("timestamp: %s\n", datebuf);
12770 if (blob_id) {
12771 err = got_object_id_str(&id_str, blob_id);
12772 if (err)
12773 return err;
12774 printf("based on blob: %s\n", id_str);
12775 free(id_str);
12778 if (staged_blob_id) {
12779 err = got_object_id_str(&id_str, staged_blob_id);
12780 if (err)
12781 return err;
12782 printf("based on staged blob: %s\n", id_str);
12783 free(id_str);
12786 if (commit_id) {
12787 err = got_object_id_str(&id_str, commit_id);
12788 if (err)
12789 return err;
12790 printf("based on commit: %s\n", id_str);
12791 free(id_str);
12794 return NULL;
12797 static const struct got_error *
12798 cmd_info(int argc, char *argv[])
12800 const struct got_error *error = NULL;
12801 struct got_worktree *worktree = NULL;
12802 char *cwd = NULL, *id_str = NULL;
12803 struct got_pathlist_head paths;
12804 struct got_pathlist_entry *pe;
12805 char *uuidstr = NULL;
12806 int ch, show_files = 0;
12807 int *pack_fds = NULL;
12809 TAILQ_INIT(&paths);
12811 while ((ch = getopt(argc, argv, "")) != -1) {
12812 switch (ch) {
12813 default:
12814 usage_info();
12815 /* NOTREACHED */
12819 argc -= optind;
12820 argv += optind;
12822 #ifndef PROFILE
12823 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12824 NULL) == -1)
12825 err(1, "pledge");
12826 #endif
12827 cwd = getcwd(NULL, 0);
12828 if (cwd == NULL) {
12829 error = got_error_from_errno("getcwd");
12830 goto done;
12833 error = got_repo_pack_fds_open(&pack_fds);
12834 if (error != NULL)
12835 goto done;
12837 error = got_worktree_open(&worktree, cwd);
12838 if (error) {
12839 if (error->code == GOT_ERR_NOT_WORKTREE)
12840 error = wrap_not_worktree_error(error, "info", cwd);
12841 goto done;
12844 #ifndef PROFILE
12845 /* Remove "cpath" promise. */
12846 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12847 NULL) == -1)
12848 err(1, "pledge");
12849 #endif
12850 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12851 if (error)
12852 goto done;
12854 if (argc >= 1) {
12855 error = get_worktree_paths_from_argv(&paths, argc, argv,
12856 worktree);
12857 if (error)
12858 goto done;
12859 show_files = 1;
12862 error = got_object_id_str(&id_str,
12863 got_worktree_get_base_commit_id(worktree));
12864 if (error)
12865 goto done;
12867 error = got_worktree_get_uuid(&uuidstr, worktree);
12868 if (error)
12869 goto done;
12871 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12872 printf("work tree base commit: %s\n", id_str);
12873 printf("work tree path prefix: %s\n",
12874 got_worktree_get_path_prefix(worktree));
12875 printf("work tree branch reference: %s\n",
12876 got_worktree_get_head_ref_name(worktree));
12877 printf("work tree UUID: %s\n", uuidstr);
12878 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12880 if (show_files) {
12881 struct got_pathlist_entry *pe;
12882 TAILQ_FOREACH(pe, &paths, entry) {
12883 if (pe->path_len == 0)
12884 continue;
12886 * Assume this path will fail. This will be corrected
12887 * in print_path_info() in case the path does suceeed.
12889 pe->data = (void *)got_error_path(pe->path,
12890 GOT_ERR_BAD_PATH);
12892 error = got_worktree_path_info(worktree, &paths,
12893 print_path_info, &paths, check_cancelled, NULL);
12894 if (error)
12895 goto done;
12896 TAILQ_FOREACH(pe, &paths, entry) {
12897 if (pe->data != NULL) {
12898 error = pe->data; /* bad path */
12899 break;
12903 done:
12904 if (pack_fds) {
12905 const struct got_error *pack_err =
12906 got_repo_pack_fds_close(pack_fds);
12907 if (error == NULL)
12908 error = pack_err;
12910 TAILQ_FOREACH(pe, &paths, entry)
12911 free((char *)pe->path);
12912 got_pathlist_free(&paths);
12913 free(cwd);
12914 free(id_str);
12915 free(uuidstr);
12916 return error;