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/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
60 #ifndef nitems
61 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
62 #endif
64 static volatile sig_atomic_t sigint_received;
65 static volatile sig_atomic_t sigpipe_received;
67 static void
68 catch_sigint(int signo)
69 {
70 sigint_received = 1;
71 }
73 static void
74 catch_sigpipe(int signo)
75 {
76 sigpipe_received = 1;
77 }
80 struct got_cmd {
81 const char *cmd_name;
82 const struct got_error *(*cmd_main)(int, char *[]);
83 void (*cmd_usage)(void);
84 const char *cmd_alias;
85 };
87 __dead static void usage(int, int);
88 __dead static void usage_init(void);
89 __dead static void usage_import(void);
90 __dead static void usage_clone(void);
91 __dead static void usage_fetch(void);
92 __dead static void usage_checkout(void);
93 __dead static void usage_update(void);
94 __dead static void usage_log(void);
95 __dead static void usage_diff(void);
96 __dead static void usage_blame(void);
97 __dead static void usage_tree(void);
98 __dead static void usage_status(void);
99 __dead static void usage_ref(void);
100 __dead static void usage_branch(void);
101 __dead static void usage_tag(void);
102 __dead static void usage_add(void);
103 __dead static void usage_remove(void);
104 __dead static void usage_revert(void);
105 __dead static void usage_commit(void);
106 __dead static void usage_send(void);
107 __dead static void usage_cherrypick(void);
108 __dead static void usage_backout(void);
109 __dead static void usage_rebase(void);
110 __dead static void usage_histedit(void);
111 __dead static void usage_integrate(void);
112 __dead static void usage_merge(void);
113 __dead static void usage_stage(void);
114 __dead static void usage_unstage(void);
115 __dead static void usage_cat(void);
116 __dead static void usage_info(void);
118 static const struct got_error* cmd_init(int, char *[]);
119 static const struct got_error* cmd_import(int, char *[]);
120 static const struct got_error* cmd_clone(int, char *[]);
121 static const struct got_error* cmd_fetch(int, char *[]);
122 static const struct got_error* cmd_checkout(int, char *[]);
123 static const struct got_error* cmd_update(int, char *[]);
124 static const struct got_error* cmd_log(int, char *[]);
125 static const struct got_error* cmd_diff(int, char *[]);
126 static const struct got_error* cmd_blame(int, char *[]);
127 static const struct got_error* cmd_tree(int, char *[]);
128 static const struct got_error* cmd_status(int, char *[]);
129 static const struct got_error* cmd_ref(int, char *[]);
130 static const struct got_error* cmd_branch(int, char *[]);
131 static const struct got_error* cmd_tag(int, char *[]);
132 static const struct got_error* cmd_add(int, char *[]);
133 static const struct got_error* cmd_remove(int, char *[]);
134 static const struct got_error* cmd_revert(int, char *[]);
135 static const struct got_error* cmd_commit(int, char *[]);
136 static const struct got_error* cmd_send(int, char *[]);
137 static const struct got_error* cmd_cherrypick(int, char *[]);
138 static const struct got_error* cmd_backout(int, char *[]);
139 static const struct got_error* cmd_rebase(int, char *[]);
140 static const struct got_error* cmd_histedit(int, char *[]);
141 static const struct got_error* cmd_integrate(int, char *[]);
142 static const struct got_error* cmd_merge(int, char *[]);
143 static const struct got_error* cmd_stage(int, char *[]);
144 static const struct got_error* cmd_unstage(int, char *[]);
145 static const struct got_error* cmd_cat(int, char *[]);
146 static const struct got_error* cmd_info(int, char *[]);
148 static struct got_cmd got_commands[] = {
149 { "init", cmd_init, usage_init, "" },
150 { "import", cmd_import, usage_import, "im" },
151 { "clone", cmd_clone, usage_clone, "cl" },
152 { "fetch", cmd_fetch, usage_fetch, "fe" },
153 { "checkout", cmd_checkout, usage_checkout, "co" },
154 { "update", cmd_update, usage_update, "up" },
155 { "log", cmd_log, usage_log, "" },
156 { "diff", cmd_diff, usage_diff, "di" },
157 { "blame", cmd_blame, usage_blame, "bl" },
158 { "tree", cmd_tree, usage_tree, "tr" },
159 { "status", cmd_status, usage_status, "st" },
160 { "ref", cmd_ref, usage_ref, "" },
161 { "branch", cmd_branch, usage_branch, "br" },
162 { "tag", cmd_tag, usage_tag, "" },
163 { "add", cmd_add, usage_add, "" },
164 { "remove", cmd_remove, usage_remove, "rm" },
165 { "revert", cmd_revert, usage_revert, "rv" },
166 { "commit", cmd_commit, usage_commit, "ci" },
167 { "send", cmd_send, usage_send, "se" },
168 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
169 { "backout", cmd_backout, usage_backout, "bo" },
170 { "rebase", cmd_rebase, usage_rebase, "rb" },
171 { "histedit", cmd_histedit, usage_histedit, "he" },
172 { "integrate", cmd_integrate, usage_integrate,"ig" },
173 { "merge", cmd_merge, usage_merge, "mg" },
174 { "stage", cmd_stage, usage_stage, "sg" },
175 { "unstage", cmd_unstage, usage_unstage, "ug" },
176 { "cat", cmd_cat, usage_cat, "" },
177 { "info", cmd_info, usage_info, "" },
178 };
180 static void
181 list_commands(FILE *fp)
183 size_t i;
185 fprintf(fp, "commands:");
186 for (i = 0; i < nitems(got_commands); i++) {
187 struct got_cmd *cmd = &got_commands[i];
188 fprintf(fp, " %s", cmd->cmd_name);
190 fputc('\n', fp);
193 __dead static void
194 option_conflict(char a, char b)
196 errx(1, "-%c and -%c options are mutually exclusive", a, b);
199 int
200 main(int argc, char *argv[])
202 struct got_cmd *cmd;
203 size_t i;
204 int ch;
205 int hflag = 0, Vflag = 0;
206 static struct option longopts[] = {
207 { "version", no_argument, NULL, 'V' },
208 { NULL, 0, NULL, 0 }
209 };
211 setlocale(LC_CTYPE, "");
213 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
214 switch (ch) {
215 case 'h':
216 hflag = 1;
217 break;
218 case 'V':
219 Vflag = 1;
220 break;
221 default:
222 usage(hflag, 1);
223 /* NOTREACHED */
227 argc -= optind;
228 argv += optind;
229 optind = 1;
230 optreset = 1;
232 if (Vflag) {
233 got_version_print_str();
234 return 0;
237 if (argc <= 0)
238 usage(hflag, hflag ? 0 : 1);
240 signal(SIGINT, catch_sigint);
241 signal(SIGPIPE, catch_sigpipe);
243 for (i = 0; i < nitems(got_commands); i++) {
244 const struct got_error *error;
246 cmd = &got_commands[i];
248 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
249 strcmp(cmd->cmd_alias, argv[0]) != 0)
250 continue;
252 if (hflag)
253 got_commands[i].cmd_usage();
255 error = got_commands[i].cmd_main(argc, argv);
256 if (error && error->code != GOT_ERR_CANCELLED &&
257 error->code != GOT_ERR_PRIVSEP_EXIT &&
258 !(sigpipe_received &&
259 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
260 !(sigint_received &&
261 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
262 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
263 return 1;
266 return 0;
269 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
270 list_commands(stderr);
271 return 1;
274 __dead static void
275 usage(int hflag, int status)
277 FILE *fp = (status == 0) ? stdout : stderr;
279 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
280 getprogname());
281 if (hflag)
282 list_commands(fp);
283 exit(status);
286 static const struct got_error *
287 get_editor(char **abspath)
289 const struct got_error *err = NULL;
290 const char *editor;
292 *abspath = NULL;
294 editor = getenv("VISUAL");
295 if (editor == NULL)
296 editor = getenv("EDITOR");
298 if (editor) {
299 err = got_path_find_prog(abspath, editor);
300 if (err)
301 return err;
304 if (*abspath == NULL) {
305 *abspath = strdup("/bin/ed");
306 if (*abspath == NULL)
307 return got_error_from_errno("strdup");
310 return NULL;
313 static const struct got_error *
314 apply_unveil(const char *repo_path, int repo_read_only,
315 const char *worktree_path)
317 const struct got_error *err;
319 #ifdef PROFILE
320 if (unveil("gmon.out", "rwc") != 0)
321 return got_error_from_errno2("unveil", "gmon.out");
322 #endif
323 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
324 return got_error_from_errno2("unveil", repo_path);
326 if (worktree_path && unveil(worktree_path, "rwc") != 0)
327 return got_error_from_errno2("unveil", worktree_path);
329 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
330 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
332 err = got_privsep_unveil_exec_helpers();
333 if (err != NULL)
334 return err;
336 if (unveil(NULL, NULL) != 0)
337 return got_error_from_errno("unveil");
339 return NULL;
342 __dead static void
343 usage_init(void)
345 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
346 exit(1);
349 static const struct got_error *
350 cmd_init(int argc, char *argv[])
352 const struct got_error *error = NULL;
353 char *repo_path = NULL;
354 int ch;
356 while ((ch = getopt(argc, argv, "")) != -1) {
357 switch (ch) {
358 default:
359 usage_init();
360 /* NOTREACHED */
364 argc -= optind;
365 argv += optind;
367 #ifndef PROFILE
368 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
369 err(1, "pledge");
370 #endif
371 if (argc != 1)
372 usage_init();
374 repo_path = strdup(argv[0]);
375 if (repo_path == NULL)
376 return got_error_from_errno("strdup");
378 got_path_strip_trailing_slashes(repo_path);
380 error = got_path_mkdir(repo_path);
381 if (error &&
382 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
383 goto done;
385 error = apply_unveil(repo_path, 0, NULL);
386 if (error)
387 goto done;
389 error = got_repo_init(repo_path);
390 done:
391 free(repo_path);
392 return error;
395 __dead static void
396 usage_import(void)
398 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
399 "[-r repository-path] [-I pattern] path\n", getprogname());
400 exit(1);
403 int
404 spawn_editor(const char *editor, const char *file)
406 pid_t pid;
407 sig_t sighup, sigint, sigquit;
408 int st = -1;
410 sighup = signal(SIGHUP, SIG_IGN);
411 sigint = signal(SIGINT, SIG_IGN);
412 sigquit = signal(SIGQUIT, SIG_IGN);
414 switch (pid = fork()) {
415 case -1:
416 goto doneediting;
417 case 0:
418 execl(editor, editor, file, (char *)NULL);
419 _exit(127);
422 while (waitpid(pid, &st, 0) == -1)
423 if (errno != EINTR)
424 break;
426 doneediting:
427 (void)signal(SIGHUP, sighup);
428 (void)signal(SIGINT, sigint);
429 (void)signal(SIGQUIT, sigquit);
431 if (!WIFEXITED(st)) {
432 errno = EINTR;
433 return -1;
436 return WEXITSTATUS(st);
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 char *line = NULL;
446 size_t linesize = 0;
447 ssize_t linelen;
448 struct stat st, st2;
449 FILE *fp = NULL;
450 size_t len, logmsg_len;
451 char *initial_content_stripped = NULL, *buf = NULL, *s;
453 *logmsg = NULL;
455 if (stat(logmsg_path, &st) == -1)
456 return got_error_from_errno2("stat", logmsg_path);
458 if (spawn_editor(editor, logmsg_path) == -1)
459 return got_error_from_errno("failed spawning editor");
461 if (stat(logmsg_path, &st2) == -1)
462 return got_error_from_errno("stat");
464 if (require_modification &&
465 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
466 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
467 "no changes made to commit message, aborting");
469 /*
470 * Set up a stripped version of the initial content without comments
471 * and blank lines. We need this in order to check if the message
472 * has in fact been edited.
473 */
474 initial_content_stripped = malloc(initial_content_len + 1);
475 if (initial_content_stripped == NULL)
476 return got_error_from_errno("malloc");
477 initial_content_stripped[0] = '\0';
479 buf = strdup(initial_content);
480 if (buf == NULL) {
481 err = got_error_from_errno("strdup");
482 goto done;
484 s = buf;
485 len = 0;
486 while ((line = strsep(&s, "\n")) != NULL) {
487 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
488 continue; /* remove comments and leading empty lines */
489 len = strlcat(initial_content_stripped, line,
490 initial_content_len + 1);
491 if (len >= initial_content_len + 1) {
492 err = got_error(GOT_ERR_NO_SPACE);
493 goto done;
496 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
497 initial_content_stripped[len - 1] = '\0';
498 len--;
501 logmsg_len = st2.st_size;
502 *logmsg = malloc(logmsg_len + 1);
503 if (*logmsg == NULL)
504 return got_error_from_errno("malloc");
505 (*logmsg)[0] = '\0';
507 fp = fopen(logmsg_path, "r");
508 if (fp == NULL) {
509 err = got_error_from_errno("fopen");
510 goto done;
513 len = 0;
514 while ((linelen = getline(&line, &linesize, fp)) != -1) {
515 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
516 continue; /* remove comments and leading empty lines */
517 len = strlcat(*logmsg, line, logmsg_len + 1);
518 if (len >= logmsg_len + 1) {
519 err = got_error(GOT_ERR_NO_SPACE);
520 goto done;
523 free(line);
524 if (ferror(fp)) {
525 err = got_ferror(fp, GOT_ERR_IO);
526 goto done;
528 while (len > 0 && (*logmsg)[len - 1] == '\n') {
529 (*logmsg)[len - 1] = '\0';
530 len--;
533 if (len == 0) {
534 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
535 "commit message cannot be empty, aborting");
536 goto done;
538 if (require_modification &&
539 strcmp(*logmsg, initial_content_stripped) == 0)
540 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
541 "no changes made to commit message, aborting");
542 done:
543 free(initial_content_stripped);
544 free(buf);
545 if (fp && fclose(fp) == EOF && err == NULL)
546 err = got_error_from_errno("fclose");
547 if (err) {
548 free(*logmsg);
549 *logmsg = NULL;
551 return err;
554 static const struct got_error *
555 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
556 const char *path_dir, const char *branch_name)
558 char *initial_content = NULL;
559 const struct got_error *err = NULL;
560 int initial_content_len;
561 int fd = -1;
563 initial_content_len = asprintf(&initial_content,
564 "\n# %s to be imported to branch %s\n", path_dir,
565 branch_name);
566 if (initial_content_len == -1)
567 return got_error_from_errno("asprintf");
569 err = got_opentemp_named_fd(logmsg_path, &fd,
570 GOT_TMPDIR_STR "/got-importmsg");
571 if (err)
572 goto done;
574 if (write(fd, initial_content, initial_content_len) == -1) {
575 err = got_error_from_errno2("write", *logmsg_path);
576 goto done;
579 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
580 initial_content_len, 1);
581 done:
582 if (fd != -1 && close(fd) == -1 && err == NULL)
583 err = got_error_from_errno2("close", *logmsg_path);
584 free(initial_content);
585 if (err) {
586 free(*logmsg_path);
587 *logmsg_path = NULL;
589 return err;
592 static const struct got_error *
593 import_progress(void *arg, const char *path)
595 printf("A %s\n", path);
596 return NULL;
599 static const struct got_error *
600 get_author(char **author, struct got_repository *repo,
601 struct got_worktree *worktree)
603 const struct got_error *err = NULL;
604 const char *got_author = NULL, *name, *email;
605 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
607 *author = NULL;
609 if (worktree)
610 worktree_conf = got_worktree_get_gotconfig(worktree);
611 repo_conf = got_repo_get_gotconfig(repo);
613 /*
614 * Priority of potential author information sources, from most
615 * significant to least significant:
616 * 1) work tree's .got/got.conf file
617 * 2) repository's got.conf file
618 * 3) repository's git config file
619 * 4) environment variables
620 * 5) global git config files (in user's home directory or /etc)
621 */
623 if (worktree_conf)
624 got_author = got_gotconfig_get_author(worktree_conf);
625 if (got_author == NULL)
626 got_author = got_gotconfig_get_author(repo_conf);
627 if (got_author == NULL) {
628 name = got_repo_get_gitconfig_author_name(repo);
629 email = got_repo_get_gitconfig_author_email(repo);
630 if (name && email) {
631 if (asprintf(author, "%s <%s>", name, email) == -1)
632 return got_error_from_errno("asprintf");
633 return NULL;
636 got_author = getenv("GOT_AUTHOR");
637 if (got_author == NULL) {
638 name = got_repo_get_global_gitconfig_author_name(repo);
639 email = got_repo_get_global_gitconfig_author_email(
640 repo);
641 if (name && email) {
642 if (asprintf(author, "%s <%s>", name, email)
643 == -1)
644 return got_error_from_errno("asprintf");
645 return NULL;
647 /* TODO: Look up user in password database? */
648 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
652 *author = strdup(got_author);
653 if (*author == NULL)
654 return got_error_from_errno("strdup");
656 /*
657 * Really dumb email address check; we're only doing this to
658 * avoid git's object parser breaking on commits we create.
659 */
660 while (*got_author && *got_author != '<')
661 got_author++;
662 if (*got_author != '<') {
663 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
664 goto done;
666 while (*got_author && *got_author != '@')
667 got_author++;
668 if (*got_author != '@') {
669 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
670 goto done;
672 while (*got_author && *got_author != '>')
673 got_author++;
674 if (*got_author != '>')
675 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
676 done:
677 if (err) {
678 free(*author);
679 *author = NULL;
681 return err;
684 static const struct got_error *
685 get_gitconfig_path(char **gitconfig_path)
687 const char *homedir = getenv("HOME");
689 *gitconfig_path = NULL;
690 if (homedir) {
691 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
692 return got_error_from_errno("asprintf");
695 return NULL;
698 static const struct got_error *
699 cmd_import(int argc, char *argv[])
701 const struct got_error *error = NULL;
702 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
703 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
704 const char *branch_name = "main";
705 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
706 struct got_repository *repo = NULL;
707 struct got_reference *branch_ref = NULL, *head_ref = NULL;
708 struct got_object_id *new_commit_id = NULL;
709 int ch;
710 struct got_pathlist_head ignores;
711 struct got_pathlist_entry *pe;
712 int preserve_logmsg = 0;
714 TAILQ_INIT(&ignores);
716 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
717 switch (ch) {
718 case 'b':
719 branch_name = optarg;
720 break;
721 case 'm':
722 logmsg = strdup(optarg);
723 if (logmsg == NULL) {
724 error = got_error_from_errno("strdup");
725 goto done;
727 break;
728 case 'r':
729 repo_path = realpath(optarg, NULL);
730 if (repo_path == NULL) {
731 error = got_error_from_errno2("realpath",
732 optarg);
733 goto done;
735 break;
736 case 'I':
737 if (optarg[0] == '\0')
738 break;
739 error = got_pathlist_insert(&pe, &ignores, optarg,
740 NULL);
741 if (error)
742 goto done;
743 break;
744 default:
745 usage_import();
746 /* NOTREACHED */
750 argc -= optind;
751 argv += optind;
753 #ifndef PROFILE
754 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
755 "unveil",
756 NULL) == -1)
757 err(1, "pledge");
758 #endif
759 if (argc != 1)
760 usage_import();
762 if (repo_path == NULL) {
763 repo_path = getcwd(NULL, 0);
764 if (repo_path == NULL)
765 return got_error_from_errno("getcwd");
767 got_path_strip_trailing_slashes(repo_path);
768 error = get_gitconfig_path(&gitconfig_path);
769 if (error)
770 goto done;
771 error = got_repo_open(&repo, repo_path, gitconfig_path);
772 if (error)
773 goto done;
775 error = get_author(&author, repo, NULL);
776 if (error)
777 return error;
779 /*
780 * Don't let the user create a branch name with a leading '-'.
781 * While technically a valid reference name, this case is usually
782 * an unintended typo.
783 */
784 if (branch_name[0] == '-')
785 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
787 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
788 error = got_error_from_errno("asprintf");
789 goto done;
792 error = got_ref_open(&branch_ref, repo, refname, 0);
793 if (error) {
794 if (error->code != GOT_ERR_NOT_REF)
795 goto done;
796 } else {
797 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
798 "import target branch already exists");
799 goto done;
802 path_dir = realpath(argv[0], NULL);
803 if (path_dir == NULL) {
804 error = got_error_from_errno2("realpath", argv[0]);
805 goto done;
807 got_path_strip_trailing_slashes(path_dir);
809 /*
810 * unveil(2) traverses exec(2); if an editor is used we have
811 * to apply unveil after the log message has been written.
812 */
813 if (logmsg == NULL || strlen(logmsg) == 0) {
814 error = get_editor(&editor);
815 if (error)
816 goto done;
817 free(logmsg);
818 error = collect_import_msg(&logmsg, &logmsg_path, editor,
819 path_dir, refname);
820 if (error) {
821 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
822 logmsg_path != NULL)
823 preserve_logmsg = 1;
824 goto done;
828 if (unveil(path_dir, "r") != 0) {
829 error = got_error_from_errno2("unveil", path_dir);
830 if (logmsg_path)
831 preserve_logmsg = 1;
832 goto done;
835 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
836 if (error) {
837 if (logmsg_path)
838 preserve_logmsg = 1;
839 goto done;
842 error = got_repo_import(&new_commit_id, path_dir, logmsg,
843 author, &ignores, repo, import_progress, NULL);
844 if (error) {
845 if (logmsg_path)
846 preserve_logmsg = 1;
847 goto done;
850 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
851 if (error) {
852 if (logmsg_path)
853 preserve_logmsg = 1;
854 goto done;
857 error = got_ref_write(branch_ref, repo);
858 if (error) {
859 if (logmsg_path)
860 preserve_logmsg = 1;
861 goto done;
864 error = got_object_id_str(&id_str, new_commit_id);
865 if (error) {
866 if (logmsg_path)
867 preserve_logmsg = 1;
868 goto done;
871 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
872 if (error) {
873 if (error->code != GOT_ERR_NOT_REF) {
874 if (logmsg_path)
875 preserve_logmsg = 1;
876 goto done;
879 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
880 branch_ref);
881 if (error) {
882 if (logmsg_path)
883 preserve_logmsg = 1;
884 goto done;
887 error = got_ref_write(head_ref, repo);
888 if (error) {
889 if (logmsg_path)
890 preserve_logmsg = 1;
891 goto done;
895 printf("Created branch %s with commit %s\n",
896 got_ref_get_name(branch_ref), id_str);
897 done:
898 if (preserve_logmsg) {
899 fprintf(stderr, "%s: log message preserved in %s\n",
900 getprogname(), logmsg_path);
901 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
902 error = got_error_from_errno2("unlink", logmsg_path);
903 free(logmsg);
904 free(logmsg_path);
905 free(repo_path);
906 free(editor);
907 free(refname);
908 free(new_commit_id);
909 free(id_str);
910 free(author);
911 free(gitconfig_path);
912 if (branch_ref)
913 got_ref_close(branch_ref);
914 if (head_ref)
915 got_ref_close(head_ref);
916 return error;
919 __dead static void
920 usage_clone(void)
922 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
923 "[-R reference] repository-url [directory]\n", getprogname());
924 exit(1);
927 struct got_fetch_progress_arg {
928 char last_scaled_size[FMT_SCALED_STRSIZE];
929 int last_p_indexed;
930 int last_p_resolved;
931 int verbosity;
933 struct got_repository *repo;
935 int create_configs;
936 int configs_created;
937 struct {
938 struct got_pathlist_head *symrefs;
939 struct got_pathlist_head *wanted_branches;
940 struct got_pathlist_head *wanted_refs;
941 const char *proto;
942 const char *host;
943 const char *port;
944 const char *remote_repo_path;
945 const char *git_url;
946 int fetch_all_branches;
947 int mirror_references;
948 } config_info;
949 };
951 /* XXX forward declaration */
952 static const struct got_error *
953 create_config_files(const char *proto, const char *host, const char *port,
954 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
955 int mirror_references, struct got_pathlist_head *symrefs,
956 struct got_pathlist_head *wanted_branches,
957 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
959 static const struct got_error *
960 fetch_progress(void *arg, const char *message, off_t packfile_size,
961 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
963 const struct got_error *err = NULL;
964 struct got_fetch_progress_arg *a = arg;
965 char scaled_size[FMT_SCALED_STRSIZE];
966 int p_indexed, p_resolved;
967 int print_size = 0, print_indexed = 0, print_resolved = 0;
969 /*
970 * In order to allow a failed clone to be resumed with 'got fetch'
971 * we try to create configuration files as soon as possible.
972 * Once the server has sent information about its default branch
973 * we have all required information.
974 */
975 if (a->create_configs && !a->configs_created &&
976 !TAILQ_EMPTY(a->config_info.symrefs)) {
977 err = create_config_files(a->config_info.proto,
978 a->config_info.host, a->config_info.port,
979 a->config_info.remote_repo_path,
980 a->config_info.git_url,
981 a->config_info.fetch_all_branches,
982 a->config_info.mirror_references,
983 a->config_info.symrefs,
984 a->config_info.wanted_branches,
985 a->config_info.wanted_refs, a->repo);
986 if (err)
987 return err;
988 a->configs_created = 1;
991 if (a->verbosity < 0)
992 return NULL;
994 if (message && message[0] != '\0') {
995 printf("\rserver: %s", message);
996 fflush(stdout);
997 return NULL;
1000 if (packfile_size > 0 || nobj_indexed > 0) {
1001 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1002 (a->last_scaled_size[0] == '\0' ||
1003 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1004 print_size = 1;
1005 if (strlcpy(a->last_scaled_size, scaled_size,
1006 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1007 return got_error(GOT_ERR_NO_SPACE);
1009 if (nobj_indexed > 0) {
1010 p_indexed = (nobj_indexed * 100) / nobj_total;
1011 if (p_indexed != a->last_p_indexed) {
1012 a->last_p_indexed = p_indexed;
1013 print_indexed = 1;
1014 print_size = 1;
1017 if (nobj_resolved > 0) {
1018 p_resolved = (nobj_resolved * 100) /
1019 (nobj_total - nobj_loose);
1020 if (p_resolved != a->last_p_resolved) {
1021 a->last_p_resolved = p_resolved;
1022 print_resolved = 1;
1023 print_indexed = 1;
1024 print_size = 1;
1029 if (print_size || print_indexed || print_resolved)
1030 printf("\r");
1031 if (print_size)
1032 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1033 if (print_indexed)
1034 printf("; indexing %d%%", p_indexed);
1035 if (print_resolved)
1036 printf("; resolving deltas %d%%", p_resolved);
1037 if (print_size || print_indexed || print_resolved)
1038 fflush(stdout);
1040 return NULL;
1043 static const struct got_error *
1044 create_symref(const char *refname, struct got_reference *target_ref,
1045 int verbosity, struct got_repository *repo)
1047 const struct got_error *err;
1048 struct got_reference *head_symref;
1050 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1051 if (err)
1052 return err;
1054 err = got_ref_write(head_symref, repo);
1055 if (err == NULL && verbosity > 0) {
1056 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1057 got_ref_get_name(target_ref));
1059 got_ref_close(head_symref);
1060 return err;
1063 static const struct got_error *
1064 list_remote_refs(struct got_pathlist_head *symrefs,
1065 struct got_pathlist_head *refs)
1067 const struct got_error *err;
1068 struct got_pathlist_entry *pe;
1070 TAILQ_FOREACH(pe, symrefs, entry) {
1071 const char *refname = pe->path;
1072 const char *targetref = pe->data;
1074 printf("%s: %s\n", refname, targetref);
1077 TAILQ_FOREACH(pe, refs, entry) {
1078 const char *refname = pe->path;
1079 struct got_object_id *id = pe->data;
1080 char *id_str;
1082 err = got_object_id_str(&id_str, id);
1083 if (err)
1084 return err;
1085 printf("%s: %s\n", refname, id_str);
1086 free(id_str);
1089 return NULL;
1092 static const struct got_error *
1093 create_ref(const char *refname, struct got_object_id *id,
1094 int verbosity, struct got_repository *repo)
1096 const struct got_error *err = NULL;
1097 struct got_reference *ref;
1098 char *id_str;
1100 err = got_object_id_str(&id_str, id);
1101 if (err)
1102 return err;
1104 err = got_ref_alloc(&ref, refname, id);
1105 if (err)
1106 goto done;
1108 err = got_ref_write(ref, repo);
1109 got_ref_close(ref);
1111 if (err == NULL && verbosity >= 0)
1112 printf("Created reference %s: %s\n", refname, id_str);
1113 done:
1114 free(id_str);
1115 return err;
1118 static int
1119 match_wanted_ref(const char *refname, const char *wanted_ref)
1121 if (strncmp(refname, "refs/", 5) != 0)
1122 return 0;
1123 refname += 5;
1126 * Prevent fetching of references that won't make any
1127 * sense outside of the remote repository's context.
1129 if (strncmp(refname, "got/", 4) == 0)
1130 return 0;
1131 if (strncmp(refname, "remotes/", 8) == 0)
1132 return 0;
1134 if (strncmp(wanted_ref, "refs/", 5) == 0)
1135 wanted_ref += 5;
1137 /* Allow prefix match. */
1138 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1139 return 1;
1141 /* Allow exact match. */
1142 return (strcmp(refname, wanted_ref) == 0);
1145 static int
1146 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1148 struct got_pathlist_entry *pe;
1150 TAILQ_FOREACH(pe, wanted_refs, entry) {
1151 if (match_wanted_ref(refname, pe->path))
1152 return 1;
1155 return 0;
1158 static const struct got_error *
1159 create_wanted_ref(const char *refname, struct got_object_id *id,
1160 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1162 const struct got_error *err;
1163 char *remote_refname;
1165 if (strncmp("refs/", refname, 5) == 0)
1166 refname += 5;
1168 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1169 remote_repo_name, refname) == -1)
1170 return got_error_from_errno("asprintf");
1172 err = create_ref(remote_refname, id, verbosity, repo);
1173 free(remote_refname);
1174 return err;
1177 static const struct got_error *
1178 create_gotconfig(const char *proto, const char *host, const char *port,
1179 const char *remote_repo_path, const char *default_branch,
1180 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1181 struct got_pathlist_head *wanted_refs, int mirror_references,
1182 struct got_repository *repo)
1184 const struct got_error *err = NULL;
1185 char *gotconfig_path = NULL;
1186 char *gotconfig = NULL;
1187 FILE *gotconfig_file = NULL;
1188 const char *branchname = NULL;
1189 char *branches = NULL, *refs = NULL;
1190 ssize_t n;
1192 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1193 struct got_pathlist_entry *pe;
1194 TAILQ_FOREACH(pe, wanted_branches, entry) {
1195 char *s;
1196 branchname = pe->path;
1197 if (strncmp(branchname, "refs/heads/", 11) == 0)
1198 branchname += 11;
1199 if (asprintf(&s, "%s\"%s\" ",
1200 branches ? branches : "", branchname) == -1) {
1201 err = got_error_from_errno("asprintf");
1202 goto done;
1204 free(branches);
1205 branches = s;
1207 } else if (!fetch_all_branches && default_branch) {
1208 branchname = default_branch;
1209 if (strncmp(branchname, "refs/heads/", 11) == 0)
1210 branchname += 11;
1211 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1212 err = got_error_from_errno("asprintf");
1213 goto done;
1216 if (!TAILQ_EMPTY(wanted_refs)) {
1217 struct got_pathlist_entry *pe;
1218 TAILQ_FOREACH(pe, wanted_refs, entry) {
1219 char *s;
1220 const char *refname = pe->path;
1221 if (strncmp(refname, "refs/", 5) == 0)
1222 branchname += 5;
1223 if (asprintf(&s, "%s\"%s\" ",
1224 refs ? refs : "", refname) == -1) {
1225 err = got_error_from_errno("asprintf");
1226 goto done;
1228 free(refs);
1229 refs = s;
1233 /* Create got.conf(5). */
1234 gotconfig_path = got_repo_get_path_gotconfig(repo);
1235 if (gotconfig_path == NULL) {
1236 err = got_error_from_errno("got_repo_get_path_gotconfig");
1237 goto done;
1239 gotconfig_file = fopen(gotconfig_path, "a");
1240 if (gotconfig_file == NULL) {
1241 err = got_error_from_errno2("fopen", gotconfig_path);
1242 goto done;
1244 if (asprintf(&gotconfig,
1245 "remote \"%s\" {\n"
1246 "\tserver %s\n"
1247 "\tprotocol %s\n"
1248 "%s%s%s"
1249 "\trepository \"%s\"\n"
1250 "%s%s%s"
1251 "%s%s%s"
1252 "%s"
1253 "%s"
1254 "}\n",
1255 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1256 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1257 remote_repo_path, branches ? "\tbranch { " : "",
1258 branches ? branches : "", branches ? "}\n" : "",
1259 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1260 mirror_references ? "\tmirror-references yes\n" : "",
1261 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1262 err = got_error_from_errno("asprintf");
1263 goto done;
1265 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1266 if (n != strlen(gotconfig)) {
1267 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1268 goto done;
1271 done:
1272 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1273 err = got_error_from_errno2("fclose", gotconfig_path);
1274 free(gotconfig_path);
1275 free(branches);
1276 return err;
1279 static const struct got_error *
1280 create_gitconfig(const char *git_url, const char *default_branch,
1281 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1282 struct got_pathlist_head *wanted_refs, int mirror_references,
1283 struct got_repository *repo)
1285 const struct got_error *err = NULL;
1286 char *gitconfig_path = NULL;
1287 char *gitconfig = NULL;
1288 FILE *gitconfig_file = NULL;
1289 char *branches = NULL, *refs = NULL;
1290 const char *branchname;
1291 ssize_t n;
1293 /* Create a config file Git can understand. */
1294 gitconfig_path = got_repo_get_path_gitconfig(repo);
1295 if (gitconfig_path == NULL) {
1296 err = got_error_from_errno("got_repo_get_path_gitconfig");
1297 goto done;
1299 gitconfig_file = fopen(gitconfig_path, "a");
1300 if (gitconfig_file == NULL) {
1301 err = got_error_from_errno2("fopen", gitconfig_path);
1302 goto done;
1304 if (fetch_all_branches) {
1305 if (mirror_references) {
1306 if (asprintf(&branches,
1307 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1308 err = got_error_from_errno("asprintf");
1309 goto done;
1311 } else if (asprintf(&branches,
1312 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1313 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1314 err = got_error_from_errno("asprintf");
1315 goto done;
1317 } else if (!TAILQ_EMPTY(wanted_branches)) {
1318 struct got_pathlist_entry *pe;
1319 TAILQ_FOREACH(pe, wanted_branches, entry) {
1320 char *s;
1321 branchname = pe->path;
1322 if (strncmp(branchname, "refs/heads/", 11) == 0)
1323 branchname += 11;
1324 if (mirror_references) {
1325 if (asprintf(&s,
1326 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1327 branches ? branches : "",
1328 branchname, branchname) == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 } else if (asprintf(&s,
1333 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1334 branches ? branches : "",
1335 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1336 branchname) == -1) {
1337 err = got_error_from_errno("asprintf");
1338 goto done;
1340 free(branches);
1341 branches = s;
1343 } else {
1345 * If the server specified a default branch, use just that one.
1346 * Otherwise fall back to fetching all branches on next fetch.
1348 if (default_branch) {
1349 branchname = default_branch;
1350 if (strncmp(branchname, "refs/heads/", 11) == 0)
1351 branchname += 11;
1352 } else
1353 branchname = "*"; /* fall back to all branches */
1354 if (mirror_references) {
1355 if (asprintf(&branches,
1356 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1357 branchname, branchname) == -1) {
1358 err = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (asprintf(&branches,
1362 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1363 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1364 branchname) == -1) {
1365 err = got_error_from_errno("asprintf");
1366 goto done;
1369 if (!TAILQ_EMPTY(wanted_refs)) {
1370 struct got_pathlist_entry *pe;
1371 TAILQ_FOREACH(pe, wanted_refs, entry) {
1372 char *s;
1373 const char *refname = pe->path;
1374 if (strncmp(refname, "refs/", 5) == 0)
1375 refname += 5;
1376 if (mirror_references) {
1377 if (asprintf(&s,
1378 "%s\tfetch = refs/%s:refs/%s\n",
1379 refs ? refs : "", refname, refname) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1383 } else if (asprintf(&s,
1384 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1385 refs ? refs : "",
1386 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1387 refname) == -1) {
1388 err = got_error_from_errno("asprintf");
1389 goto done;
1391 free(refs);
1392 refs = s;
1396 if (asprintf(&gitconfig,
1397 "[remote \"%s\"]\n"
1398 "\turl = %s\n"
1399 "%s"
1400 "%s"
1401 "\tfetch = refs/tags/*:refs/tags/*\n",
1402 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1403 refs ? refs : "") == -1) {
1404 err = got_error_from_errno("asprintf");
1405 goto done;
1407 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1408 if (n != strlen(gitconfig)) {
1409 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1410 goto done;
1412 done:
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1414 err = got_error_from_errno2("fclose", gitconfig_path);
1415 free(gitconfig_path);
1416 free(branches);
1417 return err;
1420 static const struct got_error *
1421 create_config_files(const char *proto, const char *host, const char *port,
1422 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1423 int mirror_references, struct got_pathlist_head *symrefs,
1424 struct got_pathlist_head *wanted_branches,
1425 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1427 const struct got_error *err = NULL;
1428 const char *default_branch = NULL;
1429 struct got_pathlist_entry *pe;
1432 * If we asked for a set of wanted branches then use the first
1433 * one of those.
1435 if (!TAILQ_EMPTY(wanted_branches)) {
1436 pe = TAILQ_FIRST(wanted_branches);
1437 default_branch = pe->path;
1438 } else {
1439 /* First HEAD ref listed by server is the default branch. */
1440 TAILQ_FOREACH(pe, symrefs, entry) {
1441 const char *refname = pe->path;
1442 const char *target = pe->data;
1444 if (strcmp(refname, GOT_REF_HEAD) != 0)
1445 continue;
1447 default_branch = target;
1448 break;
1452 /* Create got.conf(5). */
1453 err = create_gotconfig(proto, host, port, remote_repo_path,
1454 default_branch, fetch_all_branches, wanted_branches,
1455 wanted_refs, mirror_references, repo);
1456 if (err)
1457 return err;
1459 /* Create a config file Git can understand. */
1460 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1461 wanted_branches, wanted_refs, mirror_references, repo);
1464 static const struct got_error *
1465 cmd_clone(int argc, char *argv[])
1467 const struct got_error *error = NULL;
1468 const char *uri, *dirname;
1469 char *proto, *host, *port, *repo_name, *server_path;
1470 char *default_destdir = NULL, *id_str = NULL;
1471 const char *repo_path;
1472 struct got_repository *repo = NULL;
1473 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1474 struct got_pathlist_entry *pe;
1475 struct got_object_id *pack_hash = NULL;
1476 int ch, fetchfd = -1, fetchstatus;
1477 pid_t fetchpid = -1;
1478 struct got_fetch_progress_arg fpa;
1479 char *git_url = NULL;
1480 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1481 int list_refs_only = 0;
1483 TAILQ_INIT(&refs);
1484 TAILQ_INIT(&symrefs);
1485 TAILQ_INIT(&wanted_branches);
1486 TAILQ_INIT(&wanted_refs);
1488 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1489 switch (ch) {
1490 case 'a':
1491 fetch_all_branches = 1;
1492 break;
1493 case 'b':
1494 error = got_pathlist_append(&wanted_branches,
1495 optarg, NULL);
1496 if (error)
1497 return error;
1498 break;
1499 case 'l':
1500 list_refs_only = 1;
1501 break;
1502 case 'm':
1503 mirror_references = 1;
1504 break;
1505 case 'v':
1506 if (verbosity < 0)
1507 verbosity = 0;
1508 else if (verbosity < 3)
1509 verbosity++;
1510 break;
1511 case 'q':
1512 verbosity = -1;
1513 break;
1514 case 'R':
1515 error = got_pathlist_append(&wanted_refs,
1516 optarg, NULL);
1517 if (error)
1518 return error;
1519 break;
1520 default:
1521 usage_clone();
1522 break;
1525 argc -= optind;
1526 argv += optind;
1528 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1529 option_conflict('a', 'b');
1530 if (list_refs_only) {
1531 if (!TAILQ_EMPTY(&wanted_branches))
1532 option_conflict('l', 'b');
1533 if (fetch_all_branches)
1534 option_conflict('l', 'a');
1535 if (mirror_references)
1536 option_conflict('l', 'm');
1537 if (!TAILQ_EMPTY(&wanted_refs))
1538 option_conflict('l', 'R');
1541 uri = argv[0];
1543 if (argc == 1)
1544 dirname = NULL;
1545 else if (argc == 2)
1546 dirname = argv[1];
1547 else
1548 usage_clone();
1550 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1551 &repo_name, uri);
1552 if (error)
1553 goto done;
1555 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1556 host, port ? ":" : "", port ? port : "",
1557 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1558 error = got_error_from_errno("asprintf");
1559 goto done;
1562 if (strcmp(proto, "git") == 0) {
1563 #ifndef PROFILE
1564 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1565 "sendfd dns inet unveil", NULL) == -1)
1566 err(1, "pledge");
1567 #endif
1568 } else if (strcmp(proto, "git+ssh") == 0 ||
1569 strcmp(proto, "ssh") == 0) {
1570 #ifndef PROFILE
1571 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1572 "sendfd unveil", NULL) == -1)
1573 err(1, "pledge");
1574 #endif
1575 } else if (strcmp(proto, "http") == 0 ||
1576 strcmp(proto, "git+http") == 0) {
1577 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1578 goto done;
1579 } else {
1580 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1581 goto done;
1583 if (dirname == NULL) {
1584 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1585 error = got_error_from_errno("asprintf");
1586 goto done;
1588 repo_path = default_destdir;
1589 } else
1590 repo_path = dirname;
1592 if (!list_refs_only) {
1593 error = got_path_mkdir(repo_path);
1594 if (error &&
1595 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1596 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1597 goto done;
1598 if (!got_path_dir_is_empty(repo_path)) {
1599 error = got_error_path(repo_path,
1600 GOT_ERR_DIR_NOT_EMPTY);
1601 goto done;
1605 error = got_dial_apply_unveil(proto);
1606 if (error)
1607 goto done;
1609 error = apply_unveil(repo_path, 0, NULL);
1610 if (error)
1611 goto done;
1613 if (verbosity >= 0)
1614 printf("Connecting to %s%s%s\n", host,
1615 port ? ":" : "", port ? port : "");
1617 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1618 server_path, verbosity);
1619 if (error)
1620 goto done;
1622 if (!list_refs_only) {
1623 error = got_repo_init(repo_path);
1624 if (error)
1625 goto done;
1626 error = got_repo_open(&repo, repo_path, NULL);
1627 if (error)
1628 goto done;
1631 fpa.last_scaled_size[0] = '\0';
1632 fpa.last_p_indexed = -1;
1633 fpa.last_p_resolved = -1;
1634 fpa.verbosity = verbosity;
1635 fpa.create_configs = 1;
1636 fpa.configs_created = 0;
1637 fpa.repo = repo;
1638 fpa.config_info.symrefs = &symrefs;
1639 fpa.config_info.wanted_branches = &wanted_branches;
1640 fpa.config_info.wanted_refs = &wanted_refs;
1641 fpa.config_info.proto = proto;
1642 fpa.config_info.host = host;
1643 fpa.config_info.port = port;
1644 fpa.config_info.remote_repo_path = server_path;
1645 fpa.config_info.git_url = git_url;
1646 fpa.config_info.fetch_all_branches = fetch_all_branches;
1647 fpa.config_info.mirror_references = mirror_references;
1648 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1649 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1650 fetch_all_branches, &wanted_branches, &wanted_refs,
1651 list_refs_only, verbosity, fetchfd, repo,
1652 fetch_progress, &fpa);
1653 if (error)
1654 goto done;
1656 if (list_refs_only) {
1657 error = list_remote_refs(&symrefs, &refs);
1658 goto done;
1661 error = got_object_id_str(&id_str, pack_hash);
1662 if (error)
1663 goto done;
1664 if (verbosity >= 0)
1665 printf("\nFetched %s.pack\n", id_str);
1666 free(id_str);
1668 /* Set up references provided with the pack file. */
1669 TAILQ_FOREACH(pe, &refs, entry) {
1670 const char *refname = pe->path;
1671 struct got_object_id *id = pe->data;
1672 char *remote_refname;
1674 if (is_wanted_ref(&wanted_refs, refname) &&
1675 !mirror_references) {
1676 error = create_wanted_ref(refname, id,
1677 GOT_FETCH_DEFAULT_REMOTE_NAME,
1678 verbosity - 1, repo);
1679 if (error)
1680 goto done;
1681 continue;
1684 error = create_ref(refname, id, verbosity - 1, repo);
1685 if (error)
1686 goto done;
1688 if (mirror_references)
1689 continue;
1691 if (strncmp("refs/heads/", refname, 11) != 0)
1692 continue;
1694 if (asprintf(&remote_refname,
1695 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1696 refname + 11) == -1) {
1697 error = got_error_from_errno("asprintf");
1698 goto done;
1700 error = create_ref(remote_refname, id, verbosity - 1, repo);
1701 free(remote_refname);
1702 if (error)
1703 goto done;
1706 /* Set the HEAD reference if the server provided one. */
1707 TAILQ_FOREACH(pe, &symrefs, entry) {
1708 struct got_reference *target_ref;
1709 const char *refname = pe->path;
1710 const char *target = pe->data;
1711 char *remote_refname = NULL, *remote_target = NULL;
1713 if (strcmp(refname, GOT_REF_HEAD) != 0)
1714 continue;
1716 error = got_ref_open(&target_ref, repo, target, 0);
1717 if (error) {
1718 if (error->code == GOT_ERR_NOT_REF) {
1719 error = NULL;
1720 continue;
1722 goto done;
1725 error = create_symref(refname, target_ref, verbosity, repo);
1726 got_ref_close(target_ref);
1727 if (error)
1728 goto done;
1730 if (mirror_references)
1731 continue;
1733 if (strncmp("refs/heads/", target, 11) != 0)
1734 continue;
1736 if (asprintf(&remote_refname,
1737 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1738 refname) == -1) {
1739 error = got_error_from_errno("asprintf");
1740 goto done;
1742 if (asprintf(&remote_target,
1743 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1744 target + 11) == -1) {
1745 error = got_error_from_errno("asprintf");
1746 free(remote_refname);
1747 goto done;
1749 error = got_ref_open(&target_ref, repo, remote_target, 0);
1750 if (error) {
1751 free(remote_refname);
1752 free(remote_target);
1753 if (error->code == GOT_ERR_NOT_REF) {
1754 error = NULL;
1755 continue;
1757 goto done;
1759 error = create_symref(remote_refname, target_ref,
1760 verbosity - 1, repo);
1761 free(remote_refname);
1762 free(remote_target);
1763 got_ref_close(target_ref);
1764 if (error)
1765 goto done;
1767 if (pe == NULL) {
1769 * We failed to set the HEAD reference. If we asked for
1770 * a set of wanted branches use the first of one of those
1771 * which could be fetched instead.
1773 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1774 const char *target = pe->path;
1775 struct got_reference *target_ref;
1777 error = got_ref_open(&target_ref, repo, target, 0);
1778 if (error) {
1779 if (error->code == GOT_ERR_NOT_REF) {
1780 error = NULL;
1781 continue;
1783 goto done;
1786 error = create_symref(GOT_REF_HEAD, target_ref,
1787 verbosity, repo);
1788 got_ref_close(target_ref);
1789 if (error)
1790 goto done;
1791 break;
1795 if (verbosity >= 0)
1796 printf("Created %s repository '%s'\n",
1797 mirror_references ? "mirrored" : "cloned", repo_path);
1798 done:
1799 if (fetchpid > 0) {
1800 if (kill(fetchpid, SIGTERM) == -1)
1801 error = got_error_from_errno("kill");
1802 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1803 error = got_error_from_errno("waitpid");
1805 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1806 error = got_error_from_errno("close");
1807 if (repo) {
1808 const struct got_error *close_err = got_repo_close(repo);
1809 if (error == NULL)
1810 error = close_err;
1812 TAILQ_FOREACH(pe, &refs, entry) {
1813 free((void *)pe->path);
1814 free(pe->data);
1816 got_pathlist_free(&refs);
1817 TAILQ_FOREACH(pe, &symrefs, entry) {
1818 free((void *)pe->path);
1819 free(pe->data);
1821 got_pathlist_free(&symrefs);
1822 got_pathlist_free(&wanted_branches);
1823 got_pathlist_free(&wanted_refs);
1824 free(pack_hash);
1825 free(proto);
1826 free(host);
1827 free(port);
1828 free(server_path);
1829 free(repo_name);
1830 free(default_destdir);
1831 free(git_url);
1832 return error;
1835 static const struct got_error *
1836 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1837 int replace_tags, int verbosity, struct got_repository *repo)
1839 const struct got_error *err = NULL;
1840 char *new_id_str = NULL;
1841 struct got_object_id *old_id = NULL;
1843 err = got_object_id_str(&new_id_str, new_id);
1844 if (err)
1845 goto done;
1847 if (!replace_tags &&
1848 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1849 err = got_ref_resolve(&old_id, repo, ref);
1850 if (err)
1851 goto done;
1852 if (got_object_id_cmp(old_id, new_id) == 0)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Rejecting update of existing tag %s: %s\n",
1856 got_ref_get_name(ref), new_id_str);
1858 goto done;
1861 if (got_ref_is_symbolic(ref)) {
1862 if (verbosity >= 0) {
1863 printf("Replacing reference %s: %s\n",
1864 got_ref_get_name(ref),
1865 got_ref_get_symref_target(ref));
1867 err = got_ref_change_symref_to_ref(ref, new_id);
1868 if (err)
1869 goto done;
1870 err = got_ref_write(ref, repo);
1871 if (err)
1872 goto done;
1873 } else {
1874 err = got_ref_resolve(&old_id, repo, ref);
1875 if (err)
1876 goto done;
1877 if (got_object_id_cmp(old_id, new_id) == 0)
1878 goto done;
1880 err = got_ref_change_ref(ref, new_id);
1881 if (err)
1882 goto done;
1883 err = got_ref_write(ref, repo);
1884 if (err)
1885 goto done;
1888 if (verbosity >= 0)
1889 printf("Updated %s: %s\n", got_ref_get_name(ref),
1890 new_id_str);
1891 done:
1892 free(old_id);
1893 free(new_id_str);
1894 return err;
1897 static const struct got_error *
1898 update_symref(const char *refname, struct got_reference *target_ref,
1899 int verbosity, struct got_repository *repo)
1901 const struct got_error *err = NULL, *unlock_err;
1902 struct got_reference *symref;
1903 int symref_is_locked = 0;
1905 err = got_ref_open(&symref, repo, refname, 1);
1906 if (err) {
1907 if (err->code != GOT_ERR_NOT_REF)
1908 return err;
1909 err = got_ref_alloc_symref(&symref, refname, target_ref);
1910 if (err)
1911 goto done;
1913 err = got_ref_write(symref, repo);
1914 if (err)
1915 goto done;
1917 if (verbosity >= 0)
1918 printf("Created reference %s: %s\n",
1919 got_ref_get_name(symref),
1920 got_ref_get_symref_target(symref));
1921 } else {
1922 symref_is_locked = 1;
1924 if (strcmp(got_ref_get_symref_target(symref),
1925 got_ref_get_name(target_ref)) == 0)
1926 goto done;
1928 err = got_ref_change_symref(symref,
1929 got_ref_get_name(target_ref));
1930 if (err)
1931 goto done;
1933 err = got_ref_write(symref, repo);
1934 if (err)
1935 goto done;
1937 if (verbosity >= 0)
1938 printf("Updated %s: %s\n", got_ref_get_name(symref),
1939 got_ref_get_symref_target(symref));
1942 done:
1943 if (symref_is_locked) {
1944 unlock_err = got_ref_unlock(symref);
1945 if (unlock_err && err == NULL)
1946 err = unlock_err;
1948 got_ref_close(symref);
1949 return err;
1952 __dead static void
1953 usage_fetch(void)
1955 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1956 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1957 "[remote-repository-name]\n",
1958 getprogname());
1959 exit(1);
1962 static const struct got_error *
1963 delete_missing_ref(struct got_reference *ref,
1964 int verbosity, struct got_repository *repo)
1966 const struct got_error *err = NULL;
1967 struct got_object_id *id = NULL;
1968 char *id_str = NULL;
1970 if (got_ref_is_symbolic(ref)) {
1971 err = got_ref_delete(ref, repo);
1972 if (err)
1973 return err;
1974 if (verbosity >= 0) {
1975 printf("Deleted %s: %s\n",
1976 got_ref_get_name(ref),
1977 got_ref_get_symref_target(ref));
1979 } else {
1980 err = got_ref_resolve(&id, repo, ref);
1981 if (err)
1982 return err;
1983 err = got_object_id_str(&id_str, id);
1984 if (err)
1985 goto done;
1987 err = got_ref_delete(ref, repo);
1988 if (err)
1989 goto done;
1990 if (verbosity >= 0) {
1991 printf("Deleted %s: %s\n",
1992 got_ref_get_name(ref), id_str);
1995 done:
1996 free(id);
1997 free(id_str);
1998 return NULL;
2001 static const struct got_error *
2002 delete_missing_refs(struct got_pathlist_head *their_refs,
2003 struct got_pathlist_head *their_symrefs,
2004 const struct got_remote_repo *remote,
2005 int verbosity, struct got_repository *repo)
2007 const struct got_error *err = NULL, *unlock_err;
2008 struct got_reflist_head my_refs;
2009 struct got_reflist_entry *re;
2010 struct got_pathlist_entry *pe;
2011 char *remote_namespace = NULL;
2012 char *local_refname = NULL;
2014 TAILQ_INIT(&my_refs);
2016 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2017 == -1)
2018 return got_error_from_errno("asprintf");
2020 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2021 if (err)
2022 goto done;
2024 TAILQ_FOREACH(re, &my_refs, entry) {
2025 const char *refname = got_ref_get_name(re->ref);
2026 const char *their_refname;
2028 if (remote->mirror_references) {
2029 their_refname = refname;
2030 } else {
2031 if (strncmp(refname, remote_namespace,
2032 strlen(remote_namespace)) == 0) {
2033 if (strcmp(refname + strlen(remote_namespace),
2034 GOT_REF_HEAD) == 0)
2035 continue;
2036 if (asprintf(&local_refname, "refs/heads/%s",
2037 refname + strlen(remote_namespace)) == -1) {
2038 err = got_error_from_errno("asprintf");
2039 goto done;
2041 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2042 continue;
2044 their_refname = local_refname;
2047 TAILQ_FOREACH(pe, their_refs, entry) {
2048 if (strcmp(their_refname, pe->path) == 0)
2049 break;
2051 if (pe != NULL)
2052 continue;
2054 TAILQ_FOREACH(pe, their_symrefs, entry) {
2055 if (strcmp(their_refname, pe->path) == 0)
2056 break;
2058 if (pe != NULL)
2059 continue;
2061 err = delete_missing_ref(re->ref, verbosity, repo);
2062 if (err)
2063 break;
2065 if (local_refname) {
2066 struct got_reference *ref;
2067 err = got_ref_open(&ref, repo, local_refname, 1);
2068 if (err) {
2069 if (err->code != GOT_ERR_NOT_REF)
2070 break;
2071 free(local_refname);
2072 local_refname = NULL;
2073 continue;
2075 err = delete_missing_ref(ref, verbosity, repo);
2076 if (err)
2077 break;
2078 unlock_err = got_ref_unlock(ref);
2079 got_ref_close(ref);
2080 if (unlock_err && err == NULL) {
2081 err = unlock_err;
2082 break;
2085 free(local_refname);
2086 local_refname = NULL;
2089 done:
2090 free(remote_namespace);
2091 free(local_refname);
2092 return err;
2095 static const struct got_error *
2096 update_wanted_ref(const char *refname, struct got_object_id *id,
2097 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2099 const struct got_error *err, *unlock_err;
2100 char *remote_refname;
2101 struct got_reference *ref;
2103 if (strncmp("refs/", refname, 5) == 0)
2104 refname += 5;
2106 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2107 remote_repo_name, refname) == -1)
2108 return got_error_from_errno("asprintf");
2110 err = got_ref_open(&ref, repo, remote_refname, 1);
2111 if (err) {
2112 if (err->code != GOT_ERR_NOT_REF)
2113 goto done;
2114 err = create_ref(remote_refname, id, verbosity, repo);
2115 } else {
2116 err = update_ref(ref, id, 0, verbosity, repo);
2117 unlock_err = got_ref_unlock(ref);
2118 if (unlock_err && err == NULL)
2119 err = unlock_err;
2120 got_ref_close(ref);
2122 done:
2123 free(remote_refname);
2124 return err;
2127 static const struct got_error *
2128 delete_ref(struct got_repository *repo, struct got_reference *ref)
2130 const struct got_error *err = NULL;
2131 struct got_object_id *id = NULL;
2132 char *id_str = NULL;
2133 const char *target;
2135 if (got_ref_is_symbolic(ref)) {
2136 target = got_ref_get_symref_target(ref);
2137 } else {
2138 err = got_ref_resolve(&id, repo, ref);
2139 if (err)
2140 goto done;
2141 err = got_object_id_str(&id_str, id);
2142 if (err)
2143 goto done;
2144 target = id_str;
2147 err = got_ref_delete(ref, repo);
2148 if (err)
2149 goto done;
2151 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2152 done:
2153 free(id);
2154 free(id_str);
2155 return err;
2158 static const struct got_error *
2159 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2161 const struct got_error *err = NULL;
2162 struct got_reflist_head refs;
2163 struct got_reflist_entry *re;
2164 char *prefix;
2166 TAILQ_INIT(&refs);
2168 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2169 err = got_error_from_errno("asprintf");
2170 goto done;
2172 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2173 if (err)
2174 goto done;
2176 TAILQ_FOREACH(re, &refs, entry)
2177 delete_ref(repo, re->ref);
2178 done:
2179 got_ref_list_free(&refs);
2180 return err;
2183 static const struct got_error *
2184 cmd_fetch(int argc, char *argv[])
2186 const struct got_error *error = NULL, *unlock_err;
2187 char *cwd = NULL, *repo_path = NULL;
2188 const char *remote_name;
2189 char *proto = NULL, *host = NULL, *port = NULL;
2190 char *repo_name = NULL, *server_path = NULL;
2191 const struct got_remote_repo *remotes, *remote = NULL;
2192 int nremotes;
2193 char *id_str = NULL;
2194 struct got_repository *repo = NULL;
2195 struct got_worktree *worktree = NULL;
2196 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2197 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2198 struct got_pathlist_entry *pe;
2199 struct got_object_id *pack_hash = NULL;
2200 int i, ch, fetchfd = -1, fetchstatus;
2201 pid_t fetchpid = -1;
2202 struct got_fetch_progress_arg fpa;
2203 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2204 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2206 TAILQ_INIT(&refs);
2207 TAILQ_INIT(&symrefs);
2208 TAILQ_INIT(&wanted_branches);
2209 TAILQ_INIT(&wanted_refs);
2211 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2212 switch (ch) {
2213 case 'a':
2214 fetch_all_branches = 1;
2215 break;
2216 case 'b':
2217 error = got_pathlist_append(&wanted_branches,
2218 optarg, NULL);
2219 if (error)
2220 return error;
2221 break;
2222 case 'd':
2223 delete_refs = 1;
2224 break;
2225 case 'l':
2226 list_refs_only = 1;
2227 break;
2228 case 'r':
2229 repo_path = realpath(optarg, NULL);
2230 if (repo_path == NULL)
2231 return got_error_from_errno2("realpath",
2232 optarg);
2233 got_path_strip_trailing_slashes(repo_path);
2234 break;
2235 case 't':
2236 replace_tags = 1;
2237 break;
2238 case 'v':
2239 if (verbosity < 0)
2240 verbosity = 0;
2241 else if (verbosity < 3)
2242 verbosity++;
2243 break;
2244 case 'q':
2245 verbosity = -1;
2246 break;
2247 case 'R':
2248 error = got_pathlist_append(&wanted_refs,
2249 optarg, NULL);
2250 if (error)
2251 return error;
2252 break;
2253 case 'X':
2254 delete_remote = 1;
2255 break;
2256 default:
2257 usage_fetch();
2258 break;
2261 argc -= optind;
2262 argv += optind;
2264 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2265 option_conflict('a', 'b');
2266 if (list_refs_only) {
2267 if (!TAILQ_EMPTY(&wanted_branches))
2268 option_conflict('l', 'b');
2269 if (fetch_all_branches)
2270 option_conflict('l', 'a');
2271 if (delete_refs)
2272 option_conflict('l', 'd');
2273 if (delete_remote)
2274 option_conflict('l', 'X');
2276 if (delete_remote) {
2277 if (fetch_all_branches)
2278 option_conflict('X', 'a');
2279 if (!TAILQ_EMPTY(&wanted_branches))
2280 option_conflict('X', 'b');
2281 if (delete_refs)
2282 option_conflict('X', 'd');
2283 if (replace_tags)
2284 option_conflict('X', 't');
2285 if (!TAILQ_EMPTY(&wanted_refs))
2286 option_conflict('X', 'R');
2289 if (argc == 0) {
2290 if (delete_remote)
2291 errx(1, "-X option requires a remote name");
2292 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2293 } else if (argc == 1)
2294 remote_name = argv[0];
2295 else
2296 usage_fetch();
2298 cwd = getcwd(NULL, 0);
2299 if (cwd == NULL) {
2300 error = got_error_from_errno("getcwd");
2301 goto done;
2304 if (repo_path == NULL) {
2305 error = got_worktree_open(&worktree, cwd);
2306 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2307 goto done;
2308 else
2309 error = NULL;
2310 if (worktree) {
2311 repo_path =
2312 strdup(got_worktree_get_repo_path(worktree));
2313 if (repo_path == NULL)
2314 error = got_error_from_errno("strdup");
2315 if (error)
2316 goto done;
2317 } else {
2318 repo_path = strdup(cwd);
2319 if (repo_path == NULL) {
2320 error = got_error_from_errno("strdup");
2321 goto done;
2326 error = got_repo_open(&repo, repo_path, NULL);
2327 if (error)
2328 goto done;
2330 if (delete_remote) {
2331 error = delete_refs_for_remote(repo, remote_name);
2332 goto done; /* nothing else to do */
2335 if (worktree) {
2336 worktree_conf = got_worktree_get_gotconfig(worktree);
2337 if (worktree_conf) {
2338 got_gotconfig_get_remotes(&nremotes, &remotes,
2339 worktree_conf);
2340 for (i = 0; i < nremotes; i++) {
2341 if (strcmp(remotes[i].name, remote_name) == 0) {
2342 remote = &remotes[i];
2343 break;
2348 if (remote == NULL) {
2349 repo_conf = got_repo_get_gotconfig(repo);
2350 if (repo_conf) {
2351 got_gotconfig_get_remotes(&nremotes, &remotes,
2352 repo_conf);
2353 for (i = 0; i < nremotes; i++) {
2354 if (strcmp(remotes[i].name, remote_name) == 0) {
2355 remote = &remotes[i];
2356 break;
2361 if (remote == NULL) {
2362 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2363 for (i = 0; i < nremotes; i++) {
2364 if (strcmp(remotes[i].name, remote_name) == 0) {
2365 remote = &remotes[i];
2366 break;
2370 if (remote == NULL) {
2371 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2372 goto done;
2375 if (TAILQ_EMPTY(&wanted_branches)) {
2376 if (!fetch_all_branches)
2377 fetch_all_branches = remote->fetch_all_branches;
2378 for (i = 0; i < remote->nfetch_branches; i++) {
2379 got_pathlist_append(&wanted_branches,
2380 remote->fetch_branches[i], NULL);
2383 if (TAILQ_EMPTY(&wanted_refs)) {
2384 for (i = 0; i < remote->nfetch_refs; i++) {
2385 got_pathlist_append(&wanted_refs,
2386 remote->fetch_refs[i], NULL);
2390 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2391 &repo_name, remote->fetch_url);
2392 if (error)
2393 goto done;
2395 if (strcmp(proto, "git") == 0) {
2396 #ifndef PROFILE
2397 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2398 "sendfd dns inet unveil", NULL) == -1)
2399 err(1, "pledge");
2400 #endif
2401 } else if (strcmp(proto, "git+ssh") == 0 ||
2402 strcmp(proto, "ssh") == 0) {
2403 #ifndef PROFILE
2404 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2405 "sendfd unveil", NULL) == -1)
2406 err(1, "pledge");
2407 #endif
2408 } else if (strcmp(proto, "http") == 0 ||
2409 strcmp(proto, "git+http") == 0) {
2410 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2411 goto done;
2412 } else {
2413 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2414 goto done;
2417 error = got_dial_apply_unveil(proto);
2418 if (error)
2419 goto done;
2421 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2422 if (error)
2423 goto done;
2425 if (verbosity >= 0)
2426 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2427 port ? ":" : "", port ? port : "");
2429 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2430 server_path, verbosity);
2431 if (error)
2432 goto done;
2434 fpa.last_scaled_size[0] = '\0';
2435 fpa.last_p_indexed = -1;
2436 fpa.last_p_resolved = -1;
2437 fpa.verbosity = verbosity;
2438 fpa.repo = repo;
2439 fpa.create_configs = 0;
2440 fpa.configs_created = 0;
2441 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2442 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2443 remote->mirror_references, fetch_all_branches, &wanted_branches,
2444 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2445 fetch_progress, &fpa);
2446 if (error)
2447 goto done;
2449 if (list_refs_only) {
2450 error = list_remote_refs(&symrefs, &refs);
2451 goto done;
2454 if (pack_hash == NULL) {
2455 if (verbosity >= 0)
2456 printf("Already up-to-date\n");
2457 } else if (verbosity >= 0) {
2458 error = got_object_id_str(&id_str, pack_hash);
2459 if (error)
2460 goto done;
2461 printf("\nFetched %s.pack\n", id_str);
2462 free(id_str);
2463 id_str = NULL;
2466 /* Update references provided with the pack file. */
2467 TAILQ_FOREACH(pe, &refs, entry) {
2468 const char *refname = pe->path;
2469 struct got_object_id *id = pe->data;
2470 struct got_reference *ref;
2471 char *remote_refname;
2473 if (is_wanted_ref(&wanted_refs, refname) &&
2474 !remote->mirror_references) {
2475 error = update_wanted_ref(refname, id,
2476 remote->name, verbosity, repo);
2477 if (error)
2478 goto done;
2479 continue;
2482 if (remote->mirror_references ||
2483 strncmp("refs/tags/", refname, 10) == 0) {
2484 error = got_ref_open(&ref, repo, refname, 1);
2485 if (error) {
2486 if (error->code != GOT_ERR_NOT_REF)
2487 goto done;
2488 error = create_ref(refname, id, verbosity,
2489 repo);
2490 if (error)
2491 goto done;
2492 } else {
2493 error = update_ref(ref, id, replace_tags,
2494 verbosity, repo);
2495 unlock_err = got_ref_unlock(ref);
2496 if (unlock_err && error == NULL)
2497 error = unlock_err;
2498 got_ref_close(ref);
2499 if (error)
2500 goto done;
2502 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2503 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2504 remote_name, refname + 11) == -1) {
2505 error = got_error_from_errno("asprintf");
2506 goto done;
2509 error = got_ref_open(&ref, repo, remote_refname, 1);
2510 if (error) {
2511 if (error->code != GOT_ERR_NOT_REF)
2512 goto done;
2513 error = create_ref(remote_refname, id,
2514 verbosity, repo);
2515 if (error)
2516 goto done;
2517 } else {
2518 error = update_ref(ref, id, replace_tags,
2519 verbosity, repo);
2520 unlock_err = got_ref_unlock(ref);
2521 if (unlock_err && error == NULL)
2522 error = unlock_err;
2523 got_ref_close(ref);
2524 if (error)
2525 goto done;
2528 /* Also create a local branch if none exists yet. */
2529 error = got_ref_open(&ref, repo, refname, 1);
2530 if (error) {
2531 if (error->code != GOT_ERR_NOT_REF)
2532 goto done;
2533 error = create_ref(refname, id, verbosity,
2534 repo);
2535 if (error)
2536 goto done;
2537 } else {
2538 unlock_err = got_ref_unlock(ref);
2539 if (unlock_err && error == NULL)
2540 error = unlock_err;
2541 got_ref_close(ref);
2545 if (delete_refs) {
2546 error = delete_missing_refs(&refs, &symrefs, remote,
2547 verbosity, repo);
2548 if (error)
2549 goto done;
2552 if (!remote->mirror_references) {
2553 /* Update remote HEAD reference if the server provided one. */
2554 TAILQ_FOREACH(pe, &symrefs, entry) {
2555 struct got_reference *target_ref;
2556 const char *refname = pe->path;
2557 const char *target = pe->data;
2558 char *remote_refname = NULL, *remote_target = NULL;
2560 if (strcmp(refname, GOT_REF_HEAD) != 0)
2561 continue;
2563 if (strncmp("refs/heads/", target, 11) != 0)
2564 continue;
2566 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2567 remote->name, refname) == -1) {
2568 error = got_error_from_errno("asprintf");
2569 goto done;
2571 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2572 remote->name, target + 11) == -1) {
2573 error = got_error_from_errno("asprintf");
2574 free(remote_refname);
2575 goto done;
2578 error = got_ref_open(&target_ref, repo, remote_target,
2579 0);
2580 if (error) {
2581 free(remote_refname);
2582 free(remote_target);
2583 if (error->code == GOT_ERR_NOT_REF) {
2584 error = NULL;
2585 continue;
2587 goto done;
2589 error = update_symref(remote_refname, target_ref,
2590 verbosity, repo);
2591 free(remote_refname);
2592 free(remote_target);
2593 got_ref_close(target_ref);
2594 if (error)
2595 goto done;
2598 done:
2599 if (fetchpid > 0) {
2600 if (kill(fetchpid, SIGTERM) == -1)
2601 error = got_error_from_errno("kill");
2602 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2603 error = got_error_from_errno("waitpid");
2605 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2606 error = got_error_from_errno("close");
2607 if (repo) {
2608 const struct got_error *close_err = got_repo_close(repo);
2609 if (error == NULL)
2610 error = close_err;
2612 if (worktree)
2613 got_worktree_close(worktree);
2614 TAILQ_FOREACH(pe, &refs, entry) {
2615 free((void *)pe->path);
2616 free(pe->data);
2618 got_pathlist_free(&refs);
2619 TAILQ_FOREACH(pe, &symrefs, entry) {
2620 free((void *)pe->path);
2621 free(pe->data);
2623 got_pathlist_free(&symrefs);
2624 got_pathlist_free(&wanted_branches);
2625 got_pathlist_free(&wanted_refs);
2626 free(id_str);
2627 free(cwd);
2628 free(repo_path);
2629 free(pack_hash);
2630 free(proto);
2631 free(host);
2632 free(port);
2633 free(server_path);
2634 free(repo_name);
2635 return error;
2639 __dead static void
2640 usage_checkout(void)
2642 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2643 "[-p prefix] [-q] repository-path [worktree-path]\n",
2644 getprogname());
2645 exit(1);
2648 static void
2649 show_worktree_base_ref_warning(void)
2651 fprintf(stderr, "%s: warning: could not create a reference "
2652 "to the work tree's base commit; the commit could be "
2653 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2654 "repository writable and running 'got update' will prevent this\n",
2655 getprogname());
2658 struct got_checkout_progress_arg {
2659 const char *worktree_path;
2660 int had_base_commit_ref_error;
2661 int verbosity;
2664 static const struct got_error *
2665 checkout_progress(void *arg, unsigned char status, const char *path)
2667 struct got_checkout_progress_arg *a = arg;
2669 /* Base commit bump happens silently. */
2670 if (status == GOT_STATUS_BUMP_BASE)
2671 return NULL;
2673 if (status == GOT_STATUS_BASE_REF_ERR) {
2674 a->had_base_commit_ref_error = 1;
2675 return NULL;
2678 while (path[0] == '/')
2679 path++;
2681 if (a->verbosity >= 0)
2682 printf("%c %s/%s\n", status, a->worktree_path, path);
2684 return NULL;
2687 static const struct got_error *
2688 check_cancelled(void *arg)
2690 if (sigint_received || sigpipe_received)
2691 return got_error(GOT_ERR_CANCELLED);
2692 return NULL;
2695 static const struct got_error *
2696 check_linear_ancestry(struct got_object_id *commit_id,
2697 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2698 struct got_repository *repo)
2700 const struct got_error *err = NULL;
2701 struct got_object_id *yca_id;
2703 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2704 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2705 if (err)
2706 return err;
2708 if (yca_id == NULL)
2709 return got_error(GOT_ERR_ANCESTRY);
2712 * Require a straight line of history between the target commit
2713 * and the work tree's base commit.
2715 * Non-linear situations such as this require a rebase:
2717 * (commit) D F (base_commit)
2718 * \ /
2719 * C E
2720 * \ /
2721 * B (yca)
2722 * |
2723 * A
2725 * 'got update' only handles linear cases:
2726 * Update forwards in time: A (base/yca) - B - C - D (commit)
2727 * Update backwards in time: D (base) - C - B - A (commit/yca)
2729 if (allow_forwards_in_time_only) {
2730 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2731 return got_error(GOT_ERR_ANCESTRY);
2732 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2733 got_object_id_cmp(base_commit_id, yca_id) != 0)
2734 return got_error(GOT_ERR_ANCESTRY);
2736 free(yca_id);
2737 return NULL;
2740 static const struct got_error *
2741 check_same_branch(struct got_object_id *commit_id,
2742 struct got_reference *head_ref, struct got_object_id *yca_id,
2743 struct got_repository *repo)
2745 const struct got_error *err = NULL;
2746 struct got_commit_graph *graph = NULL;
2747 struct got_object_id *head_commit_id = NULL;
2748 int is_same_branch = 0;
2750 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2751 if (err)
2752 goto done;
2754 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2755 is_same_branch = 1;
2756 goto done;
2758 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2759 is_same_branch = 1;
2760 goto done;
2763 err = got_commit_graph_open(&graph, "/", 1);
2764 if (err)
2765 goto done;
2767 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2768 check_cancelled, NULL);
2769 if (err)
2770 goto done;
2772 for (;;) {
2773 struct got_object_id *id;
2774 err = got_commit_graph_iter_next(&id, graph, repo,
2775 check_cancelled, NULL);
2776 if (err) {
2777 if (err->code == GOT_ERR_ITER_COMPLETED)
2778 err = NULL;
2779 break;
2782 if (id) {
2783 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2784 break;
2785 if (got_object_id_cmp(id, commit_id) == 0) {
2786 is_same_branch = 1;
2787 break;
2791 done:
2792 if (graph)
2793 got_commit_graph_close(graph);
2794 free(head_commit_id);
2795 if (!err && !is_same_branch)
2796 err = got_error(GOT_ERR_ANCESTRY);
2797 return err;
2800 static const struct got_error *
2801 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2803 static char msg[512];
2804 const char *branch_name;
2806 if (got_ref_is_symbolic(ref))
2807 branch_name = got_ref_get_symref_target(ref);
2808 else
2809 branch_name = got_ref_get_name(ref);
2811 if (strncmp("refs/heads/", branch_name, 11) == 0)
2812 branch_name += 11;
2814 snprintf(msg, sizeof(msg),
2815 "target commit is not contained in branch '%s'; "
2816 "the branch to use must be specified with -b; "
2817 "if necessary a new branch can be created for "
2818 "this commit with 'got branch -c %s BRANCH_NAME'",
2819 branch_name, commit_id_str);
2821 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2824 static const struct got_error *
2825 cmd_checkout(int argc, char *argv[])
2827 const struct got_error *error = NULL;
2828 struct got_repository *repo = NULL;
2829 struct got_reference *head_ref = NULL, *ref = NULL;
2830 struct got_worktree *worktree = NULL;
2831 char *repo_path = NULL;
2832 char *worktree_path = NULL;
2833 const char *path_prefix = "";
2834 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2835 char *commit_id_str = NULL;
2836 struct got_object_id *commit_id = NULL;
2837 char *cwd = NULL;
2838 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2839 struct got_pathlist_head paths;
2840 struct got_checkout_progress_arg cpa;
2842 TAILQ_INIT(&paths);
2844 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2845 switch (ch) {
2846 case 'b':
2847 branch_name = optarg;
2848 break;
2849 case 'c':
2850 commit_id_str = strdup(optarg);
2851 if (commit_id_str == NULL)
2852 return got_error_from_errno("strdup");
2853 break;
2854 case 'E':
2855 allow_nonempty = 1;
2856 break;
2857 case 'p':
2858 path_prefix = optarg;
2859 break;
2860 case 'q':
2861 verbosity = -1;
2862 break;
2863 default:
2864 usage_checkout();
2865 /* NOTREACHED */
2869 argc -= optind;
2870 argv += optind;
2872 #ifndef PROFILE
2873 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2874 "unveil", NULL) == -1)
2875 err(1, "pledge");
2876 #endif
2877 if (argc == 1) {
2878 char *base, *dotgit;
2879 const char *path;
2880 repo_path = realpath(argv[0], NULL);
2881 if (repo_path == NULL)
2882 return got_error_from_errno2("realpath", argv[0]);
2883 cwd = getcwd(NULL, 0);
2884 if (cwd == NULL) {
2885 error = got_error_from_errno("getcwd");
2886 goto done;
2888 if (path_prefix[0])
2889 path = path_prefix;
2890 else
2891 path = repo_path;
2892 error = got_path_basename(&base, path);
2893 if (error)
2894 goto done;
2895 dotgit = strstr(base, ".git");
2896 if (dotgit)
2897 *dotgit = '\0';
2898 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2899 error = got_error_from_errno("asprintf");
2900 free(base);
2901 goto done;
2903 free(base);
2904 } else if (argc == 2) {
2905 repo_path = realpath(argv[0], NULL);
2906 if (repo_path == NULL) {
2907 error = got_error_from_errno2("realpath", argv[0]);
2908 goto done;
2910 worktree_path = realpath(argv[1], NULL);
2911 if (worktree_path == NULL) {
2912 if (errno != ENOENT) {
2913 error = got_error_from_errno2("realpath",
2914 argv[1]);
2915 goto done;
2917 worktree_path = strdup(argv[1]);
2918 if (worktree_path == NULL) {
2919 error = got_error_from_errno("strdup");
2920 goto done;
2923 } else
2924 usage_checkout();
2926 got_path_strip_trailing_slashes(repo_path);
2927 got_path_strip_trailing_slashes(worktree_path);
2929 error = got_repo_open(&repo, repo_path, NULL);
2930 if (error != NULL)
2931 goto done;
2933 /* Pre-create work tree path for unveil(2) */
2934 error = got_path_mkdir(worktree_path);
2935 if (error) {
2936 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2937 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2938 goto done;
2939 if (!allow_nonempty &&
2940 !got_path_dir_is_empty(worktree_path)) {
2941 error = got_error_path(worktree_path,
2942 GOT_ERR_DIR_NOT_EMPTY);
2943 goto done;
2947 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2948 if (error)
2949 goto done;
2951 error = got_ref_open(&head_ref, repo, branch_name, 0);
2952 if (error != NULL)
2953 goto done;
2955 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2956 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2957 goto done;
2959 error = got_worktree_open(&worktree, worktree_path);
2960 if (error != NULL)
2961 goto done;
2963 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2964 path_prefix);
2965 if (error != NULL)
2966 goto done;
2967 if (!same_path_prefix) {
2968 error = got_error(GOT_ERR_PATH_PREFIX);
2969 goto done;
2972 if (commit_id_str) {
2973 struct got_reflist_head refs;
2974 TAILQ_INIT(&refs);
2975 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2976 NULL);
2977 if (error)
2978 goto done;
2979 error = got_repo_match_object_id(&commit_id, NULL,
2980 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2981 got_ref_list_free(&refs);
2982 if (error)
2983 goto done;
2984 error = check_linear_ancestry(commit_id,
2985 got_worktree_get_base_commit_id(worktree), 0, repo);
2986 if (error != NULL) {
2987 free(commit_id);
2988 if (error->code == GOT_ERR_ANCESTRY) {
2989 error = checkout_ancestry_error(
2990 head_ref, commit_id_str);
2992 goto done;
2994 error = check_same_branch(commit_id, head_ref, NULL, repo);
2995 if (error) {
2996 if (error->code == GOT_ERR_ANCESTRY) {
2997 error = checkout_ancestry_error(
2998 head_ref, commit_id_str);
3000 goto done;
3002 error = got_worktree_set_base_commit_id(worktree, repo,
3003 commit_id);
3004 if (error)
3005 goto done;
3006 /* Expand potentially abbreviated commit ID string. */
3007 free(commit_id_str);
3008 error = got_object_id_str(&commit_id_str, commit_id);
3009 if (error)
3010 goto done;
3011 } else {
3012 commit_id = got_object_id_dup(
3013 got_worktree_get_base_commit_id(worktree));
3014 if (commit_id == NULL) {
3015 error = got_error_from_errno("got_object_id_dup");
3016 goto done;
3018 error = got_object_id_str(&commit_id_str, commit_id);
3019 if (error)
3020 goto done;
3023 error = got_pathlist_append(&paths, "", NULL);
3024 if (error)
3025 goto done;
3026 cpa.worktree_path = worktree_path;
3027 cpa.had_base_commit_ref_error = 0;
3028 cpa.verbosity = verbosity;
3029 error = got_worktree_checkout_files(worktree, &paths, repo,
3030 checkout_progress, &cpa, check_cancelled, NULL);
3031 if (error != NULL)
3032 goto done;
3034 if (got_ref_is_symbolic(head_ref)) {
3035 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3036 if (error)
3037 goto done;
3038 refname = got_ref_get_name(ref);
3039 } else
3040 refname = got_ref_get_name(head_ref);
3041 printf("Checked out %s: %s\n", refname, commit_id_str);
3042 printf("Now shut up and hack\n");
3043 if (cpa.had_base_commit_ref_error)
3044 show_worktree_base_ref_warning();
3045 done:
3046 if (head_ref)
3047 got_ref_close(head_ref);
3048 if (ref)
3049 got_ref_close(ref);
3050 got_pathlist_free(&paths);
3051 free(commit_id_str);
3052 free(commit_id);
3053 free(repo_path);
3054 free(worktree_path);
3055 free(cwd);
3056 return error;
3059 struct got_update_progress_arg {
3060 int did_something;
3061 int conflicts;
3062 int obstructed;
3063 int not_updated;
3064 int missing;
3065 int not_deleted;
3066 int unversioned;
3067 int verbosity;
3070 void
3071 print_update_progress_stats(struct got_update_progress_arg *upa)
3073 if (!upa->did_something)
3074 return;
3076 if (upa->conflicts > 0)
3077 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3078 if (upa->obstructed > 0)
3079 printf("File paths obstructed by a non-regular file: %d\n",
3080 upa->obstructed);
3081 if (upa->not_updated > 0)
3082 printf("Files not updated because of existing merge "
3083 "conflicts: %d\n", upa->not_updated);
3087 * The meaning of some status codes differs between merge-style operations and
3088 * update operations. For example, the ! status code means "file was missing"
3089 * if changes were merged into the work tree, and "missing file was restored"
3090 * if the work tree was updated. This function should be used by any operation
3091 * which merges changes into the work tree without updating the work tree.
3093 void
3094 print_merge_progress_stats(struct got_update_progress_arg *upa)
3096 if (!upa->did_something)
3097 return;
3099 if (upa->conflicts > 0)
3100 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3101 if (upa->obstructed > 0)
3102 printf("File paths obstructed by a non-regular file: %d\n",
3103 upa->obstructed);
3104 if (upa->missing > 0)
3105 printf("Files which had incoming changes but could not be "
3106 "found in the work tree: %d\n", upa->missing);
3107 if (upa->not_deleted > 0)
3108 printf("Files not deleted due to differences in deleted "
3109 "content: %d\n", upa->not_deleted);
3110 if (upa->unversioned > 0)
3111 printf("Files not merged because an unversioned file was "
3112 "found in the work tree: %d\n", upa->unversioned);
3115 __dead static void
3116 usage_update(void)
3118 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3119 "[path ...]\n",
3120 getprogname());
3121 exit(1);
3124 static const struct got_error *
3125 update_progress(void *arg, unsigned char status, const char *path)
3127 struct got_update_progress_arg *upa = arg;
3129 if (status == GOT_STATUS_EXISTS ||
3130 status == GOT_STATUS_BASE_REF_ERR)
3131 return NULL;
3133 upa->did_something = 1;
3135 /* Base commit bump happens silently. */
3136 if (status == GOT_STATUS_BUMP_BASE)
3137 return NULL;
3139 if (status == GOT_STATUS_CONFLICT)
3140 upa->conflicts++;
3141 if (status == GOT_STATUS_OBSTRUCTED)
3142 upa->obstructed++;
3143 if (status == GOT_STATUS_CANNOT_UPDATE)
3144 upa->not_updated++;
3145 if (status == GOT_STATUS_MISSING)
3146 upa->missing++;
3147 if (status == GOT_STATUS_CANNOT_DELETE)
3148 upa->not_deleted++;
3149 if (status == GOT_STATUS_UNVERSIONED)
3150 upa->unversioned++;
3152 while (path[0] == '/')
3153 path++;
3154 if (upa->verbosity >= 0)
3155 printf("%c %s\n", status, path);
3157 return NULL;
3160 static const struct got_error *
3161 switch_head_ref(struct got_reference *head_ref,
3162 struct got_object_id *commit_id, struct got_worktree *worktree,
3163 struct got_repository *repo)
3165 const struct got_error *err = NULL;
3166 char *base_id_str;
3167 int ref_has_moved = 0;
3169 /* Trivial case: switching between two different references. */
3170 if (strcmp(got_ref_get_name(head_ref),
3171 got_worktree_get_head_ref_name(worktree)) != 0) {
3172 printf("Switching work tree from %s to %s\n",
3173 got_worktree_get_head_ref_name(worktree),
3174 got_ref_get_name(head_ref));
3175 return got_worktree_set_head_ref(worktree, head_ref);
3178 err = check_linear_ancestry(commit_id,
3179 got_worktree_get_base_commit_id(worktree), 0, repo);
3180 if (err) {
3181 if (err->code != GOT_ERR_ANCESTRY)
3182 return err;
3183 ref_has_moved = 1;
3185 if (!ref_has_moved)
3186 return NULL;
3188 /* Switching to a rebased branch with the same reference name. */
3189 err = got_object_id_str(&base_id_str,
3190 got_worktree_get_base_commit_id(worktree));
3191 if (err)
3192 return err;
3193 printf("Reference %s now points at a different branch\n",
3194 got_worktree_get_head_ref_name(worktree));
3195 printf("Switching work tree from %s to %s\n", base_id_str,
3196 got_worktree_get_head_ref_name(worktree));
3197 return NULL;
3200 static const struct got_error *
3201 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3203 const struct got_error *err;
3204 int in_progress;
3206 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3207 if (err)
3208 return err;
3209 if (in_progress)
3210 return got_error(GOT_ERR_REBASING);
3212 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3213 if (err)
3214 return err;
3215 if (in_progress)
3216 return got_error(GOT_ERR_HISTEDIT_BUSY);
3218 return NULL;
3221 static const struct got_error *
3222 check_merge_in_progress(struct got_worktree *worktree,
3223 struct got_repository *repo)
3225 const struct got_error *err;
3226 int in_progress;
3228 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3229 if (err)
3230 return err;
3231 if (in_progress)
3232 return got_error(GOT_ERR_MERGE_BUSY);
3234 return NULL;
3237 static const struct got_error *
3238 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3239 char *argv[], struct got_worktree *worktree)
3241 const struct got_error *err = NULL;
3242 char *path;
3243 struct got_pathlist_entry *new;
3244 int i;
3246 if (argc == 0) {
3247 path = strdup("");
3248 if (path == NULL)
3249 return got_error_from_errno("strdup");
3250 return got_pathlist_append(paths, path, NULL);
3253 for (i = 0; i < argc; i++) {
3254 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3255 if (err)
3256 break;
3257 err = got_pathlist_insert(&new, paths, path, NULL);
3258 if (err || new == NULL /* duplicate */) {
3259 free(path);
3260 if (err)
3261 break;
3265 return err;
3268 static const struct got_error *
3269 wrap_not_worktree_error(const struct got_error *orig_err,
3270 const char *cmdname, const char *path)
3272 const struct got_error *err;
3273 struct got_repository *repo;
3274 static char msg[512];
3276 err = got_repo_open(&repo, path, NULL);
3277 if (err)
3278 return orig_err;
3280 snprintf(msg, sizeof(msg),
3281 "'got %s' needs a work tree in addition to a git repository\n"
3282 "Work trees can be checked out from this Git repository with "
3283 "'got checkout'.\n"
3284 "The got(1) manual page contains more information.", cmdname);
3285 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3286 got_repo_close(repo);
3287 return err;
3290 static const struct got_error *
3291 cmd_update(int argc, char *argv[])
3293 const struct got_error *error = NULL;
3294 struct got_repository *repo = NULL;
3295 struct got_worktree *worktree = NULL;
3296 char *worktree_path = NULL;
3297 struct got_object_id *commit_id = NULL;
3298 char *commit_id_str = NULL;
3299 const char *branch_name = NULL;
3300 struct got_reference *head_ref = NULL;
3301 struct got_pathlist_head paths;
3302 struct got_pathlist_entry *pe;
3303 int ch, verbosity = 0;
3304 struct got_update_progress_arg upa;
3306 TAILQ_INIT(&paths);
3308 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3309 switch (ch) {
3310 case 'b':
3311 branch_name = optarg;
3312 break;
3313 case 'c':
3314 commit_id_str = strdup(optarg);
3315 if (commit_id_str == NULL)
3316 return got_error_from_errno("strdup");
3317 break;
3318 case 'q':
3319 verbosity = -1;
3320 break;
3321 default:
3322 usage_update();
3323 /* NOTREACHED */
3327 argc -= optind;
3328 argv += optind;
3330 #ifndef PROFILE
3331 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3332 "unveil", NULL) == -1)
3333 err(1, "pledge");
3334 #endif
3335 worktree_path = getcwd(NULL, 0);
3336 if (worktree_path == NULL) {
3337 error = got_error_from_errno("getcwd");
3338 goto done;
3340 error = got_worktree_open(&worktree, worktree_path);
3341 if (error) {
3342 if (error->code == GOT_ERR_NOT_WORKTREE)
3343 error = wrap_not_worktree_error(error, "update",
3344 worktree_path);
3345 goto done;
3348 error = check_rebase_or_histedit_in_progress(worktree);
3349 if (error)
3350 goto done;
3352 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3353 NULL);
3354 if (error != NULL)
3355 goto done;
3357 error = apply_unveil(got_repo_get_path(repo), 0,
3358 got_worktree_get_root_path(worktree));
3359 if (error)
3360 goto done;
3362 error = check_merge_in_progress(worktree, repo);
3363 if (error)
3364 goto done;
3366 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3367 if (error)
3368 goto done;
3370 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3371 got_worktree_get_head_ref_name(worktree), 0);
3372 if (error != NULL)
3373 goto done;
3374 if (commit_id_str == NULL) {
3375 error = got_ref_resolve(&commit_id, repo, head_ref);
3376 if (error != NULL)
3377 goto done;
3378 error = got_object_id_str(&commit_id_str, commit_id);
3379 if (error != NULL)
3380 goto done;
3381 } else {
3382 struct got_reflist_head refs;
3383 TAILQ_INIT(&refs);
3384 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3385 NULL);
3386 if (error)
3387 goto done;
3388 error = got_repo_match_object_id(&commit_id, NULL,
3389 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3390 got_ref_list_free(&refs);
3391 free(commit_id_str);
3392 commit_id_str = NULL;
3393 if (error)
3394 goto done;
3395 error = got_object_id_str(&commit_id_str, commit_id);
3396 if (error)
3397 goto done;
3400 if (branch_name) {
3401 struct got_object_id *head_commit_id;
3402 TAILQ_FOREACH(pe, &paths, entry) {
3403 if (pe->path_len == 0)
3404 continue;
3405 error = got_error_msg(GOT_ERR_BAD_PATH,
3406 "switching between branches requires that "
3407 "the entire work tree gets updated");
3408 goto done;
3410 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3411 if (error)
3412 goto done;
3413 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3414 repo);
3415 free(head_commit_id);
3416 if (error != NULL)
3417 goto done;
3418 error = check_same_branch(commit_id, head_ref, NULL, repo);
3419 if (error)
3420 goto done;
3421 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3422 if (error)
3423 goto done;
3424 } else {
3425 error = check_linear_ancestry(commit_id,
3426 got_worktree_get_base_commit_id(worktree), 0, repo);
3427 if (error != NULL) {
3428 if (error->code == GOT_ERR_ANCESTRY)
3429 error = got_error(GOT_ERR_BRANCH_MOVED);
3430 goto done;
3432 error = check_same_branch(commit_id, head_ref, NULL, repo);
3433 if (error)
3434 goto done;
3437 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3438 commit_id) != 0) {
3439 error = got_worktree_set_base_commit_id(worktree, repo,
3440 commit_id);
3441 if (error)
3442 goto done;
3445 memset(&upa, 0, sizeof(upa));
3446 upa.verbosity = verbosity;
3447 error = got_worktree_checkout_files(worktree, &paths, repo,
3448 update_progress, &upa, check_cancelled, NULL);
3449 if (error != NULL)
3450 goto done;
3452 if (upa.did_something) {
3453 printf("Updated to %s: %s\n",
3454 got_worktree_get_head_ref_name(worktree), commit_id_str);
3455 } else
3456 printf("Already up-to-date\n");
3457 print_update_progress_stats(&upa);
3458 done:
3459 free(worktree_path);
3460 TAILQ_FOREACH(pe, &paths, entry)
3461 free((char *)pe->path);
3462 got_pathlist_free(&paths);
3463 free(commit_id);
3464 free(commit_id_str);
3465 return error;
3468 static const struct got_error *
3469 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3470 const char *path, int diff_context, int ignore_whitespace,
3471 int force_text_diff, struct got_repository *repo)
3473 const struct got_error *err = NULL;
3474 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3476 if (blob_id1) {
3477 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3478 if (err)
3479 goto done;
3482 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3483 if (err)
3484 goto done;
3486 while (path[0] == '/')
3487 path++;
3488 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3489 diff_context, ignore_whitespace, force_text_diff, stdout);
3490 done:
3491 if (blob1)
3492 got_object_blob_close(blob1);
3493 got_object_blob_close(blob2);
3494 return err;
3497 static const struct got_error *
3498 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3499 const char *path, int diff_context, int ignore_whitespace,
3500 int force_text_diff, struct got_repository *repo)
3502 const struct got_error *err = NULL;
3503 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3504 struct got_diff_blob_output_unidiff_arg arg;
3506 if (tree_id1) {
3507 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3508 if (err)
3509 goto done;
3512 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3513 if (err)
3514 goto done;
3516 arg.diff_context = diff_context;
3517 arg.ignore_whitespace = ignore_whitespace;
3518 arg.force_text_diff = force_text_diff;
3519 arg.outfile = stdout;
3520 arg.line_offsets = NULL;
3521 arg.nlines = 0;
3522 while (path[0] == '/')
3523 path++;
3524 err = got_diff_tree(tree1, tree2, path, path, repo,
3525 got_diff_blob_output_unidiff, &arg, 1);
3526 done:
3527 if (tree1)
3528 got_object_tree_close(tree1);
3529 if (tree2)
3530 got_object_tree_close(tree2);
3531 return err;
3534 static const struct got_error *
3535 get_changed_paths(struct got_pathlist_head *paths,
3536 struct got_commit_object *commit, struct got_repository *repo)
3538 const struct got_error *err = NULL;
3539 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3540 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3541 struct got_object_qid *qid;
3543 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3544 if (qid != NULL) {
3545 struct got_commit_object *pcommit;
3546 err = got_object_open_as_commit(&pcommit, repo,
3547 qid->id);
3548 if (err)
3549 return err;
3551 tree_id1 = got_object_id_dup(
3552 got_object_commit_get_tree_id(pcommit));
3553 if (tree_id1 == NULL) {
3554 got_object_commit_close(pcommit);
3555 return got_error_from_errno("got_object_id_dup");
3557 got_object_commit_close(pcommit);
3561 if (tree_id1) {
3562 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3563 if (err)
3564 goto done;
3567 tree_id2 = got_object_commit_get_tree_id(commit);
3568 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3569 if (err)
3570 goto done;
3572 err = got_diff_tree(tree1, tree2, "", "", repo,
3573 got_diff_tree_collect_changed_paths, paths, 0);
3574 done:
3575 if (tree1)
3576 got_object_tree_close(tree1);
3577 if (tree2)
3578 got_object_tree_close(tree2);
3579 free(tree_id1);
3580 return err;
3583 static const struct got_error *
3584 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3585 const char *path, int diff_context, struct got_repository *repo)
3587 const struct got_error *err = NULL;
3588 struct got_commit_object *pcommit = NULL;
3589 char *id_str1 = NULL, *id_str2 = NULL;
3590 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3591 struct got_object_qid *qid;
3593 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3594 if (qid != NULL) {
3595 err = got_object_open_as_commit(&pcommit, repo,
3596 qid->id);
3597 if (err)
3598 return err;
3601 if (path && path[0] != '\0') {
3602 int obj_type;
3603 err = got_object_id_by_path(&obj_id2, repo, id, path);
3604 if (err)
3605 goto done;
3606 err = got_object_id_str(&id_str2, obj_id2);
3607 if (err) {
3608 free(obj_id2);
3609 goto done;
3611 if (pcommit) {
3612 err = got_object_id_by_path(&obj_id1, repo,
3613 qid->id, path);
3614 if (err) {
3615 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3616 free(obj_id2);
3617 goto done;
3619 } else {
3620 err = got_object_id_str(&id_str1, obj_id1);
3621 if (err) {
3622 free(obj_id2);
3623 goto done;
3627 err = got_object_get_type(&obj_type, repo, obj_id2);
3628 if (err) {
3629 free(obj_id2);
3630 goto done;
3632 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3633 switch (obj_type) {
3634 case GOT_OBJ_TYPE_BLOB:
3635 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3636 0, 0, repo);
3637 break;
3638 case GOT_OBJ_TYPE_TREE:
3639 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3640 0, 0, repo);
3641 break;
3642 default:
3643 err = got_error(GOT_ERR_OBJ_TYPE);
3644 break;
3646 free(obj_id1);
3647 free(obj_id2);
3648 } else {
3649 obj_id2 = got_object_commit_get_tree_id(commit);
3650 err = got_object_id_str(&id_str2, obj_id2);
3651 if (err)
3652 goto done;
3653 if (pcommit) {
3654 obj_id1 = got_object_commit_get_tree_id(pcommit);
3655 err = got_object_id_str(&id_str1, obj_id1);
3656 if (err)
3657 goto done;
3659 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3660 id_str2);
3661 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3662 repo);
3664 done:
3665 free(id_str1);
3666 free(id_str2);
3667 if (pcommit)
3668 got_object_commit_close(pcommit);
3669 return err;
3672 static char *
3673 get_datestr(time_t *time, char *datebuf)
3675 struct tm mytm, *tm;
3676 char *p, *s;
3678 tm = gmtime_r(time, &mytm);
3679 if (tm == NULL)
3680 return NULL;
3681 s = asctime_r(tm, datebuf);
3682 if (s == NULL)
3683 return NULL;
3684 p = strchr(s, '\n');
3685 if (p)
3686 *p = '\0';
3687 return s;
3690 static const struct got_error *
3691 match_logmsg(int *have_match, struct got_object_id *id,
3692 struct got_commit_object *commit, regex_t *regex)
3694 const struct got_error *err = NULL;
3695 regmatch_t regmatch;
3696 char *id_str = NULL, *logmsg = NULL;
3698 *have_match = 0;
3700 err = got_object_id_str(&id_str, id);
3701 if (err)
3702 return err;
3704 err = got_object_commit_get_logmsg(&logmsg, commit);
3705 if (err)
3706 goto done;
3708 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3709 *have_match = 1;
3710 done:
3711 free(id_str);
3712 free(logmsg);
3713 return err;
3716 static void
3717 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3718 regex_t *regex)
3720 regmatch_t regmatch;
3721 struct got_pathlist_entry *pe;
3723 *have_match = 0;
3725 TAILQ_FOREACH(pe, changed_paths, entry) {
3726 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3727 *have_match = 1;
3728 break;
3733 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3735 static const struct got_error*
3736 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3737 struct got_object_id *id, struct got_repository *repo)
3739 static const struct got_error *err = NULL;
3740 struct got_reflist_entry *re;
3741 char *s;
3742 const char *name;
3744 *refs_str = NULL;
3746 TAILQ_FOREACH(re, refs, entry) {
3747 struct got_tag_object *tag = NULL;
3748 struct got_object_id *ref_id;
3749 int cmp;
3751 name = got_ref_get_name(re->ref);
3752 if (strcmp(name, GOT_REF_HEAD) == 0)
3753 continue;
3754 if (strncmp(name, "refs/", 5) == 0)
3755 name += 5;
3756 if (strncmp(name, "got/", 4) == 0)
3757 continue;
3758 if (strncmp(name, "heads/", 6) == 0)
3759 name += 6;
3760 if (strncmp(name, "remotes/", 8) == 0) {
3761 name += 8;
3762 s = strstr(name, "/" GOT_REF_HEAD);
3763 if (s != NULL && s[strlen(s)] == '\0')
3764 continue;
3766 err = got_ref_resolve(&ref_id, repo, re->ref);
3767 if (err)
3768 break;
3769 if (strncmp(name, "tags/", 5) == 0) {
3770 err = got_object_open_as_tag(&tag, repo, ref_id);
3771 if (err) {
3772 if (err->code != GOT_ERR_OBJ_TYPE) {
3773 free(ref_id);
3774 break;
3776 /* Ref points at something other than a tag. */
3777 err = NULL;
3778 tag = NULL;
3781 cmp = got_object_id_cmp(tag ?
3782 got_object_tag_get_object_id(tag) : ref_id, id);
3783 free(ref_id);
3784 if (tag)
3785 got_object_tag_close(tag);
3786 if (cmp != 0)
3787 continue;
3788 s = *refs_str;
3789 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3790 s ? ", " : "", name) == -1) {
3791 err = got_error_from_errno("asprintf");
3792 free(s);
3793 *refs_str = NULL;
3794 break;
3796 free(s);
3799 return err;
3802 static const struct got_error *
3803 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3804 struct got_repository *repo, const char *path,
3805 struct got_pathlist_head *changed_paths, int show_patch,
3806 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3807 const char *custom_refs_str)
3809 const struct got_error *err = NULL;
3810 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3811 char datebuf[26];
3812 time_t committer_time;
3813 const char *author, *committer;
3814 char *refs_str = NULL;
3816 err = got_object_id_str(&id_str, id);
3817 if (err)
3818 return err;
3820 if (custom_refs_str == NULL) {
3821 struct got_reflist_head *refs;
3822 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3823 if (refs) {
3824 err = build_refs_str(&refs_str, refs, id, repo);
3825 if (err)
3826 goto done;
3830 printf(GOT_COMMIT_SEP_STR);
3831 if (custom_refs_str)
3832 printf("commit %s (%s)\n", id_str, custom_refs_str);
3833 else
3834 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3835 refs_str ? refs_str : "", refs_str ? ")" : "");
3836 free(id_str);
3837 id_str = NULL;
3838 free(refs_str);
3839 refs_str = NULL;
3840 printf("from: %s\n", got_object_commit_get_author(commit));
3841 committer_time = got_object_commit_get_committer_time(commit);
3842 datestr = get_datestr(&committer_time, datebuf);
3843 if (datestr)
3844 printf("date: %s UTC\n", datestr);
3845 author = got_object_commit_get_author(commit);
3846 committer = got_object_commit_get_committer(commit);
3847 if (strcmp(author, committer) != 0)
3848 printf("via: %s\n", committer);
3849 if (got_object_commit_get_nparents(commit) > 1) {
3850 const struct got_object_id_queue *parent_ids;
3851 struct got_object_qid *qid;
3852 int n = 1;
3853 parent_ids = got_object_commit_get_parent_ids(commit);
3854 STAILQ_FOREACH(qid, parent_ids, entry) {
3855 err = got_object_id_str(&id_str, qid->id);
3856 if (err)
3857 goto done;
3858 printf("parent %d: %s\n", n++, id_str);
3859 free(id_str);
3860 id_str = NULL;
3864 err = got_object_commit_get_logmsg(&logmsg0, commit);
3865 if (err)
3866 goto done;
3868 logmsg = logmsg0;
3869 do {
3870 line = strsep(&logmsg, "\n");
3871 if (line)
3872 printf(" %s\n", line);
3873 } while (line);
3874 free(logmsg0);
3876 if (changed_paths) {
3877 struct got_pathlist_entry *pe;
3878 TAILQ_FOREACH(pe, changed_paths, entry) {
3879 struct got_diff_changed_path *cp = pe->data;
3880 printf(" %c %s\n", cp->status, pe->path);
3882 printf("\n");
3884 if (show_patch) {
3885 err = print_patch(commit, id, path, diff_context, repo);
3886 if (err == 0)
3887 printf("\n");
3890 if (fflush(stdout) != 0 && err == NULL)
3891 err = got_error_from_errno("fflush");
3892 done:
3893 free(id_str);
3894 free(refs_str);
3895 return err;
3898 static const struct got_error *
3899 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3900 struct got_repository *repo, const char *path, int show_changed_paths,
3901 int show_patch, const char *search_pattern, int diff_context, int limit,
3902 int log_branches, int reverse_display_order,
3903 struct got_reflist_object_id_map *refs_idmap)
3905 const struct got_error *err;
3906 struct got_commit_graph *graph;
3907 regex_t regex;
3908 int have_match;
3909 struct got_object_id_queue reversed_commits;
3910 struct got_object_qid *qid;
3911 struct got_commit_object *commit;
3912 struct got_pathlist_head changed_paths;
3913 struct got_pathlist_entry *pe;
3915 STAILQ_INIT(&reversed_commits);
3916 TAILQ_INIT(&changed_paths);
3918 if (search_pattern && regcomp(&regex, search_pattern,
3919 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3920 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3922 err = got_commit_graph_open(&graph, path, !log_branches);
3923 if (err)
3924 return err;
3925 err = got_commit_graph_iter_start(graph, root_id, repo,
3926 check_cancelled, NULL);
3927 if (err)
3928 goto done;
3929 for (;;) {
3930 struct got_object_id *id;
3932 if (sigint_received || sigpipe_received)
3933 break;
3935 err = got_commit_graph_iter_next(&id, graph, repo,
3936 check_cancelled, NULL);
3937 if (err) {
3938 if (err->code == GOT_ERR_ITER_COMPLETED)
3939 err = NULL;
3940 break;
3942 if (id == NULL)
3943 break;
3945 err = got_object_open_as_commit(&commit, repo, id);
3946 if (err)
3947 break;
3949 if (show_changed_paths && !reverse_display_order) {
3950 err = get_changed_paths(&changed_paths, commit, repo);
3951 if (err)
3952 break;
3955 if (search_pattern) {
3956 err = match_logmsg(&have_match, id, commit, &regex);
3957 if (err) {
3958 got_object_commit_close(commit);
3959 break;
3961 if (have_match == 0 && show_changed_paths)
3962 match_changed_paths(&have_match,
3963 &changed_paths, &regex);
3964 if (have_match == 0) {
3965 got_object_commit_close(commit);
3966 TAILQ_FOREACH(pe, &changed_paths, entry) {
3967 free((char *)pe->path);
3968 free(pe->data);
3970 got_pathlist_free(&changed_paths);
3971 continue;
3975 if (reverse_display_order) {
3976 err = got_object_qid_alloc(&qid, id);
3977 if (err)
3978 break;
3979 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3980 got_object_commit_close(commit);
3981 } else {
3982 err = print_commit(commit, id, repo, path,
3983 show_changed_paths ? &changed_paths : NULL,
3984 show_patch, diff_context, refs_idmap, NULL);
3985 got_object_commit_close(commit);
3986 if (err)
3987 break;
3989 if ((limit && --limit == 0) ||
3990 (end_id && got_object_id_cmp(id, end_id) == 0))
3991 break;
3993 TAILQ_FOREACH(pe, &changed_paths, entry) {
3994 free((char *)pe->path);
3995 free(pe->data);
3997 got_pathlist_free(&changed_paths);
3999 if (reverse_display_order) {
4000 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4001 err = got_object_open_as_commit(&commit, repo, qid->id);
4002 if (err)
4003 break;
4004 if (show_changed_paths) {
4005 err = get_changed_paths(&changed_paths,
4006 commit, repo);
4007 if (err)
4008 break;
4010 err = print_commit(commit, qid->id, repo, path,
4011 show_changed_paths ? &changed_paths : NULL,
4012 show_patch, diff_context, refs_idmap, NULL);
4013 got_object_commit_close(commit);
4014 if (err)
4015 break;
4016 TAILQ_FOREACH(pe, &changed_paths, entry) {
4017 free((char *)pe->path);
4018 free(pe->data);
4020 got_pathlist_free(&changed_paths);
4023 done:
4024 while (!STAILQ_EMPTY(&reversed_commits)) {
4025 qid = STAILQ_FIRST(&reversed_commits);
4026 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4027 got_object_qid_free(qid);
4029 TAILQ_FOREACH(pe, &changed_paths, entry) {
4030 free((char *)pe->path);
4031 free(pe->data);
4033 got_pathlist_free(&changed_paths);
4034 if (search_pattern)
4035 regfree(&regex);
4036 got_commit_graph_close(graph);
4037 return err;
4040 __dead static void
4041 usage_log(void)
4043 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4044 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4045 "[-R] [path]\n", getprogname());
4046 exit(1);
4049 static int
4050 get_default_log_limit(void)
4052 const char *got_default_log_limit;
4053 long long n;
4054 const char *errstr;
4056 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4057 if (got_default_log_limit == NULL)
4058 return 0;
4059 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4060 if (errstr != NULL)
4061 return 0;
4062 return n;
4065 static const struct got_error *
4066 cmd_log(int argc, char *argv[])
4068 const struct got_error *error;
4069 struct got_repository *repo = NULL;
4070 struct got_worktree *worktree = NULL;
4071 struct got_object_id *start_id = NULL, *end_id = NULL;
4072 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4073 const char *start_commit = NULL, *end_commit = NULL;
4074 const char *search_pattern = NULL;
4075 int diff_context = -1, ch;
4076 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4077 int reverse_display_order = 0;
4078 const char *errstr;
4079 struct got_reflist_head refs;
4080 struct got_reflist_object_id_map *refs_idmap = NULL;
4082 TAILQ_INIT(&refs);
4084 #ifndef PROFILE
4085 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4086 NULL)
4087 == -1)
4088 err(1, "pledge");
4089 #endif
4091 limit = get_default_log_limit();
4093 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4094 switch (ch) {
4095 case 'p':
4096 show_patch = 1;
4097 break;
4098 case 'P':
4099 show_changed_paths = 1;
4100 break;
4101 case 'c':
4102 start_commit = optarg;
4103 break;
4104 case 'C':
4105 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4106 &errstr);
4107 if (errstr != NULL)
4108 err(1, "-C option %s", errstr);
4109 break;
4110 case 'l':
4111 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4112 if (errstr != NULL)
4113 err(1, "-l option %s", errstr);
4114 break;
4115 case 'b':
4116 log_branches = 1;
4117 break;
4118 case 'r':
4119 repo_path = realpath(optarg, NULL);
4120 if (repo_path == NULL)
4121 return got_error_from_errno2("realpath",
4122 optarg);
4123 got_path_strip_trailing_slashes(repo_path);
4124 break;
4125 case 'R':
4126 reverse_display_order = 1;
4127 break;
4128 case 's':
4129 search_pattern = optarg;
4130 break;
4131 case 'x':
4132 end_commit = optarg;
4133 break;
4134 default:
4135 usage_log();
4136 /* NOTREACHED */
4140 argc -= optind;
4141 argv += optind;
4143 if (diff_context == -1)
4144 diff_context = 3;
4145 else if (!show_patch)
4146 errx(1, "-C requires -p");
4148 cwd = getcwd(NULL, 0);
4149 if (cwd == NULL) {
4150 error = got_error_from_errno("getcwd");
4151 goto done;
4154 if (repo_path == NULL) {
4155 error = got_worktree_open(&worktree, cwd);
4156 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4157 goto done;
4158 error = NULL;
4161 if (argc == 1) {
4162 if (worktree) {
4163 error = got_worktree_resolve_path(&path, worktree,
4164 argv[0]);
4165 if (error)
4166 goto done;
4167 } else {
4168 path = strdup(argv[0]);
4169 if (path == NULL) {
4170 error = got_error_from_errno("strdup");
4171 goto done;
4174 } else if (argc != 0)
4175 usage_log();
4177 if (repo_path == NULL) {
4178 repo_path = worktree ?
4179 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4181 if (repo_path == NULL) {
4182 error = got_error_from_errno("strdup");
4183 goto done;
4186 error = got_repo_open(&repo, repo_path, NULL);
4187 if (error != NULL)
4188 goto done;
4190 error = apply_unveil(got_repo_get_path(repo), 1,
4191 worktree ? got_worktree_get_root_path(worktree) : NULL);
4192 if (error)
4193 goto done;
4195 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4196 if (error)
4197 goto done;
4199 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4200 if (error)
4201 goto done;
4203 if (start_commit == NULL) {
4204 struct got_reference *head_ref;
4205 struct got_commit_object *commit = NULL;
4206 error = got_ref_open(&head_ref, repo,
4207 worktree ? got_worktree_get_head_ref_name(worktree)
4208 : GOT_REF_HEAD, 0);
4209 if (error != NULL)
4210 goto done;
4211 error = got_ref_resolve(&start_id, repo, head_ref);
4212 got_ref_close(head_ref);
4213 if (error != NULL)
4214 goto done;
4215 error = got_object_open_as_commit(&commit, repo,
4216 start_id);
4217 if (error != NULL)
4218 goto done;
4219 got_object_commit_close(commit);
4220 } else {
4221 error = got_repo_match_object_id(&start_id, NULL,
4222 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4223 if (error != NULL)
4224 goto done;
4226 if (end_commit != NULL) {
4227 error = got_repo_match_object_id(&end_id, NULL,
4228 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4229 if (error != NULL)
4230 goto done;
4233 if (worktree) {
4235 * If a path was specified on the command line it was resolved
4236 * to a path in the work tree above. Prepend the work tree's
4237 * path prefix to obtain the corresponding in-repository path.
4239 if (path) {
4240 const char *prefix;
4241 prefix = got_worktree_get_path_prefix(worktree);
4242 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4243 (path[0] != '\0') ? "/" : "", path) == -1) {
4244 error = got_error_from_errno("asprintf");
4245 goto done;
4248 } else
4249 error = got_repo_map_path(&in_repo_path, repo,
4250 path ? path : "");
4251 if (error != NULL)
4252 goto done;
4253 if (in_repo_path) {
4254 free(path);
4255 path = in_repo_path;
4258 error = print_commits(start_id, end_id, repo, path ? path : "",
4259 show_changed_paths, show_patch, search_pattern, diff_context,
4260 limit, log_branches, reverse_display_order, refs_idmap);
4261 done:
4262 free(path);
4263 free(repo_path);
4264 free(cwd);
4265 if (worktree)
4266 got_worktree_close(worktree);
4267 if (repo) {
4268 const struct got_error *close_err = got_repo_close(repo);
4269 if (error == NULL)
4270 error = close_err;
4272 if (refs_idmap)
4273 got_reflist_object_id_map_free(refs_idmap);
4274 got_ref_list_free(&refs);
4275 return error;
4278 __dead static void
4279 usage_diff(void)
4281 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4282 "[-r repository-path] [-s] [-w] [-P] "
4283 "[object1 object2 | path ...]\n", getprogname());
4284 exit(1);
4287 struct print_diff_arg {
4288 struct got_repository *repo;
4289 struct got_worktree *worktree;
4290 int diff_context;
4291 const char *id_str;
4292 int header_shown;
4293 int diff_staged;
4294 int ignore_whitespace;
4295 int force_text_diff;
4299 * Create a file which contains the target path of a symlink so we can feed
4300 * it as content to the diff engine.
4302 static const struct got_error *
4303 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4304 const char *abspath)
4306 const struct got_error *err = NULL;
4307 char target_path[PATH_MAX];
4308 ssize_t target_len, outlen;
4310 *fd = -1;
4312 if (dirfd != -1) {
4313 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4314 if (target_len == -1)
4315 return got_error_from_errno2("readlinkat", abspath);
4316 } else {
4317 target_len = readlink(abspath, target_path, PATH_MAX);
4318 if (target_len == -1)
4319 return got_error_from_errno2("readlink", abspath);
4322 *fd = got_opentempfd();
4323 if (*fd == -1)
4324 return got_error_from_errno("got_opentempfd");
4326 outlen = write(*fd, target_path, target_len);
4327 if (outlen == -1) {
4328 err = got_error_from_errno("got_opentempfd");
4329 goto done;
4332 if (lseek(*fd, 0, SEEK_SET) == -1) {
4333 err = got_error_from_errno2("lseek", abspath);
4334 goto done;
4336 done:
4337 if (err) {
4338 close(*fd);
4339 *fd = -1;
4341 return err;
4344 static const struct got_error *
4345 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4346 const char *path, struct got_object_id *blob_id,
4347 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4348 int dirfd, const char *de_name)
4350 struct print_diff_arg *a = arg;
4351 const struct got_error *err = NULL;
4352 struct got_blob_object *blob1 = NULL;
4353 int fd = -1;
4354 FILE *f2 = NULL;
4355 char *abspath = NULL, *label1 = NULL;
4356 struct stat sb;
4358 if (a->diff_staged) {
4359 if (staged_status != GOT_STATUS_MODIFY &&
4360 staged_status != GOT_STATUS_ADD &&
4361 staged_status != GOT_STATUS_DELETE)
4362 return NULL;
4363 } else {
4364 if (staged_status == GOT_STATUS_DELETE)
4365 return NULL;
4366 if (status == GOT_STATUS_NONEXISTENT)
4367 return got_error_set_errno(ENOENT, path);
4368 if (status != GOT_STATUS_MODIFY &&
4369 status != GOT_STATUS_ADD &&
4370 status != GOT_STATUS_DELETE &&
4371 status != GOT_STATUS_CONFLICT)
4372 return NULL;
4375 if (!a->header_shown) {
4376 printf("diff %s %s%s\n", a->id_str,
4377 got_worktree_get_root_path(a->worktree),
4378 a->diff_staged ? " (staged changes)" : "");
4379 a->header_shown = 1;
4382 if (a->diff_staged) {
4383 const char *label1 = NULL, *label2 = NULL;
4384 switch (staged_status) {
4385 case GOT_STATUS_MODIFY:
4386 label1 = path;
4387 label2 = path;
4388 break;
4389 case GOT_STATUS_ADD:
4390 label2 = path;
4391 break;
4392 case GOT_STATUS_DELETE:
4393 label1 = path;
4394 break;
4395 default:
4396 return got_error(GOT_ERR_FILE_STATUS);
4398 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4399 staged_blob_id, label1, label2, a->diff_context,
4400 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4403 if (staged_status == GOT_STATUS_ADD ||
4404 staged_status == GOT_STATUS_MODIFY) {
4405 char *id_str;
4406 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4407 8192);
4408 if (err)
4409 goto done;
4410 err = got_object_id_str(&id_str, staged_blob_id);
4411 if (err)
4412 goto done;
4413 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4414 err = got_error_from_errno("asprintf");
4415 free(id_str);
4416 goto done;
4418 free(id_str);
4419 } else if (status != GOT_STATUS_ADD) {
4420 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4421 if (err)
4422 goto done;
4425 if (status != GOT_STATUS_DELETE) {
4426 if (asprintf(&abspath, "%s/%s",
4427 got_worktree_get_root_path(a->worktree), path) == -1) {
4428 err = got_error_from_errno("asprintf");
4429 goto done;
4432 if (dirfd != -1) {
4433 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4434 if (fd == -1) {
4435 if (!got_err_open_nofollow_on_symlink()) {
4436 err = got_error_from_errno2("openat",
4437 abspath);
4438 goto done;
4440 err = get_symlink_target_file(&fd, dirfd,
4441 de_name, abspath);
4442 if (err)
4443 goto done;
4445 } else {
4446 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4447 if (fd == -1) {
4448 if (!got_err_open_nofollow_on_symlink()) {
4449 err = got_error_from_errno2("open",
4450 abspath);
4451 goto done;
4453 err = get_symlink_target_file(&fd, dirfd,
4454 de_name, abspath);
4455 if (err)
4456 goto done;
4459 if (fstat(fd, &sb) == -1) {
4460 err = got_error_from_errno2("fstat", abspath);
4461 goto done;
4463 f2 = fdopen(fd, "r");
4464 if (f2 == NULL) {
4465 err = got_error_from_errno2("fdopen", abspath);
4466 goto done;
4468 fd = -1;
4469 } else
4470 sb.st_size = 0;
4472 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4473 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4474 done:
4475 if (blob1)
4476 got_object_blob_close(blob1);
4477 if (f2 && fclose(f2) == EOF && err == NULL)
4478 err = got_error_from_errno("fclose");
4479 if (fd != -1 && close(fd) == -1 && err == NULL)
4480 err = got_error_from_errno("close");
4481 free(abspath);
4482 return err;
4485 static const struct got_error *
4486 cmd_diff(int argc, char *argv[])
4488 const struct got_error *error;
4489 struct got_repository *repo = NULL;
4490 struct got_worktree *worktree = NULL;
4491 char *cwd = NULL, *repo_path = NULL;
4492 const char *commit_args[2] = { NULL, NULL };
4493 int ncommit_args = 0;
4494 struct got_object_id *ids[2] = { NULL, NULL };
4495 char *labels[2] = { NULL, NULL };
4496 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4497 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4498 int force_text_diff = 0, force_path = 0, rflag = 0;
4499 const char *errstr;
4500 struct got_reflist_head refs;
4501 struct got_pathlist_head paths;
4502 struct got_pathlist_entry *pe;
4504 TAILQ_INIT(&refs);
4505 TAILQ_INIT(&paths);
4507 #ifndef PROFILE
4508 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4509 NULL) == -1)
4510 err(1, "pledge");
4511 #endif
4513 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4514 switch (ch) {
4515 case 'a':
4516 force_text_diff = 1;
4517 break;
4518 case 'c':
4519 if (ncommit_args >= 2)
4520 errx(1, "too many -c options used");
4521 commit_args[ncommit_args++] = optarg;
4522 break;
4523 case 'C':
4524 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4525 &errstr);
4526 if (errstr != NULL)
4527 err(1, "-C option %s", errstr);
4528 break;
4529 case 'r':
4530 repo_path = realpath(optarg, NULL);
4531 if (repo_path == NULL)
4532 return got_error_from_errno2("realpath",
4533 optarg);
4534 got_path_strip_trailing_slashes(repo_path);
4535 rflag = 1;
4536 break;
4537 case 's':
4538 diff_staged = 1;
4539 break;
4540 case 'w':
4541 ignore_whitespace = 1;
4542 break;
4543 case 'P':
4544 force_path = 1;
4545 break;
4546 default:
4547 usage_diff();
4548 /* NOTREACHED */
4552 argc -= optind;
4553 argv += optind;
4555 cwd = getcwd(NULL, 0);
4556 if (cwd == NULL) {
4557 error = got_error_from_errno("getcwd");
4558 goto done;
4561 if (repo_path == NULL) {
4562 error = got_worktree_open(&worktree, cwd);
4563 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4564 goto done;
4565 else
4566 error = NULL;
4567 if (worktree) {
4568 repo_path =
4569 strdup(got_worktree_get_repo_path(worktree));
4570 if (repo_path == NULL) {
4571 error = got_error_from_errno("strdup");
4572 goto done;
4574 } else {
4575 repo_path = strdup(cwd);
4576 if (repo_path == NULL) {
4577 error = got_error_from_errno("strdup");
4578 goto done;
4583 error = got_repo_open(&repo, repo_path, NULL);
4584 free(repo_path);
4585 if (error != NULL)
4586 goto done;
4588 if (rflag || worktree == NULL || ncommit_args > 0) {
4589 if (force_path) {
4590 error = got_error_msg(GOT_ERR_NOT_IMPL,
4591 "-P option can only be used when diffing "
4592 "a work tree");
4593 goto done;
4595 if (diff_staged) {
4596 error = got_error_msg(GOT_ERR_NOT_IMPL,
4597 "-s option can only be used when diffing "
4598 "a work tree");
4599 goto done;
4603 error = apply_unveil(got_repo_get_path(repo), 1,
4604 worktree ? got_worktree_get_root_path(worktree) : NULL);
4605 if (error)
4606 goto done;
4608 if ((!force_path && argc == 2) || ncommit_args > 0) {
4609 int obj_type = (ncommit_args > 0 ?
4610 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4611 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4612 NULL);
4613 if (error)
4614 goto done;
4615 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4616 const char *arg;
4617 if (ncommit_args > 0)
4618 arg = commit_args[i];
4619 else
4620 arg = argv[i];
4621 error = got_repo_match_object_id(&ids[i], &labels[i],
4622 arg, obj_type, &refs, repo);
4623 if (error) {
4624 if (error->code != GOT_ERR_NOT_REF &&
4625 error->code != GOT_ERR_NO_OBJ)
4626 goto done;
4627 if (ncommit_args > 0)
4628 goto done;
4629 error = NULL;
4630 break;
4635 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4636 struct print_diff_arg arg;
4637 char *id_str;
4639 if (worktree == NULL) {
4640 if (argc == 2 && ids[0] == NULL) {
4641 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4642 goto done;
4643 } else if (argc == 2 && ids[1] == NULL) {
4644 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4645 goto done;
4646 } else if (argc > 0) {
4647 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4648 "%s", "specified paths cannot be resolved");
4649 goto done;
4650 } else {
4651 error = got_error(GOT_ERR_NOT_WORKTREE);
4652 goto done;
4656 error = get_worktree_paths_from_argv(&paths, argc, argv,
4657 worktree);
4658 if (error)
4659 goto done;
4661 error = got_object_id_str(&id_str,
4662 got_worktree_get_base_commit_id(worktree));
4663 if (error)
4664 goto done;
4665 arg.repo = repo;
4666 arg.worktree = worktree;
4667 arg.diff_context = diff_context;
4668 arg.id_str = id_str;
4669 arg.header_shown = 0;
4670 arg.diff_staged = diff_staged;
4671 arg.ignore_whitespace = ignore_whitespace;
4672 arg.force_text_diff = force_text_diff;
4674 error = got_worktree_status(worktree, &paths, repo, 0,
4675 print_diff, &arg, check_cancelled, NULL);
4676 free(id_str);
4677 goto done;
4680 if (ncommit_args == 1) {
4681 struct got_commit_object *commit;
4682 error = got_object_open_as_commit(&commit, repo, ids[0]);
4683 if (error)
4684 goto done;
4686 labels[1] = labels[0];
4687 ids[1] = ids[0];
4688 if (got_object_commit_get_nparents(commit) > 0) {
4689 const struct got_object_id_queue *pids;
4690 struct got_object_qid *pid;
4691 pids = got_object_commit_get_parent_ids(commit);
4692 pid = STAILQ_FIRST(pids);
4693 ids[0] = got_object_id_dup(pid->id);
4694 if (ids[0] == NULL) {
4695 error = got_error_from_errno(
4696 "got_object_id_dup");
4697 got_object_commit_close(commit);
4698 goto done;
4700 error = got_object_id_str(&labels[0], ids[0]);
4701 if (error) {
4702 got_object_commit_close(commit);
4703 goto done;
4705 } else {
4706 ids[0] = NULL;
4707 labels[0] = strdup("/dev/null");
4708 if (labels[0] == NULL) {
4709 error = got_error_from_errno("strdup");
4710 got_object_commit_close(commit);
4711 goto done;
4715 got_object_commit_close(commit);
4718 if (ncommit_args == 0 && argc > 2) {
4719 error = got_error_msg(GOT_ERR_BAD_PATH,
4720 "path arguments cannot be used when diffing two objects");
4721 goto done;
4724 if (ids[0]) {
4725 error = got_object_get_type(&type1, repo, ids[0]);
4726 if (error)
4727 goto done;
4730 error = got_object_get_type(&type2, repo, ids[1]);
4731 if (error)
4732 goto done;
4733 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4734 error = got_error(GOT_ERR_OBJ_TYPE);
4735 goto done;
4737 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4738 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4739 "path arguments cannot be used when diffing blobs");
4740 goto done;
4743 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4744 char *in_repo_path;
4745 struct got_pathlist_entry *new;
4746 if (worktree) {
4747 const char *prefix;
4748 char *p;
4749 error = got_worktree_resolve_path(&p, worktree,
4750 argv[i]);
4751 if (error)
4752 goto done;
4753 prefix = got_worktree_get_path_prefix(worktree);
4754 while (prefix[0] == '/')
4755 prefix++;
4756 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4757 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4758 p) == -1) {
4759 error = got_error_from_errno("asprintf");
4760 free(p);
4761 goto done;
4763 free(p);
4764 } else {
4765 char *mapped_path, *s;
4766 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4767 if (error)
4768 goto done;
4769 s = mapped_path;
4770 while (s[0] == '/')
4771 s++;
4772 in_repo_path = strdup(s);
4773 if (in_repo_path == NULL) {
4774 error = got_error_from_errno("asprintf");
4775 free(mapped_path);
4776 goto done;
4778 free(mapped_path);
4781 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4782 if (error || new == NULL /* duplicate */)
4783 free(in_repo_path);
4784 if (error)
4785 goto done;
4788 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4789 case GOT_OBJ_TYPE_BLOB:
4790 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4791 NULL, NULL, diff_context, ignore_whitespace,
4792 force_text_diff, repo, stdout);
4793 break;
4794 case GOT_OBJ_TYPE_TREE:
4795 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4796 &paths, "", "", diff_context, ignore_whitespace,
4797 force_text_diff, repo, stdout);
4798 break;
4799 case GOT_OBJ_TYPE_COMMIT:
4800 printf("diff %s %s\n", labels[0], labels[1]);
4801 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4802 &paths, diff_context, ignore_whitespace, force_text_diff,
4803 repo, stdout);
4804 break;
4805 default:
4806 error = got_error(GOT_ERR_OBJ_TYPE);
4808 done:
4809 free(labels[0]);
4810 free(labels[1]);
4811 free(ids[0]);
4812 free(ids[1]);
4813 if (worktree)
4814 got_worktree_close(worktree);
4815 if (repo) {
4816 const struct got_error *close_err = got_repo_close(repo);
4817 if (error == NULL)
4818 error = close_err;
4820 TAILQ_FOREACH(pe, &paths, entry)
4821 free((char *)pe->path);
4822 got_pathlist_free(&paths);
4823 got_ref_list_free(&refs);
4824 return error;
4827 __dead static void
4828 usage_blame(void)
4830 fprintf(stderr,
4831 "usage: %s blame [-c commit] [-r repository-path] path\n",
4832 getprogname());
4833 exit(1);
4836 struct blame_line {
4837 int annotated;
4838 char *id_str;
4839 char *committer;
4840 char datebuf[11]; /* YYYY-MM-DD + NUL */
4843 struct blame_cb_args {
4844 struct blame_line *lines;
4845 int nlines;
4846 int nlines_prec;
4847 int lineno_cur;
4848 off_t *line_offsets;
4849 FILE *f;
4850 struct got_repository *repo;
4853 static const struct got_error *
4854 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4856 const struct got_error *err = NULL;
4857 struct blame_cb_args *a = arg;
4858 struct blame_line *bline;
4859 char *line = NULL;
4860 size_t linesize = 0;
4861 struct got_commit_object *commit = NULL;
4862 off_t offset;
4863 struct tm tm;
4864 time_t committer_time;
4866 if (nlines != a->nlines ||
4867 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4868 return got_error(GOT_ERR_RANGE);
4870 if (sigint_received)
4871 return got_error(GOT_ERR_ITER_COMPLETED);
4873 if (lineno == -1)
4874 return NULL; /* no change in this commit */
4876 /* Annotate this line. */
4877 bline = &a->lines[lineno - 1];
4878 if (bline->annotated)
4879 return NULL;
4880 err = got_object_id_str(&bline->id_str, id);
4881 if (err)
4882 return err;
4884 err = got_object_open_as_commit(&commit, a->repo, id);
4885 if (err)
4886 goto done;
4888 bline->committer = strdup(got_object_commit_get_committer(commit));
4889 if (bline->committer == NULL) {
4890 err = got_error_from_errno("strdup");
4891 goto done;
4894 committer_time = got_object_commit_get_committer_time(commit);
4895 if (gmtime_r(&committer_time, &tm) == NULL)
4896 return got_error_from_errno("gmtime_r");
4897 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4898 &tm) == 0) {
4899 err = got_error(GOT_ERR_NO_SPACE);
4900 goto done;
4902 bline->annotated = 1;
4904 /* Print lines annotated so far. */
4905 bline = &a->lines[a->lineno_cur - 1];
4906 if (!bline->annotated)
4907 goto done;
4909 offset = a->line_offsets[a->lineno_cur - 1];
4910 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4911 err = got_error_from_errno("fseeko");
4912 goto done;
4915 while (bline->annotated) {
4916 char *smallerthan, *at, *nl, *committer;
4917 size_t len;
4919 if (getline(&line, &linesize, a->f) == -1) {
4920 if (ferror(a->f))
4921 err = got_error_from_errno("getline");
4922 break;
4925 committer = bline->committer;
4926 smallerthan = strchr(committer, '<');
4927 if (smallerthan && smallerthan[1] != '\0')
4928 committer = smallerthan + 1;
4929 at = strchr(committer, '@');
4930 if (at)
4931 *at = '\0';
4932 len = strlen(committer);
4933 if (len >= 9)
4934 committer[8] = '\0';
4936 nl = strchr(line, '\n');
4937 if (nl)
4938 *nl = '\0';
4939 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4940 bline->id_str, bline->datebuf, committer, line);
4942 a->lineno_cur++;
4943 bline = &a->lines[a->lineno_cur - 1];
4945 done:
4946 if (commit)
4947 got_object_commit_close(commit);
4948 free(line);
4949 return err;
4952 static const struct got_error *
4953 cmd_blame(int argc, char *argv[])
4955 const struct got_error *error;
4956 struct got_repository *repo = NULL;
4957 struct got_worktree *worktree = NULL;
4958 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4959 char *link_target = NULL;
4960 struct got_object_id *obj_id = NULL;
4961 struct got_object_id *commit_id = NULL;
4962 struct got_blob_object *blob = NULL;
4963 char *commit_id_str = NULL;
4964 struct blame_cb_args bca;
4965 int ch, obj_type, i;
4966 off_t filesize;
4968 memset(&bca, 0, sizeof(bca));
4970 #ifndef PROFILE
4971 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4972 NULL) == -1)
4973 err(1, "pledge");
4974 #endif
4976 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4977 switch (ch) {
4978 case 'c':
4979 commit_id_str = optarg;
4980 break;
4981 case 'r':
4982 repo_path = realpath(optarg, NULL);
4983 if (repo_path == NULL)
4984 return got_error_from_errno2("realpath",
4985 optarg);
4986 got_path_strip_trailing_slashes(repo_path);
4987 break;
4988 default:
4989 usage_blame();
4990 /* NOTREACHED */
4994 argc -= optind;
4995 argv += optind;
4997 if (argc == 1)
4998 path = argv[0];
4999 else
5000 usage_blame();
5002 cwd = getcwd(NULL, 0);
5003 if (cwd == NULL) {
5004 error = got_error_from_errno("getcwd");
5005 goto done;
5007 if (repo_path == NULL) {
5008 error = got_worktree_open(&worktree, cwd);
5009 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5010 goto done;
5011 else
5012 error = NULL;
5013 if (worktree) {
5014 repo_path =
5015 strdup(got_worktree_get_repo_path(worktree));
5016 if (repo_path == NULL) {
5017 error = got_error_from_errno("strdup");
5018 if (error)
5019 goto done;
5021 } else {
5022 repo_path = strdup(cwd);
5023 if (repo_path == NULL) {
5024 error = got_error_from_errno("strdup");
5025 goto done;
5030 error = got_repo_open(&repo, repo_path, NULL);
5031 if (error != NULL)
5032 goto done;
5034 if (worktree) {
5035 const char *prefix = got_worktree_get_path_prefix(worktree);
5036 char *p;
5038 error = got_worktree_resolve_path(&p, worktree, path);
5039 if (error)
5040 goto done;
5041 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5042 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5043 p) == -1) {
5044 error = got_error_from_errno("asprintf");
5045 free(p);
5046 goto done;
5048 free(p);
5049 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5050 } else {
5051 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5052 if (error)
5053 goto done;
5054 error = got_repo_map_path(&in_repo_path, repo, path);
5056 if (error)
5057 goto done;
5059 if (commit_id_str == NULL) {
5060 struct got_reference *head_ref;
5061 error = got_ref_open(&head_ref, repo, worktree ?
5062 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5063 if (error != NULL)
5064 goto done;
5065 error = got_ref_resolve(&commit_id, repo, head_ref);
5066 got_ref_close(head_ref);
5067 if (error != NULL)
5068 goto done;
5069 } else {
5070 struct got_reflist_head refs;
5071 TAILQ_INIT(&refs);
5072 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5073 NULL);
5074 if (error)
5075 goto done;
5076 error = got_repo_match_object_id(&commit_id, NULL,
5077 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5078 got_ref_list_free(&refs);
5079 if (error)
5080 goto done;
5083 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5084 commit_id, repo);
5085 if (error)
5086 goto done;
5088 error = got_object_id_by_path(&obj_id, repo, commit_id,
5089 link_target ? link_target : in_repo_path);
5090 if (error)
5091 goto done;
5093 error = got_object_get_type(&obj_type, repo, obj_id);
5094 if (error)
5095 goto done;
5097 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5098 error = got_error_path(link_target ? link_target : in_repo_path,
5099 GOT_ERR_OBJ_TYPE);
5100 goto done;
5103 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5104 if (error)
5105 goto done;
5106 bca.f = got_opentemp();
5107 if (bca.f == NULL) {
5108 error = got_error_from_errno("got_opentemp");
5109 goto done;
5111 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5112 &bca.line_offsets, bca.f, blob);
5113 if (error || bca.nlines == 0)
5114 goto done;
5116 /* Don't include \n at EOF in the blame line count. */
5117 if (bca.line_offsets[bca.nlines - 1] == filesize)
5118 bca.nlines--;
5120 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5121 if (bca.lines == NULL) {
5122 error = got_error_from_errno("calloc");
5123 goto done;
5125 bca.lineno_cur = 1;
5126 bca.nlines_prec = 0;
5127 i = bca.nlines;
5128 while (i > 0) {
5129 i /= 10;
5130 bca.nlines_prec++;
5132 bca.repo = repo;
5134 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5135 repo, blame_cb, &bca, check_cancelled, NULL);
5136 done:
5137 free(in_repo_path);
5138 free(link_target);
5139 free(repo_path);
5140 free(cwd);
5141 free(commit_id);
5142 free(obj_id);
5143 if (blob)
5144 got_object_blob_close(blob);
5145 if (worktree)
5146 got_worktree_close(worktree);
5147 if (repo) {
5148 const struct got_error *close_err = got_repo_close(repo);
5149 if (error == NULL)
5150 error = close_err;
5152 if (bca.lines) {
5153 for (i = 0; i < bca.nlines; i++) {
5154 struct blame_line *bline = &bca.lines[i];
5155 free(bline->id_str);
5156 free(bline->committer);
5158 free(bca.lines);
5160 free(bca.line_offsets);
5161 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5162 error = got_error_from_errno("fclose");
5163 return error;
5166 __dead static void
5167 usage_tree(void)
5169 fprintf(stderr,
5170 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5171 getprogname());
5172 exit(1);
5175 static const struct got_error *
5176 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5177 const char *root_path, struct got_repository *repo)
5179 const struct got_error *err = NULL;
5180 int is_root_path = (strcmp(path, root_path) == 0);
5181 const char *modestr = "";
5182 mode_t mode = got_tree_entry_get_mode(te);
5183 char *link_target = NULL;
5185 path += strlen(root_path);
5186 while (path[0] == '/')
5187 path++;
5189 if (got_object_tree_entry_is_submodule(te))
5190 modestr = "$";
5191 else if (S_ISLNK(mode)) {
5192 int i;
5194 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5195 if (err)
5196 return err;
5197 for (i = 0; i < strlen(link_target); i++) {
5198 if (!isprint((unsigned char)link_target[i]))
5199 link_target[i] = '?';
5202 modestr = "@";
5204 else if (S_ISDIR(mode))
5205 modestr = "/";
5206 else if (mode & S_IXUSR)
5207 modestr = "*";
5209 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5210 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5211 link_target ? " -> ": "", link_target ? link_target : "");
5213 free(link_target);
5214 return NULL;
5217 static const struct got_error *
5218 print_tree(const char *path, struct got_object_id *commit_id,
5219 int show_ids, int recurse, const char *root_path,
5220 struct got_repository *repo)
5222 const struct got_error *err = NULL;
5223 struct got_object_id *tree_id = NULL;
5224 struct got_tree_object *tree = NULL;
5225 int nentries, i;
5227 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5228 if (err)
5229 goto done;
5231 err = got_object_open_as_tree(&tree, repo, tree_id);
5232 if (err)
5233 goto done;
5234 nentries = got_object_tree_get_nentries(tree);
5235 for (i = 0; i < nentries; i++) {
5236 struct got_tree_entry *te;
5237 char *id = NULL;
5239 if (sigint_received || sigpipe_received)
5240 break;
5242 te = got_object_tree_get_entry(tree, i);
5243 if (show_ids) {
5244 char *id_str;
5245 err = got_object_id_str(&id_str,
5246 got_tree_entry_get_id(te));
5247 if (err)
5248 goto done;
5249 if (asprintf(&id, "%s ", id_str) == -1) {
5250 err = got_error_from_errno("asprintf");
5251 free(id_str);
5252 goto done;
5254 free(id_str);
5256 err = print_entry(te, id, path, root_path, repo);
5257 free(id);
5258 if (err)
5259 goto done;
5261 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5262 char *child_path;
5263 if (asprintf(&child_path, "%s%s%s", path,
5264 path[0] == '/' && path[1] == '\0' ? "" : "/",
5265 got_tree_entry_get_name(te)) == -1) {
5266 err = got_error_from_errno("asprintf");
5267 goto done;
5269 err = print_tree(child_path, commit_id, show_ids, 1,
5270 root_path, repo);
5271 free(child_path);
5272 if (err)
5273 goto done;
5276 done:
5277 if (tree)
5278 got_object_tree_close(tree);
5279 free(tree_id);
5280 return err;
5283 static const struct got_error *
5284 cmd_tree(int argc, char *argv[])
5286 const struct got_error *error;
5287 struct got_repository *repo = NULL;
5288 struct got_worktree *worktree = NULL;
5289 const char *path, *refname = NULL;
5290 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5291 struct got_object_id *commit_id = NULL;
5292 char *commit_id_str = NULL;
5293 int show_ids = 0, recurse = 0;
5294 int ch;
5296 #ifndef PROFILE
5297 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5298 NULL) == -1)
5299 err(1, "pledge");
5300 #endif
5302 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5303 switch (ch) {
5304 case 'c':
5305 commit_id_str = optarg;
5306 break;
5307 case 'r':
5308 repo_path = realpath(optarg, NULL);
5309 if (repo_path == NULL)
5310 return got_error_from_errno2("realpath",
5311 optarg);
5312 got_path_strip_trailing_slashes(repo_path);
5313 break;
5314 case 'i':
5315 show_ids = 1;
5316 break;
5317 case 'R':
5318 recurse = 1;
5319 break;
5320 default:
5321 usage_tree();
5322 /* NOTREACHED */
5326 argc -= optind;
5327 argv += optind;
5329 if (argc == 1)
5330 path = argv[0];
5331 else if (argc > 1)
5332 usage_tree();
5333 else
5334 path = NULL;
5336 cwd = getcwd(NULL, 0);
5337 if (cwd == NULL) {
5338 error = got_error_from_errno("getcwd");
5339 goto done;
5341 if (repo_path == NULL) {
5342 error = got_worktree_open(&worktree, cwd);
5343 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5344 goto done;
5345 else
5346 error = NULL;
5347 if (worktree) {
5348 repo_path =
5349 strdup(got_worktree_get_repo_path(worktree));
5350 if (repo_path == NULL)
5351 error = got_error_from_errno("strdup");
5352 if (error)
5353 goto done;
5354 } else {
5355 repo_path = strdup(cwd);
5356 if (repo_path == NULL) {
5357 error = got_error_from_errno("strdup");
5358 goto done;
5363 error = got_repo_open(&repo, repo_path, NULL);
5364 if (error != NULL)
5365 goto done;
5367 if (worktree) {
5368 const char *prefix = got_worktree_get_path_prefix(worktree);
5369 char *p;
5371 if (path == NULL)
5372 path = "";
5373 error = got_worktree_resolve_path(&p, worktree, path);
5374 if (error)
5375 goto done;
5376 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5377 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5378 p) == -1) {
5379 error = got_error_from_errno("asprintf");
5380 free(p);
5381 goto done;
5383 free(p);
5384 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5385 if (error)
5386 goto done;
5387 } else {
5388 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5389 if (error)
5390 goto done;
5391 if (path == NULL)
5392 path = "/";
5393 error = got_repo_map_path(&in_repo_path, repo, path);
5394 if (error != NULL)
5395 goto done;
5398 if (commit_id_str == NULL) {
5399 struct got_reference *head_ref;
5400 if (worktree)
5401 refname = got_worktree_get_head_ref_name(worktree);
5402 else
5403 refname = GOT_REF_HEAD;
5404 error = got_ref_open(&head_ref, repo, refname, 0);
5405 if (error != NULL)
5406 goto done;
5407 error = got_ref_resolve(&commit_id, repo, head_ref);
5408 got_ref_close(head_ref);
5409 if (error != NULL)
5410 goto done;
5411 } else {
5412 struct got_reflist_head refs;
5413 TAILQ_INIT(&refs);
5414 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5415 NULL);
5416 if (error)
5417 goto done;
5418 error = got_repo_match_object_id(&commit_id, NULL,
5419 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5420 got_ref_list_free(&refs);
5421 if (error)
5422 goto done;
5425 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5426 in_repo_path, repo);
5427 done:
5428 free(in_repo_path);
5429 free(repo_path);
5430 free(cwd);
5431 free(commit_id);
5432 if (worktree)
5433 got_worktree_close(worktree);
5434 if (repo) {
5435 const struct got_error *close_err = got_repo_close(repo);
5436 if (error == NULL)
5437 error = close_err;
5439 return error;
5442 __dead static void
5443 usage_status(void)
5445 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5446 "[-S status-codes] [path ...]\n", getprogname());
5447 exit(1);
5450 struct got_status_arg {
5451 char *status_codes;
5452 int suppress;
5455 static const struct got_error *
5456 print_status(void *arg, unsigned char status, unsigned char staged_status,
5457 const char *path, struct got_object_id *blob_id,
5458 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5459 int dirfd, const char *de_name)
5461 struct got_status_arg *st = arg;
5463 if (status == staged_status && (status == GOT_STATUS_DELETE))
5464 status = GOT_STATUS_NO_CHANGE;
5465 if (st != NULL && st->status_codes) {
5466 size_t ncodes = strlen(st->status_codes);
5467 int i, j = 0;
5469 for (i = 0; i < ncodes ; i++) {
5470 if (st->suppress) {
5471 if (status == st->status_codes[i] ||
5472 staged_status == st->status_codes[i]) {
5473 j++;
5474 continue;
5476 } else {
5477 if (status == st->status_codes[i] ||
5478 staged_status == st->status_codes[i])
5479 break;
5483 if (st->suppress && j == 0)
5484 goto print;
5486 if (i == ncodes)
5487 return NULL;
5489 print:
5490 printf("%c%c %s\n", status, staged_status, path);
5491 return NULL;
5494 static const struct got_error *
5495 cmd_status(int argc, char *argv[])
5497 const struct got_error *error = NULL;
5498 struct got_repository *repo = NULL;
5499 struct got_worktree *worktree = NULL;
5500 struct got_status_arg st;
5501 char *cwd = NULL;
5502 struct got_pathlist_head paths;
5503 struct got_pathlist_entry *pe;
5504 int ch, i, no_ignores = 0;
5506 TAILQ_INIT(&paths);
5508 memset(&st, 0, sizeof(st));
5509 st.status_codes = NULL;
5510 st.suppress = 0;
5512 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5513 switch (ch) {
5514 case 'I':
5515 no_ignores = 1;
5516 break;
5517 case 'S':
5518 if (st.status_codes != NULL && st.suppress == 0)
5519 option_conflict('S', 's');
5520 st.suppress = 1;
5521 /* fallthrough */
5522 case 's':
5523 for (i = 0; i < strlen(optarg); i++) {
5524 switch (optarg[i]) {
5525 case GOT_STATUS_MODIFY:
5526 case GOT_STATUS_ADD:
5527 case GOT_STATUS_DELETE:
5528 case GOT_STATUS_CONFLICT:
5529 case GOT_STATUS_MISSING:
5530 case GOT_STATUS_OBSTRUCTED:
5531 case GOT_STATUS_UNVERSIONED:
5532 case GOT_STATUS_MODE_CHANGE:
5533 case GOT_STATUS_NONEXISTENT:
5534 break;
5535 default:
5536 errx(1, "invalid status code '%c'",
5537 optarg[i]);
5540 if (ch == 's' && st.suppress)
5541 option_conflict('s', 'S');
5542 st.status_codes = optarg;
5543 break;
5544 default:
5545 usage_status();
5546 /* NOTREACHED */
5550 argc -= optind;
5551 argv += optind;
5553 #ifndef PROFILE
5554 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5555 NULL) == -1)
5556 err(1, "pledge");
5557 #endif
5558 cwd = getcwd(NULL, 0);
5559 if (cwd == NULL) {
5560 error = got_error_from_errno("getcwd");
5561 goto done;
5564 error = got_worktree_open(&worktree, cwd);
5565 if (error) {
5566 if (error->code == GOT_ERR_NOT_WORKTREE)
5567 error = wrap_not_worktree_error(error, "status", cwd);
5568 goto done;
5571 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5572 NULL);
5573 if (error != NULL)
5574 goto done;
5576 error = apply_unveil(got_repo_get_path(repo), 1,
5577 got_worktree_get_root_path(worktree));
5578 if (error)
5579 goto done;
5581 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5582 if (error)
5583 goto done;
5585 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5586 print_status, &st, check_cancelled, NULL);
5587 done:
5588 TAILQ_FOREACH(pe, &paths, entry)
5589 free((char *)pe->path);
5590 got_pathlist_free(&paths);
5591 free(cwd);
5592 return error;
5595 __dead static void
5596 usage_ref(void)
5598 fprintf(stderr,
5599 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5600 "[-s reference] [-d] [name]\n",
5601 getprogname());
5602 exit(1);
5605 static const struct got_error *
5606 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5608 static const struct got_error *err = NULL;
5609 struct got_reflist_head refs;
5610 struct got_reflist_entry *re;
5612 TAILQ_INIT(&refs);
5613 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5614 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5615 repo);
5616 if (err)
5617 return err;
5619 TAILQ_FOREACH(re, &refs, entry) {
5620 char *refstr;
5621 refstr = got_ref_to_str(re->ref);
5622 if (refstr == NULL)
5623 return got_error_from_errno("got_ref_to_str");
5624 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5625 free(refstr);
5628 got_ref_list_free(&refs);
5629 return NULL;
5632 static const struct got_error *
5633 delete_ref_by_name(struct got_repository *repo, const char *refname)
5635 const struct got_error *err;
5636 struct got_reference *ref;
5638 err = got_ref_open(&ref, repo, refname, 0);
5639 if (err)
5640 return err;
5642 err = delete_ref(repo, ref);
5643 got_ref_close(ref);
5644 return err;
5647 static const struct got_error *
5648 add_ref(struct got_repository *repo, const char *refname, const char *target)
5650 const struct got_error *err = NULL;
5651 struct got_object_id *id;
5652 struct got_reference *ref = NULL;
5655 * Don't let the user create a reference name with a leading '-'.
5656 * While technically a valid reference name, this case is usually
5657 * an unintended typo.
5659 if (refname[0] == '-')
5660 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5662 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5663 repo);
5664 if (err) {
5665 struct got_reference *target_ref;
5667 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5668 return err;
5669 err = got_ref_open(&target_ref, repo, target, 0);
5670 if (err)
5671 return err;
5672 err = got_ref_resolve(&id, repo, target_ref);
5673 got_ref_close(target_ref);
5674 if (err)
5675 return err;
5678 err = got_ref_alloc(&ref, refname, id);
5679 if (err)
5680 goto done;
5682 err = got_ref_write(ref, repo);
5683 done:
5684 if (ref)
5685 got_ref_close(ref);
5686 free(id);
5687 return err;
5690 static const struct got_error *
5691 add_symref(struct got_repository *repo, const char *refname, const char *target)
5693 const struct got_error *err = NULL;
5694 struct got_reference *ref = NULL;
5695 struct got_reference *target_ref = NULL;
5698 * Don't let the user create a reference name with a leading '-'.
5699 * While technically a valid reference name, this case is usually
5700 * an unintended typo.
5702 if (refname[0] == '-')
5703 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5705 err = got_ref_open(&target_ref, repo, target, 0);
5706 if (err)
5707 return err;
5709 err = got_ref_alloc_symref(&ref, refname, target_ref);
5710 if (err)
5711 goto done;
5713 err = got_ref_write(ref, repo);
5714 done:
5715 if (target_ref)
5716 got_ref_close(target_ref);
5717 if (ref)
5718 got_ref_close(ref);
5719 return err;
5722 static const struct got_error *
5723 cmd_ref(int argc, char *argv[])
5725 const struct got_error *error = NULL;
5726 struct got_repository *repo = NULL;
5727 struct got_worktree *worktree = NULL;
5728 char *cwd = NULL, *repo_path = NULL;
5729 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5730 const char *obj_arg = NULL, *symref_target= NULL;
5731 char *refname = NULL;
5733 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5734 switch (ch) {
5735 case 'c':
5736 obj_arg = optarg;
5737 break;
5738 case 'd':
5739 do_delete = 1;
5740 break;
5741 case 'r':
5742 repo_path = realpath(optarg, NULL);
5743 if (repo_path == NULL)
5744 return got_error_from_errno2("realpath",
5745 optarg);
5746 got_path_strip_trailing_slashes(repo_path);
5747 break;
5748 case 'l':
5749 do_list = 1;
5750 break;
5751 case 's':
5752 symref_target = optarg;
5753 break;
5754 case 't':
5755 sort_by_time = 1;
5756 break;
5757 default:
5758 usage_ref();
5759 /* NOTREACHED */
5763 if (obj_arg && do_list)
5764 option_conflict('c', 'l');
5765 if (obj_arg && do_delete)
5766 option_conflict('c', 'd');
5767 if (obj_arg && symref_target)
5768 option_conflict('c', 's');
5769 if (symref_target && do_delete)
5770 option_conflict('s', 'd');
5771 if (symref_target && do_list)
5772 option_conflict('s', 'l');
5773 if (do_delete && do_list)
5774 option_conflict('d', 'l');
5775 if (sort_by_time && !do_list)
5776 errx(1, "-t option requires -l option");
5778 argc -= optind;
5779 argv += optind;
5781 if (do_list) {
5782 if (argc != 0 && argc != 1)
5783 usage_ref();
5784 if (argc == 1) {
5785 refname = strdup(argv[0]);
5786 if (refname == NULL) {
5787 error = got_error_from_errno("strdup");
5788 goto done;
5791 } else {
5792 if (argc != 1)
5793 usage_ref();
5794 refname = strdup(argv[0]);
5795 if (refname == NULL) {
5796 error = got_error_from_errno("strdup");
5797 goto done;
5801 if (refname)
5802 got_path_strip_trailing_slashes(refname);
5804 #ifndef PROFILE
5805 if (do_list) {
5806 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5807 NULL) == -1)
5808 err(1, "pledge");
5809 } else {
5810 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5811 "sendfd unveil", NULL) == -1)
5812 err(1, "pledge");
5814 #endif
5815 cwd = getcwd(NULL, 0);
5816 if (cwd == NULL) {
5817 error = got_error_from_errno("getcwd");
5818 goto done;
5821 if (repo_path == NULL) {
5822 error = got_worktree_open(&worktree, cwd);
5823 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5824 goto done;
5825 else
5826 error = NULL;
5827 if (worktree) {
5828 repo_path =
5829 strdup(got_worktree_get_repo_path(worktree));
5830 if (repo_path == NULL)
5831 error = got_error_from_errno("strdup");
5832 if (error)
5833 goto done;
5834 } else {
5835 repo_path = strdup(cwd);
5836 if (repo_path == NULL) {
5837 error = got_error_from_errno("strdup");
5838 goto done;
5843 error = got_repo_open(&repo, repo_path, NULL);
5844 if (error != NULL)
5845 goto done;
5847 error = apply_unveil(got_repo_get_path(repo), do_list,
5848 worktree ? got_worktree_get_root_path(worktree) : NULL);
5849 if (error)
5850 goto done;
5852 if (do_list)
5853 error = list_refs(repo, refname, sort_by_time);
5854 else if (do_delete)
5855 error = delete_ref_by_name(repo, refname);
5856 else if (symref_target)
5857 error = add_symref(repo, refname, symref_target);
5858 else {
5859 if (obj_arg == NULL)
5860 usage_ref();
5861 error = add_ref(repo, refname, obj_arg);
5863 done:
5864 free(refname);
5865 if (repo) {
5866 const struct got_error *close_err = got_repo_close(repo);
5867 if (error == NULL)
5868 error = close_err;
5870 if (worktree)
5871 got_worktree_close(worktree);
5872 free(cwd);
5873 free(repo_path);
5874 return error;
5877 __dead static void
5878 usage_branch(void)
5880 fprintf(stderr,
5881 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5882 "[-n] [name]\n", getprogname());
5883 exit(1);
5886 static const struct got_error *
5887 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5888 struct got_reference *ref)
5890 const struct got_error *err = NULL;
5891 const char *refname, *marker = " ";
5892 char *refstr;
5894 refname = got_ref_get_name(ref);
5895 if (worktree && strcmp(refname,
5896 got_worktree_get_head_ref_name(worktree)) == 0) {
5897 struct got_object_id *id = NULL;
5899 err = got_ref_resolve(&id, repo, ref);
5900 if (err)
5901 return err;
5902 if (got_object_id_cmp(id,
5903 got_worktree_get_base_commit_id(worktree)) == 0)
5904 marker = "* ";
5905 else
5906 marker = "~ ";
5907 free(id);
5910 if (strncmp(refname, "refs/heads/", 11) == 0)
5911 refname += 11;
5912 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5913 refname += 18;
5914 if (strncmp(refname, "refs/remotes/", 13) == 0)
5915 refname += 13;
5917 refstr = got_ref_to_str(ref);
5918 if (refstr == NULL)
5919 return got_error_from_errno("got_ref_to_str");
5921 printf("%s%s: %s\n", marker, refname, refstr);
5922 free(refstr);
5923 return NULL;
5926 static const struct got_error *
5927 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5929 const char *refname;
5931 if (worktree == NULL)
5932 return got_error(GOT_ERR_NOT_WORKTREE);
5934 refname = got_worktree_get_head_ref_name(worktree);
5936 if (strncmp(refname, "refs/heads/", 11) == 0)
5937 refname += 11;
5938 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5939 refname += 18;
5941 printf("%s\n", refname);
5943 return NULL;
5946 static const struct got_error *
5947 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5948 int sort_by_time)
5950 static const struct got_error *err = NULL;
5951 struct got_reflist_head refs;
5952 struct got_reflist_entry *re;
5953 struct got_reference *temp_ref = NULL;
5954 int rebase_in_progress, histedit_in_progress;
5956 TAILQ_INIT(&refs);
5958 if (worktree) {
5959 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5960 worktree);
5961 if (err)
5962 return err;
5964 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5965 worktree);
5966 if (err)
5967 return err;
5969 if (rebase_in_progress || histedit_in_progress) {
5970 err = got_ref_open(&temp_ref, repo,
5971 got_worktree_get_head_ref_name(worktree), 0);
5972 if (err)
5973 return err;
5974 list_branch(repo, worktree, temp_ref);
5975 got_ref_close(temp_ref);
5979 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
5980 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5981 repo);
5982 if (err)
5983 return err;
5985 TAILQ_FOREACH(re, &refs, entry)
5986 list_branch(repo, worktree, re->ref);
5988 got_ref_list_free(&refs);
5990 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
5991 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5992 repo);
5993 if (err)
5994 return err;
5996 TAILQ_FOREACH(re, &refs, entry)
5997 list_branch(repo, worktree, re->ref);
5999 got_ref_list_free(&refs);
6001 return NULL;
6004 static const struct got_error *
6005 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6006 const char *branch_name)
6008 const struct got_error *err = NULL;
6009 struct got_reference *ref = NULL;
6010 char *refname, *remote_refname = NULL;
6012 if (strncmp(branch_name, "refs/", 5) == 0)
6013 branch_name += 5;
6014 if (strncmp(branch_name, "heads/", 6) == 0)
6015 branch_name += 6;
6016 else if (strncmp(branch_name, "remotes/", 8) == 0)
6017 branch_name += 8;
6019 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6020 return got_error_from_errno("asprintf");
6022 if (asprintf(&remote_refname, "refs/remotes/%s",
6023 branch_name) == -1) {
6024 err = got_error_from_errno("asprintf");
6025 goto done;
6028 err = got_ref_open(&ref, repo, refname, 0);
6029 if (err) {
6030 const struct got_error *err2;
6031 if (err->code != GOT_ERR_NOT_REF)
6032 goto done;
6034 * Keep 'err' intact such that if neither branch exists
6035 * we report "refs/heads" rather than "refs/remotes" in
6036 * our error message.
6038 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6039 if (err2)
6040 goto done;
6041 err = NULL;
6044 if (worktree &&
6045 strcmp(got_worktree_get_head_ref_name(worktree),
6046 got_ref_get_name(ref)) == 0) {
6047 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6048 "will not delete this work tree's current branch");
6049 goto done;
6052 err = delete_ref(repo, ref);
6053 done:
6054 if (ref)
6055 got_ref_close(ref);
6056 free(refname);
6057 free(remote_refname);
6058 return err;
6061 static const struct got_error *
6062 add_branch(struct got_repository *repo, const char *branch_name,
6063 struct got_object_id *base_commit_id)
6065 const struct got_error *err = NULL;
6066 struct got_reference *ref = NULL;
6067 char *base_refname = NULL, *refname = NULL;
6070 * Don't let the user create a branch name with a leading '-'.
6071 * While technically a valid reference name, this case is usually
6072 * an unintended typo.
6074 if (branch_name[0] == '-')
6075 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6077 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6078 branch_name += 11;
6080 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6081 err = got_error_from_errno("asprintf");
6082 goto done;
6085 err = got_ref_open(&ref, repo, refname, 0);
6086 if (err == NULL) {
6087 err = got_error(GOT_ERR_BRANCH_EXISTS);
6088 goto done;
6089 } else if (err->code != GOT_ERR_NOT_REF)
6090 goto done;
6092 err = got_ref_alloc(&ref, refname, base_commit_id);
6093 if (err)
6094 goto done;
6096 err = got_ref_write(ref, repo);
6097 done:
6098 if (ref)
6099 got_ref_close(ref);
6100 free(base_refname);
6101 free(refname);
6102 return err;
6105 static const struct got_error *
6106 cmd_branch(int argc, char *argv[])
6108 const struct got_error *error = NULL;
6109 struct got_repository *repo = NULL;
6110 struct got_worktree *worktree = NULL;
6111 char *cwd = NULL, *repo_path = NULL;
6112 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6113 const char *delref = NULL, *commit_id_arg = NULL;
6114 struct got_reference *ref = NULL;
6115 struct got_pathlist_head paths;
6116 struct got_pathlist_entry *pe;
6117 struct got_object_id *commit_id = NULL;
6118 char *commit_id_str = NULL;
6120 TAILQ_INIT(&paths);
6122 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6123 switch (ch) {
6124 case 'c':
6125 commit_id_arg = optarg;
6126 break;
6127 case 'd':
6128 delref = optarg;
6129 break;
6130 case 'r':
6131 repo_path = realpath(optarg, NULL);
6132 if (repo_path == NULL)
6133 return got_error_from_errno2("realpath",
6134 optarg);
6135 got_path_strip_trailing_slashes(repo_path);
6136 break;
6137 case 'l':
6138 do_list = 1;
6139 break;
6140 case 'n':
6141 do_update = 0;
6142 break;
6143 case 't':
6144 sort_by_time = 1;
6145 break;
6146 default:
6147 usage_branch();
6148 /* NOTREACHED */
6152 if (do_list && delref)
6153 option_conflict('l', 'd');
6154 if (sort_by_time && !do_list)
6155 errx(1, "-t option requires -l option");
6157 argc -= optind;
6158 argv += optind;
6160 if (!do_list && !delref && argc == 0)
6161 do_show = 1;
6163 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6164 errx(1, "-c option can only be used when creating a branch");
6166 if (do_list || delref) {
6167 if (argc > 0)
6168 usage_branch();
6169 } else if (!do_show && argc != 1)
6170 usage_branch();
6172 #ifndef PROFILE
6173 if (do_list || do_show) {
6174 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6175 NULL) == -1)
6176 err(1, "pledge");
6177 } else {
6178 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6179 "sendfd unveil", NULL) == -1)
6180 err(1, "pledge");
6182 #endif
6183 cwd = getcwd(NULL, 0);
6184 if (cwd == NULL) {
6185 error = got_error_from_errno("getcwd");
6186 goto done;
6189 if (repo_path == NULL) {
6190 error = got_worktree_open(&worktree, cwd);
6191 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6192 goto done;
6193 else
6194 error = NULL;
6195 if (worktree) {
6196 repo_path =
6197 strdup(got_worktree_get_repo_path(worktree));
6198 if (repo_path == NULL)
6199 error = got_error_from_errno("strdup");
6200 if (error)
6201 goto done;
6202 } else {
6203 repo_path = strdup(cwd);
6204 if (repo_path == NULL) {
6205 error = got_error_from_errno("strdup");
6206 goto done;
6211 error = got_repo_open(&repo, repo_path, NULL);
6212 if (error != NULL)
6213 goto done;
6215 error = apply_unveil(got_repo_get_path(repo), do_list,
6216 worktree ? got_worktree_get_root_path(worktree) : NULL);
6217 if (error)
6218 goto done;
6220 if (do_show)
6221 error = show_current_branch(repo, worktree);
6222 else if (do_list)
6223 error = list_branches(repo, worktree, sort_by_time);
6224 else if (delref)
6225 error = delete_branch(repo, worktree, delref);
6226 else {
6227 struct got_reflist_head refs;
6228 TAILQ_INIT(&refs);
6229 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6230 NULL);
6231 if (error)
6232 goto done;
6233 if (commit_id_arg == NULL)
6234 commit_id_arg = worktree ?
6235 got_worktree_get_head_ref_name(worktree) :
6236 GOT_REF_HEAD;
6237 error = got_repo_match_object_id(&commit_id, NULL,
6238 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6239 got_ref_list_free(&refs);
6240 if (error)
6241 goto done;
6242 error = add_branch(repo, argv[0], commit_id);
6243 if (error)
6244 goto done;
6245 if (worktree && do_update) {
6246 struct got_update_progress_arg upa;
6247 char *branch_refname = NULL;
6249 error = got_object_id_str(&commit_id_str, commit_id);
6250 if (error)
6251 goto done;
6252 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6253 worktree);
6254 if (error)
6255 goto done;
6256 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6257 == -1) {
6258 error = got_error_from_errno("asprintf");
6259 goto done;
6261 error = got_ref_open(&ref, repo, branch_refname, 0);
6262 free(branch_refname);
6263 if (error)
6264 goto done;
6265 error = switch_head_ref(ref, commit_id, worktree,
6266 repo);
6267 if (error)
6268 goto done;
6269 error = got_worktree_set_base_commit_id(worktree, repo,
6270 commit_id);
6271 if (error)
6272 goto done;
6273 memset(&upa, 0, sizeof(upa));
6274 error = got_worktree_checkout_files(worktree, &paths,
6275 repo, update_progress, &upa, check_cancelled,
6276 NULL);
6277 if (error)
6278 goto done;
6279 if (upa.did_something) {
6280 printf("Updated to %s: %s\n",
6281 got_worktree_get_head_ref_name(worktree),
6282 commit_id_str);
6284 print_update_progress_stats(&upa);
6287 done:
6288 if (ref)
6289 got_ref_close(ref);
6290 if (repo) {
6291 const struct got_error *close_err = got_repo_close(repo);
6292 if (error == NULL)
6293 error = close_err;
6295 if (worktree)
6296 got_worktree_close(worktree);
6297 free(cwd);
6298 free(repo_path);
6299 free(commit_id);
6300 free(commit_id_str);
6301 TAILQ_FOREACH(pe, &paths, entry)
6302 free((char *)pe->path);
6303 got_pathlist_free(&paths);
6304 return error;
6308 __dead static void
6309 usage_tag(void)
6311 fprintf(stderr,
6312 "usage: %s tag [-c commit] [-r repository] [-l] "
6313 "[-m message] name\n", getprogname());
6314 exit(1);
6317 #if 0
6318 static const struct got_error *
6319 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6321 const struct got_error *err = NULL;
6322 struct got_reflist_entry *re, *se, *new;
6323 struct got_object_id *re_id, *se_id;
6324 struct got_tag_object *re_tag, *se_tag;
6325 time_t re_time, se_time;
6327 STAILQ_FOREACH(re, tags, entry) {
6328 se = STAILQ_FIRST(sorted);
6329 if (se == NULL) {
6330 err = got_reflist_entry_dup(&new, re);
6331 if (err)
6332 return err;
6333 STAILQ_INSERT_HEAD(sorted, new, entry);
6334 continue;
6335 } else {
6336 err = got_ref_resolve(&re_id, repo, re->ref);
6337 if (err)
6338 break;
6339 err = got_object_open_as_tag(&re_tag, repo, re_id);
6340 free(re_id);
6341 if (err)
6342 break;
6343 re_time = got_object_tag_get_tagger_time(re_tag);
6344 got_object_tag_close(re_tag);
6347 while (se) {
6348 err = got_ref_resolve(&se_id, repo, re->ref);
6349 if (err)
6350 break;
6351 err = got_object_open_as_tag(&se_tag, repo, se_id);
6352 free(se_id);
6353 if (err)
6354 break;
6355 se_time = got_object_tag_get_tagger_time(se_tag);
6356 got_object_tag_close(se_tag);
6358 if (se_time > re_time) {
6359 err = got_reflist_entry_dup(&new, re);
6360 if (err)
6361 return err;
6362 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6363 break;
6365 se = STAILQ_NEXT(se, entry);
6366 continue;
6369 done:
6370 return err;
6372 #endif
6374 static const struct got_error *
6375 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6377 static const struct got_error *err = NULL;
6378 struct got_reflist_head refs;
6379 struct got_reflist_entry *re;
6381 TAILQ_INIT(&refs);
6383 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6384 if (err)
6385 return err;
6387 TAILQ_FOREACH(re, &refs, entry) {
6388 const char *refname;
6389 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6390 char datebuf[26];
6391 const char *tagger;
6392 time_t tagger_time;
6393 struct got_object_id *id;
6394 struct got_tag_object *tag;
6395 struct got_commit_object *commit = NULL;
6397 refname = got_ref_get_name(re->ref);
6398 if (strncmp(refname, "refs/tags/", 10) != 0)
6399 continue;
6400 refname += 10;
6401 refstr = got_ref_to_str(re->ref);
6402 if (refstr == NULL) {
6403 err = got_error_from_errno("got_ref_to_str");
6404 break;
6406 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6407 free(refstr);
6409 err = got_ref_resolve(&id, repo, re->ref);
6410 if (err)
6411 break;
6412 err = got_object_open_as_tag(&tag, repo, id);
6413 if (err) {
6414 if (err->code != GOT_ERR_OBJ_TYPE) {
6415 free(id);
6416 break;
6418 /* "lightweight" tag */
6419 err = got_object_open_as_commit(&commit, repo, id);
6420 if (err) {
6421 free(id);
6422 break;
6424 tagger = got_object_commit_get_committer(commit);
6425 tagger_time =
6426 got_object_commit_get_committer_time(commit);
6427 err = got_object_id_str(&id_str, id);
6428 free(id);
6429 if (err)
6430 break;
6431 } else {
6432 free(id);
6433 tagger = got_object_tag_get_tagger(tag);
6434 tagger_time = got_object_tag_get_tagger_time(tag);
6435 err = got_object_id_str(&id_str,
6436 got_object_tag_get_object_id(tag));
6437 if (err)
6438 break;
6440 printf("from: %s\n", tagger);
6441 datestr = get_datestr(&tagger_time, datebuf);
6442 if (datestr)
6443 printf("date: %s UTC\n", datestr);
6444 if (commit)
6445 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6446 else {
6447 switch (got_object_tag_get_object_type(tag)) {
6448 case GOT_OBJ_TYPE_BLOB:
6449 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6450 id_str);
6451 break;
6452 case GOT_OBJ_TYPE_TREE:
6453 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6454 id_str);
6455 break;
6456 case GOT_OBJ_TYPE_COMMIT:
6457 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6458 id_str);
6459 break;
6460 case GOT_OBJ_TYPE_TAG:
6461 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6462 id_str);
6463 break;
6464 default:
6465 break;
6468 free(id_str);
6469 if (commit) {
6470 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6471 if (err)
6472 break;
6473 got_object_commit_close(commit);
6474 } else {
6475 tagmsg0 = strdup(got_object_tag_get_message(tag));
6476 got_object_tag_close(tag);
6477 if (tagmsg0 == NULL) {
6478 err = got_error_from_errno("strdup");
6479 break;
6483 tagmsg = tagmsg0;
6484 do {
6485 line = strsep(&tagmsg, "\n");
6486 if (line)
6487 printf(" %s\n", line);
6488 } while (line);
6489 free(tagmsg0);
6492 got_ref_list_free(&refs);
6493 return NULL;
6496 static const struct got_error *
6497 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6498 const char *tag_name, const char *repo_path)
6500 const struct got_error *err = NULL;
6501 char *template = NULL, *initial_content = NULL;
6502 char *editor = NULL;
6503 int initial_content_len;
6504 int fd = -1;
6506 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6507 err = got_error_from_errno("asprintf");
6508 goto done;
6511 initial_content_len = asprintf(&initial_content,
6512 "\n# tagging commit %s as %s\n",
6513 commit_id_str, tag_name);
6514 if (initial_content_len == -1) {
6515 err = got_error_from_errno("asprintf");
6516 goto done;
6519 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6520 if (err)
6521 goto done;
6523 if (write(fd, initial_content, initial_content_len) == -1) {
6524 err = got_error_from_errno2("write", *tagmsg_path);
6525 goto done;
6528 err = get_editor(&editor);
6529 if (err)
6530 goto done;
6531 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6532 initial_content_len, 1);
6533 done:
6534 free(initial_content);
6535 free(template);
6536 free(editor);
6538 if (fd != -1 && close(fd) == -1 && err == NULL)
6539 err = got_error_from_errno2("close", *tagmsg_path);
6541 /* Editor is done; we can now apply unveil(2) */
6542 if (err == NULL)
6543 err = apply_unveil(repo_path, 0, NULL);
6544 if (err) {
6545 free(*tagmsg);
6546 *tagmsg = NULL;
6548 return err;
6551 static const struct got_error *
6552 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6553 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6555 const struct got_error *err = NULL;
6556 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6557 char *label = NULL, *commit_id_str = NULL;
6558 struct got_reference *ref = NULL;
6559 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6560 char *tagmsg_path = NULL, *tag_id_str = NULL;
6561 int preserve_tagmsg = 0;
6562 struct got_reflist_head refs;
6564 TAILQ_INIT(&refs);
6567 * Don't let the user create a tag name with a leading '-'.
6568 * While technically a valid reference name, this case is usually
6569 * an unintended typo.
6571 if (tag_name[0] == '-')
6572 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6574 err = get_author(&tagger, repo, worktree);
6575 if (err)
6576 return err;
6578 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6579 if (err)
6580 goto done;
6582 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6583 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6584 if (err)
6585 goto done;
6587 err = got_object_id_str(&commit_id_str, commit_id);
6588 if (err)
6589 goto done;
6591 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6592 refname = strdup(tag_name);
6593 if (refname == NULL) {
6594 err = got_error_from_errno("strdup");
6595 goto done;
6597 tag_name += 10;
6598 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6599 err = got_error_from_errno("asprintf");
6600 goto done;
6603 err = got_ref_open(&ref, repo, refname, 0);
6604 if (err == NULL) {
6605 err = got_error(GOT_ERR_TAG_EXISTS);
6606 goto done;
6607 } else if (err->code != GOT_ERR_NOT_REF)
6608 goto done;
6610 if (tagmsg_arg == NULL) {
6611 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6612 tag_name, got_repo_get_path(repo));
6613 if (err) {
6614 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6615 tagmsg_path != NULL)
6616 preserve_tagmsg = 1;
6617 goto done;
6621 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6622 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6623 if (err) {
6624 if (tagmsg_path)
6625 preserve_tagmsg = 1;
6626 goto done;
6629 err = got_ref_alloc(&ref, refname, tag_id);
6630 if (err) {
6631 if (tagmsg_path)
6632 preserve_tagmsg = 1;
6633 goto done;
6636 err = got_ref_write(ref, repo);
6637 if (err) {
6638 if (tagmsg_path)
6639 preserve_tagmsg = 1;
6640 goto done;
6643 err = got_object_id_str(&tag_id_str, tag_id);
6644 if (err) {
6645 if (tagmsg_path)
6646 preserve_tagmsg = 1;
6647 goto done;
6649 printf("Created tag %s\n", tag_id_str);
6650 done:
6651 if (preserve_tagmsg) {
6652 fprintf(stderr, "%s: tag message preserved in %s\n",
6653 getprogname(), tagmsg_path);
6654 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6655 err = got_error_from_errno2("unlink", tagmsg_path);
6656 free(tag_id_str);
6657 if (ref)
6658 got_ref_close(ref);
6659 free(commit_id);
6660 free(commit_id_str);
6661 free(refname);
6662 free(tagmsg);
6663 free(tagmsg_path);
6664 free(tagger);
6665 got_ref_list_free(&refs);
6666 return err;
6669 static const struct got_error *
6670 cmd_tag(int argc, char *argv[])
6672 const struct got_error *error = NULL;
6673 struct got_repository *repo = NULL;
6674 struct got_worktree *worktree = NULL;
6675 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6676 char *gitconfig_path = NULL;
6677 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6678 int ch, do_list = 0;
6680 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6681 switch (ch) {
6682 case 'c':
6683 commit_id_arg = optarg;
6684 break;
6685 case 'm':
6686 tagmsg = optarg;
6687 break;
6688 case 'r':
6689 repo_path = realpath(optarg, NULL);
6690 if (repo_path == NULL)
6691 return got_error_from_errno2("realpath",
6692 optarg);
6693 got_path_strip_trailing_slashes(repo_path);
6694 break;
6695 case 'l':
6696 do_list = 1;
6697 break;
6698 default:
6699 usage_tag();
6700 /* NOTREACHED */
6704 argc -= optind;
6705 argv += optind;
6707 if (do_list) {
6708 if (commit_id_arg != NULL)
6709 errx(1,
6710 "-c option can only be used when creating a tag");
6711 if (tagmsg)
6712 option_conflict('l', 'm');
6713 if (argc > 0)
6714 usage_tag();
6715 } else if (argc != 1)
6716 usage_tag();
6718 tag_name = argv[0];
6720 #ifndef PROFILE
6721 if (do_list) {
6722 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6723 NULL) == -1)
6724 err(1, "pledge");
6725 } else {
6726 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6727 "sendfd unveil", NULL) == -1)
6728 err(1, "pledge");
6730 #endif
6731 cwd = getcwd(NULL, 0);
6732 if (cwd == NULL) {
6733 error = got_error_from_errno("getcwd");
6734 goto done;
6737 if (repo_path == NULL) {
6738 error = got_worktree_open(&worktree, cwd);
6739 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6740 goto done;
6741 else
6742 error = NULL;
6743 if (worktree) {
6744 repo_path =
6745 strdup(got_worktree_get_repo_path(worktree));
6746 if (repo_path == NULL)
6747 error = got_error_from_errno("strdup");
6748 if (error)
6749 goto done;
6750 } else {
6751 repo_path = strdup(cwd);
6752 if (repo_path == NULL) {
6753 error = got_error_from_errno("strdup");
6754 goto done;
6759 if (do_list) {
6760 error = got_repo_open(&repo, repo_path, NULL);
6761 if (error != NULL)
6762 goto done;
6763 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6764 if (error)
6765 goto done;
6766 error = list_tags(repo, worktree);
6767 } else {
6768 error = get_gitconfig_path(&gitconfig_path);
6769 if (error)
6770 goto done;
6771 error = got_repo_open(&repo, repo_path, gitconfig_path);
6772 if (error != NULL)
6773 goto done;
6775 if (tagmsg) {
6776 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6777 if (error)
6778 goto done;
6781 if (commit_id_arg == NULL) {
6782 struct got_reference *head_ref;
6783 struct got_object_id *commit_id;
6784 error = got_ref_open(&head_ref, repo,
6785 worktree ? got_worktree_get_head_ref_name(worktree)
6786 : GOT_REF_HEAD, 0);
6787 if (error)
6788 goto done;
6789 error = got_ref_resolve(&commit_id, repo, head_ref);
6790 got_ref_close(head_ref);
6791 if (error)
6792 goto done;
6793 error = got_object_id_str(&commit_id_str, commit_id);
6794 free(commit_id);
6795 if (error)
6796 goto done;
6799 error = add_tag(repo, worktree, tag_name,
6800 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6802 done:
6803 if (repo) {
6804 const struct got_error *close_err = got_repo_close(repo);
6805 if (error == NULL)
6806 error = close_err;
6808 if (worktree)
6809 got_worktree_close(worktree);
6810 free(cwd);
6811 free(repo_path);
6812 free(gitconfig_path);
6813 free(commit_id_str);
6814 return error;
6817 __dead static void
6818 usage_add(void)
6820 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6821 getprogname());
6822 exit(1);
6825 static const struct got_error *
6826 add_progress(void *arg, unsigned char status, const char *path)
6828 while (path[0] == '/')
6829 path++;
6830 printf("%c %s\n", status, path);
6831 return NULL;
6834 static const struct got_error *
6835 cmd_add(int argc, char *argv[])
6837 const struct got_error *error = NULL;
6838 struct got_repository *repo = NULL;
6839 struct got_worktree *worktree = NULL;
6840 char *cwd = NULL;
6841 struct got_pathlist_head paths;
6842 struct got_pathlist_entry *pe;
6843 int ch, can_recurse = 0, no_ignores = 0;
6845 TAILQ_INIT(&paths);
6847 while ((ch = getopt(argc, argv, "IR")) != -1) {
6848 switch (ch) {
6849 case 'I':
6850 no_ignores = 1;
6851 break;
6852 case 'R':
6853 can_recurse = 1;
6854 break;
6855 default:
6856 usage_add();
6857 /* NOTREACHED */
6861 argc -= optind;
6862 argv += optind;
6864 #ifndef PROFILE
6865 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6866 NULL) == -1)
6867 err(1, "pledge");
6868 #endif
6869 if (argc < 1)
6870 usage_add();
6872 cwd = getcwd(NULL, 0);
6873 if (cwd == NULL) {
6874 error = got_error_from_errno("getcwd");
6875 goto done;
6878 error = got_worktree_open(&worktree, cwd);
6879 if (error) {
6880 if (error->code == GOT_ERR_NOT_WORKTREE)
6881 error = wrap_not_worktree_error(error, "add", cwd);
6882 goto done;
6885 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6886 NULL);
6887 if (error != NULL)
6888 goto done;
6890 error = apply_unveil(got_repo_get_path(repo), 1,
6891 got_worktree_get_root_path(worktree));
6892 if (error)
6893 goto done;
6895 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6896 if (error)
6897 goto done;
6899 if (!can_recurse) {
6900 char *ondisk_path;
6901 struct stat sb;
6902 TAILQ_FOREACH(pe, &paths, entry) {
6903 if (asprintf(&ondisk_path, "%s/%s",
6904 got_worktree_get_root_path(worktree),
6905 pe->path) == -1) {
6906 error = got_error_from_errno("asprintf");
6907 goto done;
6909 if (lstat(ondisk_path, &sb) == -1) {
6910 if (errno == ENOENT) {
6911 free(ondisk_path);
6912 continue;
6914 error = got_error_from_errno2("lstat",
6915 ondisk_path);
6916 free(ondisk_path);
6917 goto done;
6919 free(ondisk_path);
6920 if (S_ISDIR(sb.st_mode)) {
6921 error = got_error_msg(GOT_ERR_BAD_PATH,
6922 "adding directories requires -R option");
6923 goto done;
6928 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6929 NULL, repo, no_ignores);
6930 done:
6931 if (repo) {
6932 const struct got_error *close_err = got_repo_close(repo);
6933 if (error == NULL)
6934 error = close_err;
6936 if (worktree)
6937 got_worktree_close(worktree);
6938 TAILQ_FOREACH(pe, &paths, entry)
6939 free((char *)pe->path);
6940 got_pathlist_free(&paths);
6941 free(cwd);
6942 return error;
6945 __dead static void
6946 usage_remove(void)
6948 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6949 "path ...\n", getprogname());
6950 exit(1);
6953 static const struct got_error *
6954 print_remove_status(void *arg, unsigned char status,
6955 unsigned char staged_status, const char *path)
6957 while (path[0] == '/')
6958 path++;
6959 if (status == GOT_STATUS_NONEXISTENT)
6960 return NULL;
6961 if (status == staged_status && (status == GOT_STATUS_DELETE))
6962 status = GOT_STATUS_NO_CHANGE;
6963 printf("%c%c %s\n", status, staged_status, path);
6964 return NULL;
6967 static const struct got_error *
6968 cmd_remove(int argc, char *argv[])
6970 const struct got_error *error = NULL;
6971 struct got_worktree *worktree = NULL;
6972 struct got_repository *repo = NULL;
6973 const char *status_codes = NULL;
6974 char *cwd = NULL;
6975 struct got_pathlist_head paths;
6976 struct got_pathlist_entry *pe;
6977 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6979 TAILQ_INIT(&paths);
6981 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6982 switch (ch) {
6983 case 'f':
6984 delete_local_mods = 1;
6985 break;
6986 case 'k':
6987 keep_on_disk = 1;
6988 break;
6989 case 'R':
6990 can_recurse = 1;
6991 break;
6992 case 's':
6993 for (i = 0; i < strlen(optarg); i++) {
6994 switch (optarg[i]) {
6995 case GOT_STATUS_MODIFY:
6996 delete_local_mods = 1;
6997 break;
6998 case GOT_STATUS_MISSING:
6999 break;
7000 default:
7001 errx(1, "invalid status code '%c'",
7002 optarg[i]);
7005 status_codes = optarg;
7006 break;
7007 default:
7008 usage_remove();
7009 /* NOTREACHED */
7013 argc -= optind;
7014 argv += optind;
7016 #ifndef PROFILE
7017 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7018 NULL) == -1)
7019 err(1, "pledge");
7020 #endif
7021 if (argc < 1)
7022 usage_remove();
7024 cwd = getcwd(NULL, 0);
7025 if (cwd == NULL) {
7026 error = got_error_from_errno("getcwd");
7027 goto done;
7029 error = got_worktree_open(&worktree, cwd);
7030 if (error) {
7031 if (error->code == GOT_ERR_NOT_WORKTREE)
7032 error = wrap_not_worktree_error(error, "remove", cwd);
7033 goto done;
7036 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7037 NULL);
7038 if (error)
7039 goto done;
7041 error = apply_unveil(got_repo_get_path(repo), 1,
7042 got_worktree_get_root_path(worktree));
7043 if (error)
7044 goto done;
7046 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7047 if (error)
7048 goto done;
7050 if (!can_recurse) {
7051 char *ondisk_path;
7052 struct stat sb;
7053 TAILQ_FOREACH(pe, &paths, entry) {
7054 if (asprintf(&ondisk_path, "%s/%s",
7055 got_worktree_get_root_path(worktree),
7056 pe->path) == -1) {
7057 error = got_error_from_errno("asprintf");
7058 goto done;
7060 if (lstat(ondisk_path, &sb) == -1) {
7061 if (errno == ENOENT) {
7062 free(ondisk_path);
7063 continue;
7065 error = got_error_from_errno2("lstat",
7066 ondisk_path);
7067 free(ondisk_path);
7068 goto done;
7070 free(ondisk_path);
7071 if (S_ISDIR(sb.st_mode)) {
7072 error = got_error_msg(GOT_ERR_BAD_PATH,
7073 "removing directories requires -R option");
7074 goto done;
7079 error = got_worktree_schedule_delete(worktree, &paths,
7080 delete_local_mods, status_codes, print_remove_status, NULL,
7081 repo, keep_on_disk);
7082 done:
7083 if (repo) {
7084 const struct got_error *close_err = got_repo_close(repo);
7085 if (error == NULL)
7086 error = close_err;
7088 if (worktree)
7089 got_worktree_close(worktree);
7090 TAILQ_FOREACH(pe, &paths, entry)
7091 free((char *)pe->path);
7092 got_pathlist_free(&paths);
7093 free(cwd);
7094 return error;
7097 __dead static void
7098 usage_revert(void)
7100 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7101 "path ...\n", getprogname());
7102 exit(1);
7105 static const struct got_error *
7106 revert_progress(void *arg, unsigned char status, const char *path)
7108 if (status == GOT_STATUS_UNVERSIONED)
7109 return NULL;
7111 while (path[0] == '/')
7112 path++;
7113 printf("%c %s\n", status, path);
7114 return NULL;
7117 struct choose_patch_arg {
7118 FILE *patch_script_file;
7119 const char *action;
7122 static const struct got_error *
7123 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7124 int nchanges, const char *action)
7126 char *line = NULL;
7127 size_t linesize = 0;
7128 ssize_t linelen;
7130 switch (status) {
7131 case GOT_STATUS_ADD:
7132 printf("A %s\n%s this addition? [y/n] ", path, action);
7133 break;
7134 case GOT_STATUS_DELETE:
7135 printf("D %s\n%s this deletion? [y/n] ", path, action);
7136 break;
7137 case GOT_STATUS_MODIFY:
7138 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7139 return got_error_from_errno("fseek");
7140 printf(GOT_COMMIT_SEP_STR);
7141 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7142 printf("%s", line);
7143 if (ferror(patch_file))
7144 return got_error_from_errno("getline");
7145 printf(GOT_COMMIT_SEP_STR);
7146 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7147 path, n, nchanges, action);
7148 break;
7149 default:
7150 return got_error_path(path, GOT_ERR_FILE_STATUS);
7153 return NULL;
7156 static const struct got_error *
7157 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7158 FILE *patch_file, int n, int nchanges)
7160 const struct got_error *err = NULL;
7161 char *line = NULL;
7162 size_t linesize = 0;
7163 ssize_t linelen;
7164 int resp = ' ';
7165 struct choose_patch_arg *a = arg;
7167 *choice = GOT_PATCH_CHOICE_NONE;
7169 if (a->patch_script_file) {
7170 char *nl;
7171 err = show_change(status, path, patch_file, n, nchanges,
7172 a->action);
7173 if (err)
7174 return err;
7175 linelen = getline(&line, &linesize, a->patch_script_file);
7176 if (linelen == -1) {
7177 if (ferror(a->patch_script_file))
7178 return got_error_from_errno("getline");
7179 return NULL;
7181 nl = strchr(line, '\n');
7182 if (nl)
7183 *nl = '\0';
7184 if (strcmp(line, "y") == 0) {
7185 *choice = GOT_PATCH_CHOICE_YES;
7186 printf("y\n");
7187 } else if (strcmp(line, "n") == 0) {
7188 *choice = GOT_PATCH_CHOICE_NO;
7189 printf("n\n");
7190 } else if (strcmp(line, "q") == 0 &&
7191 status == GOT_STATUS_MODIFY) {
7192 *choice = GOT_PATCH_CHOICE_QUIT;
7193 printf("q\n");
7194 } else
7195 printf("invalid response '%s'\n", line);
7196 free(line);
7197 return NULL;
7200 while (resp != 'y' && resp != 'n' && resp != 'q') {
7201 err = show_change(status, path, patch_file, n, nchanges,
7202 a->action);
7203 if (err)
7204 return err;
7205 resp = getchar();
7206 if (resp == '\n')
7207 resp = getchar();
7208 if (status == GOT_STATUS_MODIFY) {
7209 if (resp != 'y' && resp != 'n' && resp != 'q') {
7210 printf("invalid response '%c'\n", resp);
7211 resp = ' ';
7213 } else if (resp != 'y' && resp != 'n') {
7214 printf("invalid response '%c'\n", resp);
7215 resp = ' ';
7219 if (resp == 'y')
7220 *choice = GOT_PATCH_CHOICE_YES;
7221 else if (resp == 'n')
7222 *choice = GOT_PATCH_CHOICE_NO;
7223 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7224 *choice = GOT_PATCH_CHOICE_QUIT;
7226 return NULL;
7230 static const struct got_error *
7231 cmd_revert(int argc, char *argv[])
7233 const struct got_error *error = NULL;
7234 struct got_worktree *worktree = NULL;
7235 struct got_repository *repo = NULL;
7236 char *cwd = NULL, *path = NULL;
7237 struct got_pathlist_head paths;
7238 struct got_pathlist_entry *pe;
7239 int ch, can_recurse = 0, pflag = 0;
7240 FILE *patch_script_file = NULL;
7241 const char *patch_script_path = NULL;
7242 struct choose_patch_arg cpa;
7244 TAILQ_INIT(&paths);
7246 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7247 switch (ch) {
7248 case 'p':
7249 pflag = 1;
7250 break;
7251 case 'F':
7252 patch_script_path = optarg;
7253 break;
7254 case 'R':
7255 can_recurse = 1;
7256 break;
7257 default:
7258 usage_revert();
7259 /* NOTREACHED */
7263 argc -= optind;
7264 argv += optind;
7266 #ifndef PROFILE
7267 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7268 "unveil", NULL) == -1)
7269 err(1, "pledge");
7270 #endif
7271 if (argc < 1)
7272 usage_revert();
7273 if (patch_script_path && !pflag)
7274 errx(1, "-F option can only be used together with -p option");
7276 cwd = getcwd(NULL, 0);
7277 if (cwd == NULL) {
7278 error = got_error_from_errno("getcwd");
7279 goto done;
7281 error = got_worktree_open(&worktree, cwd);
7282 if (error) {
7283 if (error->code == GOT_ERR_NOT_WORKTREE)
7284 error = wrap_not_worktree_error(error, "revert", cwd);
7285 goto done;
7288 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7289 NULL);
7290 if (error != NULL)
7291 goto done;
7293 if (patch_script_path) {
7294 patch_script_file = fopen(patch_script_path, "r");
7295 if (patch_script_file == NULL) {
7296 error = got_error_from_errno2("fopen",
7297 patch_script_path);
7298 goto done;
7301 error = apply_unveil(got_repo_get_path(repo), 1,
7302 got_worktree_get_root_path(worktree));
7303 if (error)
7304 goto done;
7306 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7307 if (error)
7308 goto done;
7310 if (!can_recurse) {
7311 char *ondisk_path;
7312 struct stat sb;
7313 TAILQ_FOREACH(pe, &paths, entry) {
7314 if (asprintf(&ondisk_path, "%s/%s",
7315 got_worktree_get_root_path(worktree),
7316 pe->path) == -1) {
7317 error = got_error_from_errno("asprintf");
7318 goto done;
7320 if (lstat(ondisk_path, &sb) == -1) {
7321 if (errno == ENOENT) {
7322 free(ondisk_path);
7323 continue;
7325 error = got_error_from_errno2("lstat",
7326 ondisk_path);
7327 free(ondisk_path);
7328 goto done;
7330 free(ondisk_path);
7331 if (S_ISDIR(sb.st_mode)) {
7332 error = got_error_msg(GOT_ERR_BAD_PATH,
7333 "reverting directories requires -R option");
7334 goto done;
7339 cpa.patch_script_file = patch_script_file;
7340 cpa.action = "revert";
7341 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7342 pflag ? choose_patch : NULL, &cpa, repo);
7343 done:
7344 if (patch_script_file && fclose(patch_script_file) == EOF &&
7345 error == NULL)
7346 error = got_error_from_errno2("fclose", patch_script_path);
7347 if (repo) {
7348 const struct got_error *close_err = got_repo_close(repo);
7349 if (error == NULL)
7350 error = close_err;
7352 if (worktree)
7353 got_worktree_close(worktree);
7354 free(path);
7355 free(cwd);
7356 return error;
7359 __dead static void
7360 usage_commit(void)
7362 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7363 "[path ...]\n", getprogname());
7364 exit(1);
7367 struct collect_commit_logmsg_arg {
7368 const char *cmdline_log;
7369 const char *prepared_log;
7370 int non_interactive;
7371 const char *editor;
7372 const char *worktree_path;
7373 const char *branch_name;
7374 const char *repo_path;
7375 char *logmsg_path;
7379 static const struct got_error *
7380 read_prepared_logmsg(char **logmsg, const char *path)
7382 const struct got_error *err = NULL;
7383 FILE *f = NULL;
7384 struct stat sb;
7385 size_t r;
7387 *logmsg = NULL;
7388 memset(&sb, 0, sizeof(sb));
7390 f = fopen(path, "r");
7391 if (f == NULL)
7392 return got_error_from_errno2("fopen", path);
7394 if (fstat(fileno(f), &sb) == -1) {
7395 err = got_error_from_errno2("fstat", path);
7396 goto done;
7398 if (sb.st_size == 0) {
7399 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7400 goto done;
7403 *logmsg = malloc(sb.st_size + 1);
7404 if (*logmsg == NULL) {
7405 err = got_error_from_errno("malloc");
7406 goto done;
7409 r = fread(*logmsg, 1, sb.st_size, f);
7410 if (r != sb.st_size) {
7411 if (ferror(f))
7412 err = got_error_from_errno2("fread", path);
7413 else
7414 err = got_error(GOT_ERR_IO);
7415 goto done;
7417 (*logmsg)[sb.st_size] = '\0';
7418 done:
7419 if (fclose(f) == EOF && err == NULL)
7420 err = got_error_from_errno2("fclose", path);
7421 if (err) {
7422 free(*logmsg);
7423 *logmsg = NULL;
7425 return err;
7429 static const struct got_error *
7430 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7431 void *arg)
7433 char *initial_content = NULL;
7434 struct got_pathlist_entry *pe;
7435 const struct got_error *err = NULL;
7436 char *template = NULL;
7437 struct collect_commit_logmsg_arg *a = arg;
7438 int initial_content_len;
7439 int fd = -1;
7440 size_t len;
7442 /* if a message was specified on the command line, just use it */
7443 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7444 len = strlen(a->cmdline_log) + 1;
7445 *logmsg = malloc(len + 1);
7446 if (*logmsg == NULL)
7447 return got_error_from_errno("malloc");
7448 strlcpy(*logmsg, a->cmdline_log, len);
7449 return NULL;
7450 } else if (a->prepared_log != NULL && a->non_interactive)
7451 return read_prepared_logmsg(logmsg, a->prepared_log);
7453 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7454 return got_error_from_errno("asprintf");
7456 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7457 if (err)
7458 goto done;
7460 if (a->prepared_log) {
7461 char *msg;
7462 err = read_prepared_logmsg(&msg, a->prepared_log);
7463 if (err)
7464 goto done;
7465 if (write(fd, msg, strlen(msg)) == -1) {
7466 err = got_error_from_errno2("write", a->logmsg_path);
7467 free(msg);
7468 goto done;
7470 free(msg);
7473 initial_content_len = asprintf(&initial_content,
7474 "\n# changes to be committed on branch %s:\n",
7475 a->branch_name);
7476 if (initial_content_len == -1) {
7477 err = got_error_from_errno("asprintf");
7478 goto done;
7481 if (write(fd, initial_content, initial_content_len) == -1) {
7482 err = got_error_from_errno2("write", a->logmsg_path);
7483 goto done;
7486 TAILQ_FOREACH(pe, commitable_paths, entry) {
7487 struct got_commitable *ct = pe->data;
7488 dprintf(fd, "# %c %s\n",
7489 got_commitable_get_status(ct),
7490 got_commitable_get_path(ct));
7493 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7494 initial_content_len, a->prepared_log ? 0 : 1);
7495 done:
7496 free(initial_content);
7497 free(template);
7499 if (fd != -1 && close(fd) == -1 && err == NULL)
7500 err = got_error_from_errno2("close", a->logmsg_path);
7502 /* Editor is done; we can now apply unveil(2) */
7503 if (err == NULL)
7504 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7505 if (err) {
7506 free(*logmsg);
7507 *logmsg = NULL;
7509 return err;
7512 static const struct got_error *
7513 cmd_commit(int argc, char *argv[])
7515 const struct got_error *error = NULL;
7516 struct got_worktree *worktree = NULL;
7517 struct got_repository *repo = NULL;
7518 char *cwd = NULL, *id_str = NULL;
7519 struct got_object_id *id = NULL;
7520 const char *logmsg = NULL;
7521 char *prepared_logmsg = NULL;
7522 struct collect_commit_logmsg_arg cl_arg;
7523 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7524 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7525 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7526 struct got_pathlist_head paths;
7528 TAILQ_INIT(&paths);
7529 cl_arg.logmsg_path = NULL;
7531 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7532 switch (ch) {
7533 case 'F':
7534 if (logmsg != NULL)
7535 option_conflict('F', 'm');
7536 prepared_logmsg = realpath(optarg, NULL);
7537 if (prepared_logmsg == NULL)
7538 return got_error_from_errno2("realpath",
7539 optarg);
7540 break;
7541 case 'm':
7542 if (prepared_logmsg)
7543 option_conflict('m', 'F');
7544 logmsg = optarg;
7545 break;
7546 case 'N':
7547 non_interactive = 1;
7548 break;
7549 case 'S':
7550 allow_bad_symlinks = 1;
7551 break;
7552 default:
7553 usage_commit();
7554 /* NOTREACHED */
7558 argc -= optind;
7559 argv += optind;
7561 #ifndef PROFILE
7562 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7563 "unveil", NULL) == -1)
7564 err(1, "pledge");
7565 #endif
7566 cwd = getcwd(NULL, 0);
7567 if (cwd == NULL) {
7568 error = got_error_from_errno("getcwd");
7569 goto done;
7571 error = got_worktree_open(&worktree, cwd);
7572 if (error) {
7573 if (error->code == GOT_ERR_NOT_WORKTREE)
7574 error = wrap_not_worktree_error(error, "commit", cwd);
7575 goto done;
7578 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7579 if (error)
7580 goto done;
7581 if (rebase_in_progress) {
7582 error = got_error(GOT_ERR_REBASING);
7583 goto done;
7586 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7587 worktree);
7588 if (error)
7589 goto done;
7591 error = get_gitconfig_path(&gitconfig_path);
7592 if (error)
7593 goto done;
7594 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7595 gitconfig_path);
7596 if (error != NULL)
7597 goto done;
7599 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7600 if (error)
7601 goto done;
7602 if (merge_in_progress) {
7603 error = got_error(GOT_ERR_MERGE_BUSY);
7604 goto done;
7607 error = get_author(&author, repo, worktree);
7608 if (error)
7609 return error;
7612 * unveil(2) traverses exec(2); if an editor is used we have
7613 * to apply unveil after the log message has been written.
7615 if (logmsg == NULL || strlen(logmsg) == 0)
7616 error = get_editor(&editor);
7617 else
7618 error = apply_unveil(got_repo_get_path(repo), 0,
7619 got_worktree_get_root_path(worktree));
7620 if (error)
7621 goto done;
7623 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7624 if (error)
7625 goto done;
7627 cl_arg.editor = editor;
7628 cl_arg.cmdline_log = logmsg;
7629 cl_arg.prepared_log = prepared_logmsg;
7630 cl_arg.non_interactive = non_interactive;
7631 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7632 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7633 if (!histedit_in_progress) {
7634 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7635 error = got_error(GOT_ERR_COMMIT_BRANCH);
7636 goto done;
7638 cl_arg.branch_name += 11;
7640 cl_arg.repo_path = got_repo_get_path(repo);
7641 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7642 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7643 print_status, NULL, repo);
7644 if (error) {
7645 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7646 cl_arg.logmsg_path != NULL)
7647 preserve_logmsg = 1;
7648 goto done;
7651 error = got_object_id_str(&id_str, id);
7652 if (error)
7653 goto done;
7654 printf("Created commit %s\n", id_str);
7655 done:
7656 if (preserve_logmsg) {
7657 fprintf(stderr, "%s: log message preserved in %s\n",
7658 getprogname(), cl_arg.logmsg_path);
7659 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7660 error == NULL)
7661 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7662 free(cl_arg.logmsg_path);
7663 if (repo) {
7664 const struct got_error *close_err = got_repo_close(repo);
7665 if (error == NULL)
7666 error = close_err;
7668 if (worktree)
7669 got_worktree_close(worktree);
7670 free(cwd);
7671 free(id_str);
7672 free(gitconfig_path);
7673 free(editor);
7674 free(author);
7675 free(prepared_logmsg);
7676 return error;
7679 __dead static void
7680 usage_send(void)
7682 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7683 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7684 "[remote-repository]\n", getprogname());
7685 exit(1);
7688 struct got_send_progress_arg {
7689 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7690 int verbosity;
7691 int last_ncommits;
7692 int last_nobj_total;
7693 int last_p_deltify;
7694 int last_p_written;
7695 int last_p_sent;
7696 int printed_something;
7697 int sent_something;
7698 struct got_pathlist_head *delete_branches;
7701 static const struct got_error *
7702 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7703 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7704 int success)
7706 struct got_send_progress_arg *a = arg;
7707 char scaled_packsize[FMT_SCALED_STRSIZE];
7708 char scaled_sent[FMT_SCALED_STRSIZE];
7709 int p_deltify = 0, p_written = 0, p_sent = 0;
7710 int print_searching = 0, print_total = 0;
7711 int print_deltify = 0, print_written = 0, print_sent = 0;
7713 if (a->verbosity < 0)
7714 return NULL;
7716 if (refname) {
7717 const char *status = success ? "accepted" : "rejected";
7719 if (success) {
7720 struct got_pathlist_entry *pe;
7721 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7722 const char *branchname = pe->path;
7723 if (got_path_cmp(branchname, refname,
7724 strlen(branchname), strlen(refname)) == 0) {
7725 status = "deleted";
7726 a->sent_something = 1;
7727 break;
7732 if (a->printed_something)
7733 putchar('\n');
7734 printf("Server has %s %s", status, refname);
7735 a->printed_something = 1;
7736 return NULL;
7739 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7740 return got_error_from_errno("fmt_scaled");
7741 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7742 return got_error_from_errno("fmt_scaled");
7744 if (a->last_ncommits != ncommits) {
7745 print_searching = 1;
7746 a->last_ncommits = ncommits;
7749 if (a->last_nobj_total != nobj_total) {
7750 print_searching = 1;
7751 print_total = 1;
7752 a->last_nobj_total = nobj_total;
7755 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7756 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7757 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7758 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7759 return got_error(GOT_ERR_NO_SPACE);
7762 if (nobj_deltify > 0 || nobj_written > 0) {
7763 if (nobj_deltify > 0) {
7764 p_deltify = (nobj_deltify * 100) / nobj_total;
7765 if (p_deltify != a->last_p_deltify) {
7766 a->last_p_deltify = p_deltify;
7767 print_searching = 1;
7768 print_total = 1;
7769 print_deltify = 1;
7772 if (nobj_written > 0) {
7773 p_written = (nobj_written * 100) / nobj_total;
7774 if (p_written != a->last_p_written) {
7775 a->last_p_written = p_written;
7776 print_searching = 1;
7777 print_total = 1;
7778 print_deltify = 1;
7779 print_written = 1;
7784 if (bytes_sent > 0) {
7785 p_sent = (bytes_sent * 100) / packfile_size;
7786 if (p_sent != a->last_p_sent) {
7787 a->last_p_sent = p_sent;
7788 print_searching = 1;
7789 print_total = 1;
7790 print_deltify = 1;
7791 print_written = 1;
7792 print_sent = 1;
7794 a->sent_something = 1;
7797 if (print_searching || print_total || print_deltify || print_written ||
7798 print_sent)
7799 printf("\r");
7800 if (print_searching)
7801 printf("packing %d reference%s", ncommits,
7802 ncommits == 1 ? "" : "s");
7803 if (print_total)
7804 printf("; %d object%s", nobj_total,
7805 nobj_total == 1 ? "" : "s");
7806 if (print_deltify)
7807 printf("; deltify: %d%%", p_deltify);
7808 if (print_sent)
7809 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7810 scaled_packsize, p_sent);
7811 else if (print_written)
7812 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7813 scaled_packsize, p_written);
7814 if (print_searching || print_total || print_deltify ||
7815 print_written || print_sent) {
7816 a->printed_something = 1;
7817 fflush(stdout);
7819 return NULL;
7822 static const struct got_error *
7823 cmd_send(int argc, char *argv[])
7825 const struct got_error *error = NULL;
7826 char *cwd = NULL, *repo_path = NULL;
7827 const char *remote_name;
7828 char *proto = NULL, *host = NULL, *port = NULL;
7829 char *repo_name = NULL, *server_path = NULL;
7830 const struct got_remote_repo *remotes, *remote = NULL;
7831 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7832 struct got_repository *repo = NULL;
7833 struct got_worktree *worktree = NULL;
7834 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7835 struct got_pathlist_head branches;
7836 struct got_pathlist_head tags;
7837 struct got_reflist_head all_branches;
7838 struct got_reflist_head all_tags;
7839 struct got_pathlist_head delete_args;
7840 struct got_pathlist_head delete_branches;
7841 struct got_reflist_entry *re;
7842 struct got_pathlist_entry *pe;
7843 int i, ch, sendfd = -1, sendstatus;
7844 pid_t sendpid = -1;
7845 struct got_send_progress_arg spa;
7846 int verbosity = 0, overwrite_refs = 0;
7847 int send_all_branches = 0, send_all_tags = 0;
7848 struct got_reference *ref = NULL;
7850 TAILQ_INIT(&branches);
7851 TAILQ_INIT(&tags);
7852 TAILQ_INIT(&all_branches);
7853 TAILQ_INIT(&all_tags);
7854 TAILQ_INIT(&delete_args);
7855 TAILQ_INIT(&delete_branches);
7857 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7858 switch (ch) {
7859 case 'a':
7860 send_all_branches = 1;
7861 break;
7862 case 'b':
7863 error = got_pathlist_append(&branches, optarg, NULL);
7864 if (error)
7865 return error;
7866 nbranches++;
7867 break;
7868 case 'd':
7869 error = got_pathlist_append(&delete_args, optarg, NULL);
7870 if (error)
7871 return error;
7872 break;
7873 case 'f':
7874 overwrite_refs = 1;
7875 break;
7876 case 'r':
7877 repo_path = realpath(optarg, NULL);
7878 if (repo_path == NULL)
7879 return got_error_from_errno2("realpath",
7880 optarg);
7881 got_path_strip_trailing_slashes(repo_path);
7882 break;
7883 case 't':
7884 error = got_pathlist_append(&tags, optarg, NULL);
7885 if (error)
7886 return error;
7887 ntags++;
7888 break;
7889 case 'T':
7890 send_all_tags = 1;
7891 break;
7892 case 'v':
7893 if (verbosity < 0)
7894 verbosity = 0;
7895 else if (verbosity < 3)
7896 verbosity++;
7897 break;
7898 case 'q':
7899 verbosity = -1;
7900 break;
7901 default:
7902 usage_send();
7903 /* NOTREACHED */
7906 argc -= optind;
7907 argv += optind;
7909 if (send_all_branches && !TAILQ_EMPTY(&branches))
7910 option_conflict('a', 'b');
7911 if (send_all_tags && !TAILQ_EMPTY(&tags))
7912 option_conflict('T', 't');
7915 if (argc == 0)
7916 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7917 else if (argc == 1)
7918 remote_name = argv[0];
7919 else
7920 usage_send();
7922 cwd = getcwd(NULL, 0);
7923 if (cwd == NULL) {
7924 error = got_error_from_errno("getcwd");
7925 goto done;
7928 if (repo_path == NULL) {
7929 error = got_worktree_open(&worktree, cwd);
7930 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7931 goto done;
7932 else
7933 error = NULL;
7934 if (worktree) {
7935 repo_path =
7936 strdup(got_worktree_get_repo_path(worktree));
7937 if (repo_path == NULL)
7938 error = got_error_from_errno("strdup");
7939 if (error)
7940 goto done;
7941 } else {
7942 repo_path = strdup(cwd);
7943 if (repo_path == NULL) {
7944 error = got_error_from_errno("strdup");
7945 goto done;
7950 error = got_repo_open(&repo, repo_path, NULL);
7951 if (error)
7952 goto done;
7954 if (worktree) {
7955 worktree_conf = got_worktree_get_gotconfig(worktree);
7956 if (worktree_conf) {
7957 got_gotconfig_get_remotes(&nremotes, &remotes,
7958 worktree_conf);
7959 for (i = 0; i < nremotes; i++) {
7960 if (strcmp(remotes[i].name, remote_name) == 0) {
7961 remote = &remotes[i];
7962 break;
7967 if (remote == NULL) {
7968 repo_conf = got_repo_get_gotconfig(repo);
7969 if (repo_conf) {
7970 got_gotconfig_get_remotes(&nremotes, &remotes,
7971 repo_conf);
7972 for (i = 0; i < nremotes; i++) {
7973 if (strcmp(remotes[i].name, remote_name) == 0) {
7974 remote = &remotes[i];
7975 break;
7980 if (remote == NULL) {
7981 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7982 for (i = 0; i < nremotes; i++) {
7983 if (strcmp(remotes[i].name, remote_name) == 0) {
7984 remote = &remotes[i];
7985 break;
7989 if (remote == NULL) {
7990 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7991 goto done;
7994 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7995 &repo_name, remote->send_url);
7996 if (error)
7997 goto done;
7999 if (strcmp(proto, "git") == 0) {
8000 #ifndef PROFILE
8001 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8002 "sendfd dns inet unveil", NULL) == -1)
8003 err(1, "pledge");
8004 #endif
8005 } else if (strcmp(proto, "git+ssh") == 0 ||
8006 strcmp(proto, "ssh") == 0) {
8007 #ifndef PROFILE
8008 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8009 "sendfd unveil", NULL) == -1)
8010 err(1, "pledge");
8011 #endif
8012 } else if (strcmp(proto, "http") == 0 ||
8013 strcmp(proto, "git+http") == 0) {
8014 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8015 goto done;
8016 } else {
8017 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8018 goto done;
8021 error = got_dial_apply_unveil(proto);
8022 if (error)
8023 goto done;
8025 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8026 if (error)
8027 goto done;
8029 if (send_all_branches) {
8030 error = got_ref_list(&all_branches, repo, "refs/heads",
8031 got_ref_cmp_by_name, NULL);
8032 if (error)
8033 goto done;
8034 TAILQ_FOREACH(re, &all_branches, entry) {
8035 const char *branchname = got_ref_get_name(re->ref);
8036 error = got_pathlist_append(&branches,
8037 branchname, NULL);
8038 if (error)
8039 goto done;
8040 nbranches++;
8042 } else if (nbranches == 0) {
8043 for (i = 0; i < remote->nsend_branches; i++) {
8044 got_pathlist_append(&branches,
8045 remote->send_branches[i], NULL);
8049 if (send_all_tags) {
8050 error = got_ref_list(&all_tags, repo, "refs/tags",
8051 got_ref_cmp_by_name, NULL);
8052 if (error)
8053 goto done;
8054 TAILQ_FOREACH(re, &all_tags, entry) {
8055 const char *tagname = got_ref_get_name(re->ref);
8056 error = got_pathlist_append(&tags,
8057 tagname, NULL);
8058 if (error)
8059 goto done;
8060 ntags++;
8065 * To prevent accidents only branches in refs/heads/ can be deleted
8066 * with 'got send -d'.
8067 * Deleting anything else requires local repository access or Git.
8069 TAILQ_FOREACH(pe, &delete_args, entry) {
8070 const char *branchname = pe->path;
8071 char *s;
8072 struct got_pathlist_entry *new;
8073 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8074 s = strdup(branchname);
8075 if (s == NULL) {
8076 error = got_error_from_errno("strdup");
8077 goto done;
8079 } else {
8080 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8081 error = got_error_from_errno("asprintf");
8082 goto done;
8085 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8086 if (error || new == NULL /* duplicate */)
8087 free(s);
8088 if (error)
8089 goto done;
8090 ndelete_branches++;
8093 if (nbranches == 0 && ndelete_branches == 0) {
8094 struct got_reference *head_ref;
8095 if (worktree)
8096 error = got_ref_open(&head_ref, repo,
8097 got_worktree_get_head_ref_name(worktree), 0);
8098 else
8099 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8100 if (error)
8101 goto done;
8102 if (got_ref_is_symbolic(head_ref)) {
8103 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8104 got_ref_close(head_ref);
8105 if (error)
8106 goto done;
8107 } else
8108 ref = head_ref;
8109 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8110 NULL);
8111 if (error)
8112 goto done;
8113 nbranches++;
8116 if (verbosity >= 0)
8117 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8118 port ? ":" : "", port ? port : "");
8120 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8121 server_path, verbosity);
8122 if (error)
8123 goto done;
8125 memset(&spa, 0, sizeof(spa));
8126 spa.last_scaled_packsize[0] = '\0';
8127 spa.last_p_deltify = -1;
8128 spa.last_p_written = -1;
8129 spa.verbosity = verbosity;
8130 spa.delete_branches = &delete_branches;
8131 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8132 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8133 check_cancelled, NULL);
8134 if (spa.printed_something)
8135 putchar('\n');
8136 if (error)
8137 goto done;
8138 if (!spa.sent_something && verbosity >= 0)
8139 printf("Already up-to-date\n");
8140 done:
8141 if (sendpid > 0) {
8142 if (kill(sendpid, SIGTERM) == -1)
8143 error = got_error_from_errno("kill");
8144 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8145 error = got_error_from_errno("waitpid");
8147 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8148 error = got_error_from_errno("close");
8149 if (repo) {
8150 const struct got_error *close_err = got_repo_close(repo);
8151 if (error == NULL)
8152 error = close_err;
8154 if (worktree)
8155 got_worktree_close(worktree);
8156 if (ref)
8157 got_ref_close(ref);
8158 got_pathlist_free(&branches);
8159 got_pathlist_free(&tags);
8160 got_ref_list_free(&all_branches);
8161 got_ref_list_free(&all_tags);
8162 got_pathlist_free(&delete_args);
8163 TAILQ_FOREACH(pe, &delete_branches, entry)
8164 free((char *)pe->path);
8165 got_pathlist_free(&delete_branches);
8166 free(cwd);
8167 free(repo_path);
8168 free(proto);
8169 free(host);
8170 free(port);
8171 free(server_path);
8172 free(repo_name);
8173 return error;
8176 __dead static void
8177 usage_cherrypick(void)
8179 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8180 exit(1);
8183 static const struct got_error *
8184 cmd_cherrypick(int argc, char *argv[])
8186 const struct got_error *error = NULL;
8187 struct got_worktree *worktree = NULL;
8188 struct got_repository *repo = NULL;
8189 char *cwd = NULL, *commit_id_str = NULL;
8190 struct got_object_id *commit_id = NULL;
8191 struct got_commit_object *commit = NULL;
8192 struct got_object_qid *pid;
8193 int ch;
8194 struct got_update_progress_arg upa;
8196 while ((ch = getopt(argc, argv, "")) != -1) {
8197 switch (ch) {
8198 default:
8199 usage_cherrypick();
8200 /* NOTREACHED */
8204 argc -= optind;
8205 argv += optind;
8207 #ifndef PROFILE
8208 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8209 "unveil", NULL) == -1)
8210 err(1, "pledge");
8211 #endif
8212 if (argc != 1)
8213 usage_cherrypick();
8215 cwd = getcwd(NULL, 0);
8216 if (cwd == NULL) {
8217 error = got_error_from_errno("getcwd");
8218 goto done;
8220 error = got_worktree_open(&worktree, cwd);
8221 if (error) {
8222 if (error->code == GOT_ERR_NOT_WORKTREE)
8223 error = wrap_not_worktree_error(error, "cherrypick",
8224 cwd);
8225 goto done;
8228 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8229 NULL);
8230 if (error != NULL)
8231 goto done;
8233 error = apply_unveil(got_repo_get_path(repo), 0,
8234 got_worktree_get_root_path(worktree));
8235 if (error)
8236 goto done;
8238 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8239 GOT_OBJ_TYPE_COMMIT, repo);
8240 if (error != NULL) {
8241 struct got_reference *ref;
8242 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8243 goto done;
8244 error = got_ref_open(&ref, repo, argv[0], 0);
8245 if (error != NULL)
8246 goto done;
8247 error = got_ref_resolve(&commit_id, repo, ref);
8248 got_ref_close(ref);
8249 if (error != NULL)
8250 goto done;
8252 error = got_object_id_str(&commit_id_str, commit_id);
8253 if (error)
8254 goto done;
8256 error = got_object_open_as_commit(&commit, repo, commit_id);
8257 if (error)
8258 goto done;
8259 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8260 memset(&upa, 0, sizeof(upa));
8261 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8262 commit_id, repo, update_progress, &upa, check_cancelled,
8263 NULL);
8264 if (error != NULL)
8265 goto done;
8267 if (upa.did_something)
8268 printf("Merged commit %s\n", commit_id_str);
8269 print_merge_progress_stats(&upa);
8270 done:
8271 if (commit)
8272 got_object_commit_close(commit);
8273 free(commit_id_str);
8274 if (worktree)
8275 got_worktree_close(worktree);
8276 if (repo) {
8277 const struct got_error *close_err = got_repo_close(repo);
8278 if (error == NULL)
8279 error = close_err;
8281 return error;
8284 __dead static void
8285 usage_backout(void)
8287 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8288 exit(1);
8291 static const struct got_error *
8292 cmd_backout(int argc, char *argv[])
8294 const struct got_error *error = NULL;
8295 struct got_worktree *worktree = NULL;
8296 struct got_repository *repo = NULL;
8297 char *cwd = NULL, *commit_id_str = NULL;
8298 struct got_object_id *commit_id = NULL;
8299 struct got_commit_object *commit = NULL;
8300 struct got_object_qid *pid;
8301 int ch;
8302 struct got_update_progress_arg upa;
8304 while ((ch = getopt(argc, argv, "")) != -1) {
8305 switch (ch) {
8306 default:
8307 usage_backout();
8308 /* NOTREACHED */
8312 argc -= optind;
8313 argv += optind;
8315 #ifndef PROFILE
8316 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8317 "unveil", NULL) == -1)
8318 err(1, "pledge");
8319 #endif
8320 if (argc != 1)
8321 usage_backout();
8323 cwd = getcwd(NULL, 0);
8324 if (cwd == NULL) {
8325 error = got_error_from_errno("getcwd");
8326 goto done;
8328 error = got_worktree_open(&worktree, cwd);
8329 if (error) {
8330 if (error->code == GOT_ERR_NOT_WORKTREE)
8331 error = wrap_not_worktree_error(error, "backout", cwd);
8332 goto done;
8335 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8336 NULL);
8337 if (error != NULL)
8338 goto done;
8340 error = apply_unveil(got_repo_get_path(repo), 0,
8341 got_worktree_get_root_path(worktree));
8342 if (error)
8343 goto done;
8345 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8346 GOT_OBJ_TYPE_COMMIT, repo);
8347 if (error != NULL) {
8348 struct got_reference *ref;
8349 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8350 goto done;
8351 error = got_ref_open(&ref, repo, argv[0], 0);
8352 if (error != NULL)
8353 goto done;
8354 error = got_ref_resolve(&commit_id, repo, ref);
8355 got_ref_close(ref);
8356 if (error != NULL)
8357 goto done;
8359 error = got_object_id_str(&commit_id_str, commit_id);
8360 if (error)
8361 goto done;
8363 error = got_object_open_as_commit(&commit, repo, commit_id);
8364 if (error)
8365 goto done;
8366 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8367 if (pid == NULL) {
8368 error = got_error(GOT_ERR_ROOT_COMMIT);
8369 goto done;
8372 memset(&upa, 0, sizeof(upa));
8373 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8374 repo, update_progress, &upa, check_cancelled, NULL);
8375 if (error != NULL)
8376 goto done;
8378 if (upa.did_something)
8379 printf("Backed out commit %s\n", commit_id_str);
8380 print_merge_progress_stats(&upa);
8381 done:
8382 if (commit)
8383 got_object_commit_close(commit);
8384 free(commit_id_str);
8385 if (worktree)
8386 got_worktree_close(worktree);
8387 if (repo) {
8388 const struct got_error *close_err = got_repo_close(repo);
8389 if (error == NULL)
8390 error = close_err;
8392 return error;
8395 __dead static void
8396 usage_rebase(void)
8398 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8399 getprogname());
8400 exit(1);
8403 void
8404 trim_logmsg(char *logmsg, int limit)
8406 char *nl;
8407 size_t len;
8409 len = strlen(logmsg);
8410 if (len > limit)
8411 len = limit;
8412 logmsg[len] = '\0';
8413 nl = strchr(logmsg, '\n');
8414 if (nl)
8415 *nl = '\0';
8418 static const struct got_error *
8419 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8421 const struct got_error *err;
8422 char *logmsg0 = NULL;
8423 const char *s;
8425 err = got_object_commit_get_logmsg(&logmsg0, commit);
8426 if (err)
8427 return err;
8429 s = logmsg0;
8430 while (isspace((unsigned char)s[0]))
8431 s++;
8433 *logmsg = strdup(s);
8434 if (*logmsg == NULL) {
8435 err = got_error_from_errno("strdup");
8436 goto done;
8439 trim_logmsg(*logmsg, limit);
8440 done:
8441 free(logmsg0);
8442 return err;
8445 static const struct got_error *
8446 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8448 const struct got_error *err;
8449 struct got_commit_object *commit = NULL;
8450 char *id_str = NULL, *logmsg = NULL;
8452 err = got_object_open_as_commit(&commit, repo, id);
8453 if (err)
8454 return err;
8456 err = got_object_id_str(&id_str, id);
8457 if (err)
8458 goto done;
8460 id_str[12] = '\0';
8462 err = get_short_logmsg(&logmsg, 42, commit);
8463 if (err)
8464 goto done;
8466 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8467 done:
8468 free(id_str);
8469 got_object_commit_close(commit);
8470 free(logmsg);
8471 return err;
8474 static const struct got_error *
8475 show_rebase_progress(struct got_commit_object *commit,
8476 struct got_object_id *old_id, struct got_object_id *new_id)
8478 const struct got_error *err;
8479 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8481 err = got_object_id_str(&old_id_str, old_id);
8482 if (err)
8483 goto done;
8485 if (new_id) {
8486 err = got_object_id_str(&new_id_str, new_id);
8487 if (err)
8488 goto done;
8491 old_id_str[12] = '\0';
8492 if (new_id_str)
8493 new_id_str[12] = '\0';
8495 err = get_short_logmsg(&logmsg, 42, commit);
8496 if (err)
8497 goto done;
8499 printf("%s -> %s: %s\n", old_id_str,
8500 new_id_str ? new_id_str : "no-op change", logmsg);
8501 done:
8502 free(old_id_str);
8503 free(new_id_str);
8504 free(logmsg);
8505 return err;
8508 static const struct got_error *
8509 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8510 struct got_reference *branch, struct got_reference *new_base_branch,
8511 struct got_reference *tmp_branch, struct got_repository *repo,
8512 int create_backup)
8514 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8515 return got_worktree_rebase_complete(worktree, fileindex,
8516 new_base_branch, tmp_branch, branch, repo, create_backup);
8519 static const struct got_error *
8520 rebase_commit(struct got_pathlist_head *merged_paths,
8521 struct got_worktree *worktree, struct got_fileindex *fileindex,
8522 struct got_reference *tmp_branch,
8523 struct got_object_id *commit_id, struct got_repository *repo)
8525 const struct got_error *error;
8526 struct got_commit_object *commit;
8527 struct got_object_id *new_commit_id;
8529 error = got_object_open_as_commit(&commit, repo, commit_id);
8530 if (error)
8531 return error;
8533 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8534 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8535 if (error) {
8536 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8537 goto done;
8538 error = show_rebase_progress(commit, commit_id, NULL);
8539 } else {
8540 error = show_rebase_progress(commit, commit_id, new_commit_id);
8541 free(new_commit_id);
8543 done:
8544 got_object_commit_close(commit);
8545 return error;
8548 struct check_path_prefix_arg {
8549 const char *path_prefix;
8550 size_t len;
8551 int errcode;
8554 static const struct got_error *
8555 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8556 struct got_blob_object *blob2, struct got_object_id *id1,
8557 struct got_object_id *id2, const char *path1, const char *path2,
8558 mode_t mode1, mode_t mode2, struct got_repository *repo)
8560 struct check_path_prefix_arg *a = arg;
8562 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8563 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8564 return got_error(a->errcode);
8566 return NULL;
8569 static const struct got_error *
8570 check_path_prefix(struct got_object_id *parent_id,
8571 struct got_object_id *commit_id, const char *path_prefix,
8572 int errcode, struct got_repository *repo)
8574 const struct got_error *err;
8575 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8576 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8577 struct check_path_prefix_arg cpp_arg;
8579 if (got_path_is_root_dir(path_prefix))
8580 return NULL;
8582 err = got_object_open_as_commit(&commit, repo, commit_id);
8583 if (err)
8584 goto done;
8586 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8587 if (err)
8588 goto done;
8590 err = got_object_open_as_tree(&tree1, repo,
8591 got_object_commit_get_tree_id(parent_commit));
8592 if (err)
8593 goto done;
8595 err = got_object_open_as_tree(&tree2, repo,
8596 got_object_commit_get_tree_id(commit));
8597 if (err)
8598 goto done;
8600 cpp_arg.path_prefix = path_prefix;
8601 while (cpp_arg.path_prefix[0] == '/')
8602 cpp_arg.path_prefix++;
8603 cpp_arg.len = strlen(cpp_arg.path_prefix);
8604 cpp_arg.errcode = errcode;
8605 err = got_diff_tree(tree1, tree2, "", "", repo,
8606 check_path_prefix_in_diff, &cpp_arg, 0);
8607 done:
8608 if (tree1)
8609 got_object_tree_close(tree1);
8610 if (tree2)
8611 got_object_tree_close(tree2);
8612 if (commit)
8613 got_object_commit_close(commit);
8614 if (parent_commit)
8615 got_object_commit_close(parent_commit);
8616 return err;
8619 static const struct got_error *
8620 collect_commits(struct got_object_id_queue *commits,
8621 struct got_object_id *initial_commit_id,
8622 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8623 const char *path_prefix, int path_prefix_errcode,
8624 struct got_repository *repo)
8626 const struct got_error *err = NULL;
8627 struct got_commit_graph *graph = NULL;
8628 struct got_object_id *parent_id = NULL;
8629 struct got_object_qid *qid;
8630 struct got_object_id *commit_id = initial_commit_id;
8632 err = got_commit_graph_open(&graph, "/", 1);
8633 if (err)
8634 return err;
8636 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8637 check_cancelled, NULL);
8638 if (err)
8639 goto done;
8640 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8641 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8642 check_cancelled, NULL);
8643 if (err) {
8644 if (err->code == GOT_ERR_ITER_COMPLETED) {
8645 err = got_error_msg(GOT_ERR_ANCESTRY,
8646 "ran out of commits to rebase before "
8647 "youngest common ancestor commit has "
8648 "been reached?!?");
8650 goto done;
8651 } else {
8652 err = check_path_prefix(parent_id, commit_id,
8653 path_prefix, path_prefix_errcode, repo);
8654 if (err)
8655 goto done;
8657 err = got_object_qid_alloc(&qid, commit_id);
8658 if (err)
8659 goto done;
8660 STAILQ_INSERT_HEAD(commits, qid, entry);
8661 commit_id = parent_id;
8664 done:
8665 got_commit_graph_close(graph);
8666 return err;
8669 static const struct got_error *
8670 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8672 const struct got_error *err = NULL;
8673 time_t committer_time;
8674 struct tm tm;
8675 char datebuf[11]; /* YYYY-MM-DD + NUL */
8676 char *author0 = NULL, *author, *smallerthan;
8677 char *logmsg0 = NULL, *logmsg, *newline;
8679 committer_time = got_object_commit_get_committer_time(commit);
8680 if (gmtime_r(&committer_time, &tm) == NULL)
8681 return got_error_from_errno("gmtime_r");
8682 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8683 return got_error(GOT_ERR_NO_SPACE);
8685 author0 = strdup(got_object_commit_get_author(commit));
8686 if (author0 == NULL)
8687 return got_error_from_errno("strdup");
8688 author = author0;
8689 smallerthan = strchr(author, '<');
8690 if (smallerthan && smallerthan[1] != '\0')
8691 author = smallerthan + 1;
8692 author[strcspn(author, "@>")] = '\0';
8694 err = got_object_commit_get_logmsg(&logmsg0, commit);
8695 if (err)
8696 goto done;
8697 logmsg = logmsg0;
8698 while (*logmsg == '\n')
8699 logmsg++;
8700 newline = strchr(logmsg, '\n');
8701 if (newline)
8702 *newline = '\0';
8704 if (asprintf(brief_str, "%s %s %s",
8705 datebuf, author, logmsg) == -1)
8706 err = got_error_from_errno("asprintf");
8707 done:
8708 free(author0);
8709 free(logmsg0);
8710 return err;
8713 static const struct got_error *
8714 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8715 struct got_repository *repo)
8717 const struct got_error *err;
8718 char *id_str;
8720 err = got_object_id_str(&id_str, id);
8721 if (err)
8722 return err;
8724 err = got_ref_delete(ref, repo);
8725 if (err)
8726 goto done;
8728 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8729 done:
8730 free(id_str);
8731 return err;
8734 static const struct got_error *
8735 print_backup_ref(const char *branch_name, const char *new_id_str,
8736 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8737 struct got_reflist_object_id_map *refs_idmap,
8738 struct got_repository *repo)
8740 const struct got_error *err = NULL;
8741 struct got_reflist_head *refs;
8742 char *refs_str = NULL;
8743 struct got_object_id *new_commit_id = NULL;
8744 struct got_commit_object *new_commit = NULL;
8745 char *new_commit_brief_str = NULL;
8746 struct got_object_id *yca_id = NULL;
8747 struct got_commit_object *yca_commit = NULL;
8748 char *yca_id_str = NULL, *yca_brief_str = NULL;
8749 char *custom_refs_str;
8751 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8752 return got_error_from_errno("asprintf");
8754 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8755 0, 0, refs_idmap, custom_refs_str);
8756 if (err)
8757 goto done;
8759 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8760 if (err)
8761 goto done;
8763 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8764 if (refs) {
8765 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8766 if (err)
8767 goto done;
8770 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8771 if (err)
8772 goto done;
8774 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8775 if (err)
8776 goto done;
8778 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8779 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
8780 if (err)
8781 goto done;
8783 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8784 refs_str ? " (" : "", refs_str ? refs_str : "",
8785 refs_str ? ")" : "", new_commit_brief_str);
8786 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8787 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8788 free(refs_str);
8789 refs_str = NULL;
8791 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8792 if (err)
8793 goto done;
8795 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8796 if (err)
8797 goto done;
8799 err = got_object_id_str(&yca_id_str, yca_id);
8800 if (err)
8801 goto done;
8803 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8804 if (refs) {
8805 err = build_refs_str(&refs_str, refs, yca_id, repo);
8806 if (err)
8807 goto done;
8809 printf("history forked at %s%s%s%s\n %s\n",
8810 yca_id_str,
8811 refs_str ? " (" : "", refs_str ? refs_str : "",
8812 refs_str ? ")" : "", yca_brief_str);
8814 done:
8815 free(custom_refs_str);
8816 free(new_commit_id);
8817 free(refs_str);
8818 free(yca_id);
8819 free(yca_id_str);
8820 free(yca_brief_str);
8821 if (new_commit)
8822 got_object_commit_close(new_commit);
8823 if (yca_commit)
8824 got_object_commit_close(yca_commit);
8826 return NULL;
8829 static const struct got_error *
8830 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8831 int delete, struct got_repository *repo)
8833 const struct got_error *err;
8834 struct got_reflist_head refs, backup_refs;
8835 struct got_reflist_entry *re;
8836 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8837 struct got_object_id *old_commit_id = NULL;
8838 char *branch_name = NULL;
8839 struct got_commit_object *old_commit = NULL;
8840 struct got_reflist_object_id_map *refs_idmap = NULL;
8841 int wanted_branch_found = 0;
8843 TAILQ_INIT(&refs);
8844 TAILQ_INIT(&backup_refs);
8846 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8847 if (err)
8848 return err;
8850 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8851 if (err)
8852 goto done;
8854 if (wanted_branch_name) {
8855 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8856 wanted_branch_name += 11;
8859 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8860 got_ref_cmp_by_commit_timestamp_descending, repo);
8861 if (err)
8862 goto done;
8864 TAILQ_FOREACH(re, &backup_refs, entry) {
8865 const char *refname = got_ref_get_name(re->ref);
8866 char *slash;
8868 err = check_cancelled(NULL);
8869 if (err)
8870 break;
8872 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8873 if (err)
8874 break;
8876 err = got_object_open_as_commit(&old_commit, repo,
8877 old_commit_id);
8878 if (err)
8879 break;
8881 if (strncmp(backup_ref_prefix, refname,
8882 backup_ref_prefix_len) == 0)
8883 refname += backup_ref_prefix_len;
8885 while (refname[0] == '/')
8886 refname++;
8888 branch_name = strdup(refname);
8889 if (branch_name == NULL) {
8890 err = got_error_from_errno("strdup");
8891 break;
8893 slash = strrchr(branch_name, '/');
8894 if (slash) {
8895 *slash = '\0';
8896 refname += strlen(branch_name) + 1;
8899 if (wanted_branch_name == NULL ||
8900 strcmp(wanted_branch_name, branch_name) == 0) {
8901 wanted_branch_found = 1;
8902 if (delete) {
8903 err = delete_backup_ref(re->ref,
8904 old_commit_id, repo);
8905 } else {
8906 err = print_backup_ref(branch_name, refname,
8907 old_commit_id, old_commit, refs_idmap,
8908 repo);
8910 if (err)
8911 break;
8914 free(old_commit_id);
8915 old_commit_id = NULL;
8916 free(branch_name);
8917 branch_name = NULL;
8918 got_object_commit_close(old_commit);
8919 old_commit = NULL;
8922 if (wanted_branch_name && !wanted_branch_found) {
8923 err = got_error_fmt(GOT_ERR_NOT_REF,
8924 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8926 done:
8927 if (refs_idmap)
8928 got_reflist_object_id_map_free(refs_idmap);
8929 got_ref_list_free(&refs);
8930 got_ref_list_free(&backup_refs);
8931 free(old_commit_id);
8932 free(branch_name);
8933 if (old_commit)
8934 got_object_commit_close(old_commit);
8935 return err;
8938 static const struct got_error *
8939 abort_progress(void *arg, unsigned char status, const char *path)
8942 * Unversioned files should not clutter progress output when
8943 * an operation is aborted.
8945 if (status == GOT_STATUS_UNVERSIONED)
8946 return NULL;
8948 return update_progress(arg, status, path);
8951 static const struct got_error *
8952 cmd_rebase(int argc, char *argv[])
8954 const struct got_error *error = NULL;
8955 struct got_worktree *worktree = NULL;
8956 struct got_repository *repo = NULL;
8957 struct got_fileindex *fileindex = NULL;
8958 char *cwd = NULL;
8959 struct got_reference *branch = NULL;
8960 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8961 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8962 struct got_object_id *resume_commit_id = NULL;
8963 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8964 struct got_commit_object *commit = NULL;
8965 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8966 int histedit_in_progress = 0, merge_in_progress = 0;
8967 int create_backup = 1, list_backups = 0, delete_backups = 0;
8968 struct got_object_id_queue commits;
8969 struct got_pathlist_head merged_paths;
8970 const struct got_object_id_queue *parent_ids;
8971 struct got_object_qid *qid, *pid;
8972 struct got_update_progress_arg upa;
8974 STAILQ_INIT(&commits);
8975 TAILQ_INIT(&merged_paths);
8976 memset(&upa, 0, sizeof(upa));
8978 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8979 switch (ch) {
8980 case 'a':
8981 abort_rebase = 1;
8982 break;
8983 case 'c':
8984 continue_rebase = 1;
8985 break;
8986 case 'l':
8987 list_backups = 1;
8988 break;
8989 case 'X':
8990 delete_backups = 1;
8991 break;
8992 default:
8993 usage_rebase();
8994 /* NOTREACHED */
8998 argc -= optind;
8999 argv += optind;
9001 #ifndef PROFILE
9002 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9003 "unveil", NULL) == -1)
9004 err(1, "pledge");
9005 #endif
9006 if (list_backups) {
9007 if (abort_rebase)
9008 option_conflict('l', 'a');
9009 if (continue_rebase)
9010 option_conflict('l', 'c');
9011 if (delete_backups)
9012 option_conflict('l', 'X');
9013 if (argc != 0 && argc != 1)
9014 usage_rebase();
9015 } else if (delete_backups) {
9016 if (abort_rebase)
9017 option_conflict('X', 'a');
9018 if (continue_rebase)
9019 option_conflict('X', 'c');
9020 if (list_backups)
9021 option_conflict('l', 'X');
9022 if (argc != 0 && argc != 1)
9023 usage_rebase();
9024 } else {
9025 if (abort_rebase && continue_rebase)
9026 usage_rebase();
9027 else if (abort_rebase || continue_rebase) {
9028 if (argc != 0)
9029 usage_rebase();
9030 } else if (argc != 1)
9031 usage_rebase();
9034 cwd = getcwd(NULL, 0);
9035 if (cwd == NULL) {
9036 error = got_error_from_errno("getcwd");
9037 goto done;
9039 error = got_worktree_open(&worktree, cwd);
9040 if (error) {
9041 if (list_backups || delete_backups) {
9042 if (error->code != GOT_ERR_NOT_WORKTREE)
9043 goto done;
9044 } else {
9045 if (error->code == GOT_ERR_NOT_WORKTREE)
9046 error = wrap_not_worktree_error(error,
9047 "rebase", cwd);
9048 goto done;
9052 error = got_repo_open(&repo,
9053 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9054 if (error != NULL)
9055 goto done;
9057 error = apply_unveil(got_repo_get_path(repo), 0,
9058 worktree ? got_worktree_get_root_path(worktree) : NULL);
9059 if (error)
9060 goto done;
9062 if (list_backups || delete_backups) {
9063 error = process_backup_refs(
9064 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9065 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9066 goto done; /* nothing else to do */
9069 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9070 worktree);
9071 if (error)
9072 goto done;
9073 if (histedit_in_progress) {
9074 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9075 goto done;
9078 error = got_worktree_merge_in_progress(&merge_in_progress,
9079 worktree, repo);
9080 if (error)
9081 goto done;
9082 if (merge_in_progress) {
9083 error = got_error(GOT_ERR_MERGE_BUSY);
9084 goto done;
9087 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9088 if (error)
9089 goto done;
9091 if (abort_rebase) {
9092 if (!rebase_in_progress) {
9093 error = got_error(GOT_ERR_NOT_REBASING);
9094 goto done;
9096 error = got_worktree_rebase_continue(&resume_commit_id,
9097 &new_base_branch, &tmp_branch, &branch, &fileindex,
9098 worktree, repo);
9099 if (error)
9100 goto done;
9101 printf("Switching work tree to %s\n",
9102 got_ref_get_symref_target(new_base_branch));
9103 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9104 new_base_branch, abort_progress, &upa);
9105 if (error)
9106 goto done;
9107 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9108 print_merge_progress_stats(&upa);
9109 goto done; /* nothing else to do */
9112 if (continue_rebase) {
9113 if (!rebase_in_progress) {
9114 error = got_error(GOT_ERR_NOT_REBASING);
9115 goto done;
9117 error = got_worktree_rebase_continue(&resume_commit_id,
9118 &new_base_branch, &tmp_branch, &branch, &fileindex,
9119 worktree, repo);
9120 if (error)
9121 goto done;
9123 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9124 resume_commit_id, repo);
9125 if (error)
9126 goto done;
9128 yca_id = got_object_id_dup(resume_commit_id);
9129 if (yca_id == NULL) {
9130 error = got_error_from_errno("got_object_id_dup");
9131 goto done;
9133 } else {
9134 error = got_ref_open(&branch, repo, argv[0], 0);
9135 if (error != NULL)
9136 goto done;
9139 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9140 if (error)
9141 goto done;
9143 if (!continue_rebase) {
9144 struct got_object_id *base_commit_id;
9146 base_commit_id = got_worktree_get_base_commit_id(worktree);
9147 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9148 base_commit_id, branch_head_commit_id, 1, repo,
9149 check_cancelled, NULL);
9150 if (error)
9151 goto done;
9152 if (yca_id == NULL) {
9153 error = got_error_msg(GOT_ERR_ANCESTRY,
9154 "specified branch shares no common ancestry "
9155 "with work tree's branch");
9156 goto done;
9159 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9160 if (error) {
9161 if (error->code != GOT_ERR_ANCESTRY)
9162 goto done;
9163 error = NULL;
9164 } else {
9165 struct got_pathlist_head paths;
9166 printf("%s is already based on %s\n",
9167 got_ref_get_name(branch),
9168 got_worktree_get_head_ref_name(worktree));
9169 error = switch_head_ref(branch, branch_head_commit_id,
9170 worktree, repo);
9171 if (error)
9172 goto done;
9173 error = got_worktree_set_base_commit_id(worktree, repo,
9174 branch_head_commit_id);
9175 if (error)
9176 goto done;
9177 TAILQ_INIT(&paths);
9178 error = got_pathlist_append(&paths, "", NULL);
9179 if (error)
9180 goto done;
9181 error = got_worktree_checkout_files(worktree,
9182 &paths, repo, update_progress, &upa,
9183 check_cancelled, NULL);
9184 got_pathlist_free(&paths);
9185 if (error)
9186 goto done;
9187 if (upa.did_something) {
9188 char *id_str;
9189 error = got_object_id_str(&id_str,
9190 branch_head_commit_id);
9191 if (error)
9192 goto done;
9193 printf("Updated to %s: %s\n",
9194 got_worktree_get_head_ref_name(worktree),
9195 id_str);
9196 free(id_str);
9197 } else
9198 printf("Already up-to-date\n");
9199 print_update_progress_stats(&upa);
9200 goto done;
9202 error = got_worktree_rebase_prepare(&new_base_branch,
9203 &tmp_branch, &fileindex, worktree, branch, repo);
9204 if (error)
9205 goto done;
9208 commit_id = branch_head_commit_id;
9209 error = got_object_open_as_commit(&commit, repo, commit_id);
9210 if (error)
9211 goto done;
9213 parent_ids = got_object_commit_get_parent_ids(commit);
9214 pid = STAILQ_FIRST(parent_ids);
9215 if (pid == NULL) {
9216 if (!continue_rebase) {
9217 error = got_worktree_rebase_abort(worktree, fileindex,
9218 repo, new_base_branch, abort_progress, &upa);
9219 if (error)
9220 goto done;
9221 printf("Rebase of %s aborted\n",
9222 got_ref_get_name(branch));
9223 print_merge_progress_stats(&upa);
9226 error = got_error(GOT_ERR_EMPTY_REBASE);
9227 goto done;
9229 error = collect_commits(&commits, commit_id, pid->id,
9230 yca_id, got_worktree_get_path_prefix(worktree),
9231 GOT_ERR_REBASE_PATH, repo);
9232 got_object_commit_close(commit);
9233 commit = NULL;
9234 if (error)
9235 goto done;
9237 if (STAILQ_EMPTY(&commits)) {
9238 if (continue_rebase) {
9239 error = rebase_complete(worktree, fileindex,
9240 branch, new_base_branch, tmp_branch, repo,
9241 create_backup);
9242 goto done;
9243 } else {
9244 /* Fast-forward the reference of the branch. */
9245 struct got_object_id *new_head_commit_id;
9246 char *id_str;
9247 error = got_ref_resolve(&new_head_commit_id, repo,
9248 new_base_branch);
9249 if (error)
9250 goto done;
9251 error = got_object_id_str(&id_str, new_head_commit_id);
9252 printf("Forwarding %s to commit %s\n",
9253 got_ref_get_name(branch), id_str);
9254 free(id_str);
9255 error = got_ref_change_ref(branch,
9256 new_head_commit_id);
9257 if (error)
9258 goto done;
9259 /* No backup needed since objects did not change. */
9260 create_backup = 0;
9264 pid = NULL;
9265 STAILQ_FOREACH(qid, &commits, entry) {
9267 commit_id = qid->id;
9268 parent_id = pid ? pid->id : yca_id;
9269 pid = qid;
9271 memset(&upa, 0, sizeof(upa));
9272 error = got_worktree_rebase_merge_files(&merged_paths,
9273 worktree, fileindex, parent_id, commit_id, repo,
9274 update_progress, &upa, check_cancelled, NULL);
9275 if (error)
9276 goto done;
9278 print_merge_progress_stats(&upa);
9279 if (upa.conflicts > 0 || upa.missing > 0 ||
9280 upa.not_deleted > 0 || upa.unversioned > 0) {
9281 if (upa.conflicts > 0) {
9282 error = show_rebase_merge_conflict(qid->id,
9283 repo);
9284 if (error)
9285 goto done;
9287 got_worktree_rebase_pathlist_free(&merged_paths);
9288 break;
9291 error = rebase_commit(&merged_paths, worktree, fileindex,
9292 tmp_branch, commit_id, repo);
9293 got_worktree_rebase_pathlist_free(&merged_paths);
9294 if (error)
9295 goto done;
9298 if (upa.conflicts > 0 || upa.missing > 0 ||
9299 upa.not_deleted > 0 || upa.unversioned > 0) {
9300 error = got_worktree_rebase_postpone(worktree, fileindex);
9301 if (error)
9302 goto done;
9303 if (upa.conflicts > 0 && upa.missing == 0 &&
9304 upa.not_deleted == 0 && upa.unversioned == 0) {
9305 error = got_error_msg(GOT_ERR_CONFLICTS,
9306 "conflicts must be resolved before rebasing "
9307 "can continue");
9308 } else if (upa.conflicts > 0) {
9309 error = got_error_msg(GOT_ERR_CONFLICTS,
9310 "conflicts must be resolved before rebasing "
9311 "can continue; changes destined for some "
9312 "files were not yet merged and should be "
9313 "merged manually if required before the "
9314 "rebase operation is continued");
9315 } else {
9316 error = got_error_msg(GOT_ERR_CONFLICTS,
9317 "changes destined for some files were not "
9318 "yet merged and should be merged manually "
9319 "if required before the rebase operation "
9320 "is continued");
9322 } else
9323 error = rebase_complete(worktree, fileindex, branch,
9324 new_base_branch, tmp_branch, repo, create_backup);
9325 done:
9326 got_object_id_queue_free(&commits);
9327 free(branch_head_commit_id);
9328 free(resume_commit_id);
9329 free(yca_id);
9330 if (commit)
9331 got_object_commit_close(commit);
9332 if (branch)
9333 got_ref_close(branch);
9334 if (new_base_branch)
9335 got_ref_close(new_base_branch);
9336 if (tmp_branch)
9337 got_ref_close(tmp_branch);
9338 if (worktree)
9339 got_worktree_close(worktree);
9340 if (repo) {
9341 const struct got_error *close_err = got_repo_close(repo);
9342 if (error == NULL)
9343 error = close_err;
9345 return error;
9348 __dead static void
9349 usage_histedit(void)
9351 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9352 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9353 getprogname());
9354 exit(1);
9357 #define GOT_HISTEDIT_PICK 'p'
9358 #define GOT_HISTEDIT_EDIT 'e'
9359 #define GOT_HISTEDIT_FOLD 'f'
9360 #define GOT_HISTEDIT_DROP 'd'
9361 #define GOT_HISTEDIT_MESG 'm'
9363 static struct got_histedit_cmd {
9364 unsigned char code;
9365 const char *name;
9366 const char *desc;
9367 } got_histedit_cmds[] = {
9368 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9369 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9370 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9371 "be used" },
9372 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9373 { GOT_HISTEDIT_MESG, "mesg",
9374 "single-line log message for commit above (open editor if empty)" },
9377 struct got_histedit_list_entry {
9378 TAILQ_ENTRY(got_histedit_list_entry) entry;
9379 struct got_object_id *commit_id;
9380 const struct got_histedit_cmd *cmd;
9381 char *logmsg;
9383 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9385 static const struct got_error *
9386 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9387 FILE *f, struct got_repository *repo)
9389 const struct got_error *err = NULL;
9390 char *logmsg = NULL, *id_str = NULL;
9391 struct got_commit_object *commit = NULL;
9392 int n;
9394 err = got_object_open_as_commit(&commit, repo, commit_id);
9395 if (err)
9396 goto done;
9398 err = get_short_logmsg(&logmsg, 34, commit);
9399 if (err)
9400 goto done;
9402 err = got_object_id_str(&id_str, commit_id);
9403 if (err)
9404 goto done;
9406 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9407 if (n < 0)
9408 err = got_ferror(f, GOT_ERR_IO);
9409 done:
9410 if (commit)
9411 got_object_commit_close(commit);
9412 free(id_str);
9413 free(logmsg);
9414 return err;
9417 static const struct got_error *
9418 histedit_write_commit_list(struct got_object_id_queue *commits,
9419 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9420 struct got_repository *repo)
9422 const struct got_error *err = NULL;
9423 struct got_object_qid *qid;
9424 const char *histedit_cmd = NULL;
9426 if (STAILQ_EMPTY(commits))
9427 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9429 STAILQ_FOREACH(qid, commits, entry) {
9430 histedit_cmd = got_histedit_cmds[0].name;
9431 if (edit_only)
9432 histedit_cmd = "edit";
9433 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9434 histedit_cmd = "fold";
9435 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9436 if (err)
9437 break;
9438 if (edit_logmsg_only) {
9439 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9440 if (n < 0) {
9441 err = got_ferror(f, GOT_ERR_IO);
9442 break;
9447 return err;
9450 static const struct got_error *
9451 write_cmd_list(FILE *f, const char *branch_name,
9452 struct got_object_id_queue *commits)
9454 const struct got_error *err = NULL;
9455 size_t i;
9456 int n;
9457 char *id_str;
9458 struct got_object_qid *qid;
9460 qid = STAILQ_FIRST(commits);
9461 err = got_object_id_str(&id_str, qid->id);
9462 if (err)
9463 return err;
9465 n = fprintf(f,
9466 "# Editing the history of branch '%s' starting at\n"
9467 "# commit %s\n"
9468 "# Commits will be processed in order from top to "
9469 "bottom of this file.\n", branch_name, id_str);
9470 if (n < 0) {
9471 err = got_ferror(f, GOT_ERR_IO);
9472 goto done;
9475 n = fprintf(f, "# Available histedit commands:\n");
9476 if (n < 0) {
9477 err = got_ferror(f, GOT_ERR_IO);
9478 goto done;
9481 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9482 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9483 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9484 cmd->desc);
9485 if (n < 0) {
9486 err = got_ferror(f, GOT_ERR_IO);
9487 break;
9490 done:
9491 free(id_str);
9492 return err;
9495 static const struct got_error *
9496 histedit_syntax_error(int lineno)
9498 static char msg[42];
9499 int ret;
9501 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9502 lineno);
9503 if (ret == -1 || ret >= sizeof(msg))
9504 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9506 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9509 static const struct got_error *
9510 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9511 char *logmsg, struct got_repository *repo)
9513 const struct got_error *err;
9514 struct got_commit_object *folded_commit = NULL;
9515 char *id_str, *folded_logmsg = NULL;
9517 err = got_object_id_str(&id_str, hle->commit_id);
9518 if (err)
9519 return err;
9521 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9522 if (err)
9523 goto done;
9525 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9526 if (err)
9527 goto done;
9528 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9529 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9530 folded_logmsg) == -1) {
9531 err = got_error_from_errno("asprintf");
9533 done:
9534 if (folded_commit)
9535 got_object_commit_close(folded_commit);
9536 free(id_str);
9537 free(folded_logmsg);
9538 return err;
9541 static struct got_histedit_list_entry *
9542 get_folded_commits(struct got_histedit_list_entry *hle)
9544 struct got_histedit_list_entry *prev, *folded = NULL;
9546 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9547 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9548 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9549 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9550 folded = prev;
9551 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9554 return folded;
9557 static const struct got_error *
9558 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9559 struct got_repository *repo)
9561 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9562 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9563 const struct got_error *err = NULL;
9564 struct got_commit_object *commit = NULL;
9565 int logmsg_len;
9566 int fd;
9567 struct got_histedit_list_entry *folded = NULL;
9569 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9570 if (err)
9571 return err;
9573 folded = get_folded_commits(hle);
9574 if (folded) {
9575 while (folded != hle) {
9576 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9577 folded = TAILQ_NEXT(folded, entry);
9578 continue;
9580 err = append_folded_commit_msg(&new_msg, folded,
9581 logmsg, repo);
9582 if (err)
9583 goto done;
9584 free(logmsg);
9585 logmsg = new_msg;
9586 folded = TAILQ_NEXT(folded, entry);
9590 err = got_object_id_str(&id_str, hle->commit_id);
9591 if (err)
9592 goto done;
9593 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9594 if (err)
9595 goto done;
9596 logmsg_len = asprintf(&new_msg,
9597 "%s\n# original log message of commit %s: %s",
9598 logmsg ? logmsg : "", id_str, orig_logmsg);
9599 if (logmsg_len == -1) {
9600 err = got_error_from_errno("asprintf");
9601 goto done;
9603 free(logmsg);
9604 logmsg = new_msg;
9606 err = got_object_id_str(&id_str, hle->commit_id);
9607 if (err)
9608 goto done;
9610 err = got_opentemp_named_fd(&logmsg_path, &fd,
9611 GOT_TMPDIR_STR "/got-logmsg");
9612 if (err)
9613 goto done;
9615 write(fd, logmsg, logmsg_len);
9616 close(fd);
9618 err = get_editor(&editor);
9619 if (err)
9620 goto done;
9622 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9623 logmsg_len, 0);
9624 if (err) {
9625 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9626 goto done;
9627 err = NULL;
9628 hle->logmsg = strdup(new_msg);
9629 if (hle->logmsg == NULL)
9630 err = got_error_from_errno("strdup");
9632 done:
9633 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9634 err = got_error_from_errno2("unlink", logmsg_path);
9635 free(logmsg_path);
9636 free(logmsg);
9637 free(orig_logmsg);
9638 free(editor);
9639 if (commit)
9640 got_object_commit_close(commit);
9641 return err;
9644 static const struct got_error *
9645 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9646 FILE *f, struct got_repository *repo)
9648 const struct got_error *err = NULL;
9649 char *line = NULL, *p, *end;
9650 size_t i, size;
9651 ssize_t len;
9652 int lineno = 0;
9653 const struct got_histedit_cmd *cmd;
9654 struct got_object_id *commit_id = NULL;
9655 struct got_histedit_list_entry *hle = NULL;
9657 for (;;) {
9658 len = getline(&line, &size, f);
9659 if (len == -1) {
9660 const struct got_error *getline_err;
9661 if (feof(f))
9662 break;
9663 getline_err = got_error_from_errno("getline");
9664 err = got_ferror(f, getline_err->code);
9665 break;
9667 lineno++;
9668 p = line;
9669 while (isspace((unsigned char)p[0]))
9670 p++;
9671 if (p[0] == '#' || p[0] == '\0') {
9672 free(line);
9673 line = NULL;
9674 continue;
9676 cmd = NULL;
9677 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9678 cmd = &got_histedit_cmds[i];
9679 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9680 isspace((unsigned char)p[strlen(cmd->name)])) {
9681 p += strlen(cmd->name);
9682 break;
9684 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9685 p++;
9686 break;
9689 if (i == nitems(got_histedit_cmds)) {
9690 err = histedit_syntax_error(lineno);
9691 break;
9693 while (isspace((unsigned char)p[0]))
9694 p++;
9695 if (cmd->code == GOT_HISTEDIT_MESG) {
9696 if (hle == NULL || hle->logmsg != NULL) {
9697 err = got_error(GOT_ERR_HISTEDIT_CMD);
9698 break;
9700 if (p[0] == '\0') {
9701 err = histedit_edit_logmsg(hle, repo);
9702 if (err)
9703 break;
9704 } else {
9705 hle->logmsg = strdup(p);
9706 if (hle->logmsg == NULL) {
9707 err = got_error_from_errno("strdup");
9708 break;
9711 free(line);
9712 line = NULL;
9713 continue;
9714 } else {
9715 end = p;
9716 while (end[0] && !isspace((unsigned char)end[0]))
9717 end++;
9718 *end = '\0';
9720 err = got_object_resolve_id_str(&commit_id, repo, p);
9721 if (err) {
9722 /* override error code */
9723 err = histedit_syntax_error(lineno);
9724 break;
9727 hle = malloc(sizeof(*hle));
9728 if (hle == NULL) {
9729 err = got_error_from_errno("malloc");
9730 break;
9732 hle->cmd = cmd;
9733 hle->commit_id = commit_id;
9734 hle->logmsg = NULL;
9735 commit_id = NULL;
9736 free(line);
9737 line = NULL;
9738 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9741 free(line);
9742 free(commit_id);
9743 return err;
9746 static const struct got_error *
9747 histedit_check_script(struct got_histedit_list *histedit_cmds,
9748 struct got_object_id_queue *commits, struct got_repository *repo)
9750 const struct got_error *err = NULL;
9751 struct got_object_qid *qid;
9752 struct got_histedit_list_entry *hle;
9753 static char msg[92];
9754 char *id_str;
9756 if (TAILQ_EMPTY(histedit_cmds))
9757 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9758 "histedit script contains no commands");
9759 if (STAILQ_EMPTY(commits))
9760 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9762 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9763 struct got_histedit_list_entry *hle2;
9764 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9765 if (hle == hle2)
9766 continue;
9767 if (got_object_id_cmp(hle->commit_id,
9768 hle2->commit_id) != 0)
9769 continue;
9770 err = got_object_id_str(&id_str, hle->commit_id);
9771 if (err)
9772 return err;
9773 snprintf(msg, sizeof(msg), "commit %s is listed "
9774 "more than once in histedit script", id_str);
9775 free(id_str);
9776 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9780 STAILQ_FOREACH(qid, commits, entry) {
9781 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9782 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9783 break;
9785 if (hle == NULL) {
9786 err = got_object_id_str(&id_str, qid->id);
9787 if (err)
9788 return err;
9789 snprintf(msg, sizeof(msg),
9790 "commit %s missing from histedit script", id_str);
9791 free(id_str);
9792 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9796 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9797 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9798 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9799 "last commit in histedit script cannot be folded");
9801 return NULL;
9804 static const struct got_error *
9805 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9806 const char *path, struct got_object_id_queue *commits,
9807 struct got_repository *repo)
9809 const struct got_error *err = NULL;
9810 char *editor;
9811 FILE *f = NULL;
9813 err = get_editor(&editor);
9814 if (err)
9815 return err;
9817 if (spawn_editor(editor, path) == -1) {
9818 err = got_error_from_errno("failed spawning editor");
9819 goto done;
9822 f = fopen(path, "r");
9823 if (f == NULL) {
9824 err = got_error_from_errno("fopen");
9825 goto done;
9827 err = histedit_parse_list(histedit_cmds, f, repo);
9828 if (err)
9829 goto done;
9831 err = histedit_check_script(histedit_cmds, commits, repo);
9832 done:
9833 if (f && fclose(f) == EOF && err == NULL)
9834 err = got_error_from_errno("fclose");
9835 free(editor);
9836 return err;
9839 static const struct got_error *
9840 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9841 struct got_object_id_queue *, const char *, const char *,
9842 struct got_repository *);
9844 static const struct got_error *
9845 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9846 struct got_object_id_queue *commits, const char *branch_name,
9847 int edit_logmsg_only, int fold_only, int edit_only,
9848 struct got_repository *repo)
9850 const struct got_error *err;
9851 FILE *f = NULL;
9852 char *path = NULL;
9854 err = got_opentemp_named(&path, &f, "got-histedit");
9855 if (err)
9856 return err;
9858 err = write_cmd_list(f, branch_name, commits);
9859 if (err)
9860 goto done;
9862 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9863 fold_only, edit_only, repo);
9864 if (err)
9865 goto done;
9867 if (edit_logmsg_only || fold_only || edit_only) {
9868 rewind(f);
9869 err = histedit_parse_list(histedit_cmds, f, repo);
9870 } else {
9871 if (fclose(f) == EOF) {
9872 err = got_error_from_errno("fclose");
9873 goto done;
9875 f = NULL;
9876 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9877 if (err) {
9878 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9879 err->code != GOT_ERR_HISTEDIT_CMD)
9880 goto done;
9881 err = histedit_edit_list_retry(histedit_cmds, err,
9882 commits, path, branch_name, repo);
9885 done:
9886 if (f && fclose(f) == EOF && err == NULL)
9887 err = got_error_from_errno("fclose");
9888 if (path && unlink(path) != 0 && err == NULL)
9889 err = got_error_from_errno2("unlink", path);
9890 free(path);
9891 return err;
9894 static const struct got_error *
9895 histedit_save_list(struct got_histedit_list *histedit_cmds,
9896 struct got_worktree *worktree, struct got_repository *repo)
9898 const struct got_error *err = NULL;
9899 char *path = NULL;
9900 FILE *f = NULL;
9901 struct got_histedit_list_entry *hle;
9902 struct got_commit_object *commit = NULL;
9904 err = got_worktree_get_histedit_script_path(&path, worktree);
9905 if (err)
9906 return err;
9908 f = fopen(path, "w");
9909 if (f == NULL) {
9910 err = got_error_from_errno2("fopen", path);
9911 goto done;
9913 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9914 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9915 repo);
9916 if (err)
9917 break;
9919 if (hle->logmsg) {
9920 int n = fprintf(f, "%c %s\n",
9921 GOT_HISTEDIT_MESG, hle->logmsg);
9922 if (n < 0) {
9923 err = got_ferror(f, GOT_ERR_IO);
9924 break;
9928 done:
9929 if (f && fclose(f) == EOF && err == NULL)
9930 err = got_error_from_errno("fclose");
9931 free(path);
9932 if (commit)
9933 got_object_commit_close(commit);
9934 return err;
9937 void
9938 histedit_free_list(struct got_histedit_list *histedit_cmds)
9940 struct got_histedit_list_entry *hle;
9942 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9943 TAILQ_REMOVE(histedit_cmds, hle, entry);
9944 free(hle);
9948 static const struct got_error *
9949 histedit_load_list(struct got_histedit_list *histedit_cmds,
9950 const char *path, struct got_repository *repo)
9952 const struct got_error *err = NULL;
9953 FILE *f = NULL;
9955 f = fopen(path, "r");
9956 if (f == NULL) {
9957 err = got_error_from_errno2("fopen", path);
9958 goto done;
9961 err = histedit_parse_list(histedit_cmds, f, repo);
9962 done:
9963 if (f && fclose(f) == EOF && err == NULL)
9964 err = got_error_from_errno("fclose");
9965 return err;
9968 static const struct got_error *
9969 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9970 const struct got_error *edit_err, struct got_object_id_queue *commits,
9971 const char *path, const char *branch_name, struct got_repository *repo)
9973 const struct got_error *err = NULL, *prev_err = edit_err;
9974 int resp = ' ';
9976 while (resp != 'c' && resp != 'r' && resp != 'a') {
9977 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9978 "or (a)bort: ", getprogname(), prev_err->msg);
9979 resp = getchar();
9980 if (resp == '\n')
9981 resp = getchar();
9982 if (resp == 'c') {
9983 histedit_free_list(histedit_cmds);
9984 err = histedit_run_editor(histedit_cmds, path, commits,
9985 repo);
9986 if (err) {
9987 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9988 err->code != GOT_ERR_HISTEDIT_CMD)
9989 break;
9990 prev_err = err;
9991 resp = ' ';
9992 continue;
9994 break;
9995 } else if (resp == 'r') {
9996 histedit_free_list(histedit_cmds);
9997 err = histedit_edit_script(histedit_cmds,
9998 commits, branch_name, 0, 0, 0, repo);
9999 if (err) {
10000 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10001 err->code != GOT_ERR_HISTEDIT_CMD)
10002 break;
10003 prev_err = err;
10004 resp = ' ';
10005 continue;
10007 break;
10008 } else if (resp == 'a') {
10009 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10010 break;
10011 } else
10012 printf("invalid response '%c'\n", resp);
10015 return err;
10018 static const struct got_error *
10019 histedit_complete(struct got_worktree *worktree,
10020 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10021 struct got_reference *branch, struct got_repository *repo)
10023 printf("Switching work tree to %s\n",
10024 got_ref_get_symref_target(branch));
10025 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10026 branch, repo);
10029 static const struct got_error *
10030 show_histedit_progress(struct got_commit_object *commit,
10031 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10033 const struct got_error *err;
10034 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10036 err = got_object_id_str(&old_id_str, hle->commit_id);
10037 if (err)
10038 goto done;
10040 if (new_id) {
10041 err = got_object_id_str(&new_id_str, new_id);
10042 if (err)
10043 goto done;
10046 old_id_str[12] = '\0';
10047 if (new_id_str)
10048 new_id_str[12] = '\0';
10050 if (hle->logmsg) {
10051 logmsg = strdup(hle->logmsg);
10052 if (logmsg == NULL) {
10053 err = got_error_from_errno("strdup");
10054 goto done;
10056 trim_logmsg(logmsg, 42);
10057 } else {
10058 err = get_short_logmsg(&logmsg, 42, commit);
10059 if (err)
10060 goto done;
10063 switch (hle->cmd->code) {
10064 case GOT_HISTEDIT_PICK:
10065 case GOT_HISTEDIT_EDIT:
10066 printf("%s -> %s: %s\n", old_id_str,
10067 new_id_str ? new_id_str : "no-op change", logmsg);
10068 break;
10069 case GOT_HISTEDIT_DROP:
10070 case GOT_HISTEDIT_FOLD:
10071 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10072 logmsg);
10073 break;
10074 default:
10075 break;
10077 done:
10078 free(old_id_str);
10079 free(new_id_str);
10080 return err;
10083 static const struct got_error *
10084 histedit_commit(struct got_pathlist_head *merged_paths,
10085 struct got_worktree *worktree, struct got_fileindex *fileindex,
10086 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10087 struct got_repository *repo)
10089 const struct got_error *err;
10090 struct got_commit_object *commit;
10091 struct got_object_id *new_commit_id;
10093 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10094 && hle->logmsg == NULL) {
10095 err = histedit_edit_logmsg(hle, repo);
10096 if (err)
10097 return err;
10100 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10101 if (err)
10102 return err;
10104 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10105 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10106 hle->logmsg, repo);
10107 if (err) {
10108 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10109 goto done;
10110 err = show_histedit_progress(commit, hle, NULL);
10111 } else {
10112 err = show_histedit_progress(commit, hle, new_commit_id);
10113 free(new_commit_id);
10115 done:
10116 got_object_commit_close(commit);
10117 return err;
10120 static const struct got_error *
10121 histedit_skip_commit(struct got_histedit_list_entry *hle,
10122 struct got_worktree *worktree, struct got_repository *repo)
10124 const struct got_error *error;
10125 struct got_commit_object *commit;
10127 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10128 repo);
10129 if (error)
10130 return error;
10132 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10133 if (error)
10134 return error;
10136 error = show_histedit_progress(commit, hle, NULL);
10137 got_object_commit_close(commit);
10138 return error;
10141 static const struct got_error *
10142 check_local_changes(void *arg, unsigned char status,
10143 unsigned char staged_status, const char *path,
10144 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10145 struct got_object_id *commit_id, int dirfd, const char *de_name)
10147 int *have_local_changes = arg;
10149 switch (status) {
10150 case GOT_STATUS_ADD:
10151 case GOT_STATUS_DELETE:
10152 case GOT_STATUS_MODIFY:
10153 case GOT_STATUS_CONFLICT:
10154 *have_local_changes = 1;
10155 return got_error(GOT_ERR_CANCELLED);
10156 default:
10157 break;
10160 switch (staged_status) {
10161 case GOT_STATUS_ADD:
10162 case GOT_STATUS_DELETE:
10163 case GOT_STATUS_MODIFY:
10164 *have_local_changes = 1;
10165 return got_error(GOT_ERR_CANCELLED);
10166 default:
10167 break;
10170 return NULL;
10173 static const struct got_error *
10174 cmd_histedit(int argc, char *argv[])
10176 const struct got_error *error = NULL;
10177 struct got_worktree *worktree = NULL;
10178 struct got_fileindex *fileindex = NULL;
10179 struct got_repository *repo = NULL;
10180 char *cwd = NULL;
10181 struct got_reference *branch = NULL;
10182 struct got_reference *tmp_branch = NULL;
10183 struct got_object_id *resume_commit_id = NULL;
10184 struct got_object_id *base_commit_id = NULL;
10185 struct got_object_id *head_commit_id = NULL;
10186 struct got_commit_object *commit = NULL;
10187 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10188 struct got_update_progress_arg upa;
10189 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10190 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10191 int list_backups = 0, delete_backups = 0;
10192 const char *edit_script_path = NULL;
10193 struct got_object_id_queue commits;
10194 struct got_pathlist_head merged_paths;
10195 const struct got_object_id_queue *parent_ids;
10196 struct got_object_qid *pid;
10197 struct got_histedit_list histedit_cmds;
10198 struct got_histedit_list_entry *hle;
10200 STAILQ_INIT(&commits);
10201 TAILQ_INIT(&histedit_cmds);
10202 TAILQ_INIT(&merged_paths);
10203 memset(&upa, 0, sizeof(upa));
10205 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10206 switch (ch) {
10207 case 'a':
10208 abort_edit = 1;
10209 break;
10210 case 'c':
10211 continue_edit = 1;
10212 break;
10213 case 'e':
10214 edit_only = 1;
10215 break;
10216 case 'f':
10217 fold_only = 1;
10218 break;
10219 case 'F':
10220 edit_script_path = optarg;
10221 break;
10222 case 'm':
10223 edit_logmsg_only = 1;
10224 break;
10225 case 'l':
10226 list_backups = 1;
10227 break;
10228 case 'X':
10229 delete_backups = 1;
10230 break;
10231 default:
10232 usage_histedit();
10233 /* NOTREACHED */
10237 argc -= optind;
10238 argv += optind;
10240 #ifndef PROFILE
10241 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10242 "unveil", NULL) == -1)
10243 err(1, "pledge");
10244 #endif
10245 if (abort_edit && continue_edit)
10246 option_conflict('a', 'c');
10247 if (edit_script_path && edit_logmsg_only)
10248 option_conflict('F', 'm');
10249 if (abort_edit && edit_logmsg_only)
10250 option_conflict('a', 'm');
10251 if (continue_edit && edit_logmsg_only)
10252 option_conflict('c', 'm');
10253 if (abort_edit && fold_only)
10254 option_conflict('a', 'f');
10255 if (continue_edit && fold_only)
10256 option_conflict('c', 'f');
10257 if (fold_only && edit_logmsg_only)
10258 option_conflict('f', 'm');
10259 if (edit_script_path && fold_only)
10260 option_conflict('F', 'f');
10261 if (abort_edit && edit_only)
10262 option_conflict('a', 'e');
10263 if (continue_edit && edit_only)
10264 option_conflict('c', 'e');
10265 if (edit_only && edit_logmsg_only)
10266 option_conflict('e', 'm');
10267 if (edit_script_path && edit_only)
10268 option_conflict('F', 'e');
10269 if (list_backups) {
10270 if (abort_edit)
10271 option_conflict('l', 'a');
10272 if (continue_edit)
10273 option_conflict('l', 'c');
10274 if (edit_script_path)
10275 option_conflict('l', 'F');
10276 if (edit_logmsg_only)
10277 option_conflict('l', 'm');
10278 if (fold_only)
10279 option_conflict('l', 'f');
10280 if (edit_only)
10281 option_conflict('l', 'e');
10282 if (delete_backups)
10283 option_conflict('l', 'X');
10284 if (argc != 0 && argc != 1)
10285 usage_histedit();
10286 } else if (delete_backups) {
10287 if (abort_edit)
10288 option_conflict('X', 'a');
10289 if (continue_edit)
10290 option_conflict('X', 'c');
10291 if (edit_script_path)
10292 option_conflict('X', 'F');
10293 if (edit_logmsg_only)
10294 option_conflict('X', 'm');
10295 if (fold_only)
10296 option_conflict('X', 'f');
10297 if (edit_only)
10298 option_conflict('X', 'e');
10299 if (list_backups)
10300 option_conflict('X', 'l');
10301 if (argc != 0 && argc != 1)
10302 usage_histedit();
10303 } else if (argc != 0)
10304 usage_histedit();
10307 * This command cannot apply unveil(2) in all cases because the
10308 * user may choose to run an editor to edit the histedit script
10309 * and to edit individual commit log messages.
10310 * unveil(2) traverses exec(2); if an editor is used we have to
10311 * apply unveil after edit script and log messages have been written.
10312 * XXX TODO: Make use of unveil(2) where possible.
10315 cwd = getcwd(NULL, 0);
10316 if (cwd == NULL) {
10317 error = got_error_from_errno("getcwd");
10318 goto done;
10320 error = got_worktree_open(&worktree, cwd);
10321 if (error) {
10322 if (list_backups || delete_backups) {
10323 if (error->code != GOT_ERR_NOT_WORKTREE)
10324 goto done;
10325 } else {
10326 if (error->code == GOT_ERR_NOT_WORKTREE)
10327 error = wrap_not_worktree_error(error,
10328 "histedit", cwd);
10329 goto done;
10333 if (list_backups || delete_backups) {
10334 error = got_repo_open(&repo,
10335 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10336 NULL);
10337 if (error != NULL)
10338 goto done;
10339 error = apply_unveil(got_repo_get_path(repo), 0,
10340 worktree ? got_worktree_get_root_path(worktree) : NULL);
10341 if (error)
10342 goto done;
10343 error = process_backup_refs(
10344 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10345 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10346 goto done; /* nothing else to do */
10349 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10350 NULL);
10351 if (error != NULL)
10352 goto done;
10354 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10355 if (error)
10356 goto done;
10357 if (rebase_in_progress) {
10358 error = got_error(GOT_ERR_REBASING);
10359 goto done;
10362 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10363 repo);
10364 if (error)
10365 goto done;
10366 if (merge_in_progress) {
10367 error = got_error(GOT_ERR_MERGE_BUSY);
10368 goto done;
10371 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10372 if (error)
10373 goto done;
10375 if (edit_in_progress && edit_logmsg_only) {
10376 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10377 "histedit operation is in progress in this "
10378 "work tree and must be continued or aborted "
10379 "before the -m option can be used");
10380 goto done;
10382 if (edit_in_progress && fold_only) {
10383 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10384 "histedit operation is in progress in this "
10385 "work tree and must be continued or aborted "
10386 "before the -f option can be used");
10387 goto done;
10389 if (edit_in_progress && edit_only) {
10390 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10391 "histedit operation is in progress in this "
10392 "work tree and must be continued or aborted "
10393 "before the -e option can be used");
10394 goto done;
10397 if (edit_in_progress && abort_edit) {
10398 error = got_worktree_histedit_continue(&resume_commit_id,
10399 &tmp_branch, &branch, &base_commit_id, &fileindex,
10400 worktree, repo);
10401 if (error)
10402 goto done;
10403 printf("Switching work tree to %s\n",
10404 got_ref_get_symref_target(branch));
10405 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10406 branch, base_commit_id, abort_progress, &upa);
10407 if (error)
10408 goto done;
10409 printf("Histedit of %s aborted\n",
10410 got_ref_get_symref_target(branch));
10411 print_merge_progress_stats(&upa);
10412 goto done; /* nothing else to do */
10413 } else if (abort_edit) {
10414 error = got_error(GOT_ERR_NOT_HISTEDIT);
10415 goto done;
10418 if (continue_edit) {
10419 char *path;
10421 if (!edit_in_progress) {
10422 error = got_error(GOT_ERR_NOT_HISTEDIT);
10423 goto done;
10426 error = got_worktree_get_histedit_script_path(&path, worktree);
10427 if (error)
10428 goto done;
10430 error = histedit_load_list(&histedit_cmds, path, repo);
10431 free(path);
10432 if (error)
10433 goto done;
10435 error = got_worktree_histedit_continue(&resume_commit_id,
10436 &tmp_branch, &branch, &base_commit_id, &fileindex,
10437 worktree, repo);
10438 if (error)
10439 goto done;
10441 error = got_ref_resolve(&head_commit_id, repo, branch);
10442 if (error)
10443 goto done;
10445 error = got_object_open_as_commit(&commit, repo,
10446 head_commit_id);
10447 if (error)
10448 goto done;
10449 parent_ids = got_object_commit_get_parent_ids(commit);
10450 pid = STAILQ_FIRST(parent_ids);
10451 if (pid == NULL) {
10452 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10453 goto done;
10455 error = collect_commits(&commits, head_commit_id, pid->id,
10456 base_commit_id, got_worktree_get_path_prefix(worktree),
10457 GOT_ERR_HISTEDIT_PATH, repo);
10458 got_object_commit_close(commit);
10459 commit = NULL;
10460 if (error)
10461 goto done;
10462 } else {
10463 if (edit_in_progress) {
10464 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10465 goto done;
10468 error = got_ref_open(&branch, repo,
10469 got_worktree_get_head_ref_name(worktree), 0);
10470 if (error != NULL)
10471 goto done;
10473 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10474 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10475 "will not edit commit history of a branch outside "
10476 "the \"refs/heads/\" reference namespace");
10477 goto done;
10480 error = got_ref_resolve(&head_commit_id, repo, branch);
10481 got_ref_close(branch);
10482 branch = NULL;
10483 if (error)
10484 goto done;
10486 error = got_object_open_as_commit(&commit, repo,
10487 head_commit_id);
10488 if (error)
10489 goto done;
10490 parent_ids = got_object_commit_get_parent_ids(commit);
10491 pid = STAILQ_FIRST(parent_ids);
10492 if (pid == NULL) {
10493 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10494 goto done;
10496 error = collect_commits(&commits, head_commit_id, pid->id,
10497 got_worktree_get_base_commit_id(worktree),
10498 got_worktree_get_path_prefix(worktree),
10499 GOT_ERR_HISTEDIT_PATH, repo);
10500 got_object_commit_close(commit);
10501 commit = NULL;
10502 if (error)
10503 goto done;
10505 if (STAILQ_EMPTY(&commits)) {
10506 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10507 goto done;
10510 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10511 &base_commit_id, &fileindex, worktree, repo);
10512 if (error)
10513 goto done;
10515 if (edit_script_path) {
10516 error = histedit_load_list(&histedit_cmds,
10517 edit_script_path, repo);
10518 if (error) {
10519 got_worktree_histedit_abort(worktree, fileindex,
10520 repo, branch, base_commit_id,
10521 abort_progress, &upa);
10522 print_merge_progress_stats(&upa);
10523 goto done;
10525 } else {
10526 const char *branch_name;
10527 branch_name = got_ref_get_symref_target(branch);
10528 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10529 branch_name += 11;
10530 error = histedit_edit_script(&histedit_cmds, &commits,
10531 branch_name, edit_logmsg_only, fold_only,
10532 edit_only, repo);
10533 if (error) {
10534 got_worktree_histedit_abort(worktree, fileindex,
10535 repo, branch, base_commit_id,
10536 abort_progress, &upa);
10537 print_merge_progress_stats(&upa);
10538 goto done;
10543 error = histedit_save_list(&histedit_cmds, worktree,
10544 repo);
10545 if (error) {
10546 got_worktree_histedit_abort(worktree, fileindex,
10547 repo, branch, base_commit_id,
10548 abort_progress, &upa);
10549 print_merge_progress_stats(&upa);
10550 goto done;
10555 error = histedit_check_script(&histedit_cmds, &commits, repo);
10556 if (error)
10557 goto done;
10559 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10560 if (resume_commit_id) {
10561 if (got_object_id_cmp(hle->commit_id,
10562 resume_commit_id) != 0)
10563 continue;
10565 resume_commit_id = NULL;
10566 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10567 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10568 error = histedit_skip_commit(hle, worktree,
10569 repo);
10570 if (error)
10571 goto done;
10572 } else {
10573 struct got_pathlist_head paths;
10574 int have_changes = 0;
10576 TAILQ_INIT(&paths);
10577 error = got_pathlist_append(&paths, "", NULL);
10578 if (error)
10579 goto done;
10580 error = got_worktree_status(worktree, &paths,
10581 repo, 0, check_local_changes, &have_changes,
10582 check_cancelled, NULL);
10583 got_pathlist_free(&paths);
10584 if (error) {
10585 if (error->code != GOT_ERR_CANCELLED)
10586 goto done;
10587 if (sigint_received || sigpipe_received)
10588 goto done;
10590 if (have_changes) {
10591 error = histedit_commit(NULL, worktree,
10592 fileindex, tmp_branch, hle, repo);
10593 if (error)
10594 goto done;
10595 } else {
10596 error = got_object_open_as_commit(
10597 &commit, repo, hle->commit_id);
10598 if (error)
10599 goto done;
10600 error = show_histedit_progress(commit,
10601 hle, NULL);
10602 got_object_commit_close(commit);
10603 commit = NULL;
10604 if (error)
10605 goto done;
10608 continue;
10611 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10612 error = histedit_skip_commit(hle, worktree, repo);
10613 if (error)
10614 goto done;
10615 continue;
10618 error = got_object_open_as_commit(&commit, repo,
10619 hle->commit_id);
10620 if (error)
10621 goto done;
10622 parent_ids = got_object_commit_get_parent_ids(commit);
10623 pid = STAILQ_FIRST(parent_ids);
10625 error = got_worktree_histedit_merge_files(&merged_paths,
10626 worktree, fileindex, pid->id, hle->commit_id, repo,
10627 update_progress, &upa, check_cancelled, NULL);
10628 if (error)
10629 goto done;
10630 got_object_commit_close(commit);
10631 commit = NULL;
10633 print_merge_progress_stats(&upa);
10634 if (upa.conflicts > 0 || upa.missing > 0 ||
10635 upa.not_deleted > 0 || upa.unversioned > 0) {
10636 if (upa.conflicts > 0) {
10637 error = show_rebase_merge_conflict(
10638 hle->commit_id, repo);
10639 if (error)
10640 goto done;
10642 got_worktree_rebase_pathlist_free(&merged_paths);
10643 break;
10646 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10647 char *id_str;
10648 error = got_object_id_str(&id_str, hle->commit_id);
10649 if (error)
10650 goto done;
10651 printf("Stopping histedit for amending commit %s\n",
10652 id_str);
10653 free(id_str);
10654 got_worktree_rebase_pathlist_free(&merged_paths);
10655 error = got_worktree_histedit_postpone(worktree,
10656 fileindex);
10657 goto done;
10660 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10661 error = histedit_skip_commit(hle, worktree, repo);
10662 if (error)
10663 goto done;
10664 continue;
10667 error = histedit_commit(&merged_paths, worktree, fileindex,
10668 tmp_branch, hle, repo);
10669 got_worktree_rebase_pathlist_free(&merged_paths);
10670 if (error)
10671 goto done;
10674 if (upa.conflicts > 0 || upa.missing > 0 ||
10675 upa.not_deleted > 0 || upa.unversioned > 0) {
10676 error = got_worktree_histedit_postpone(worktree, fileindex);
10677 if (error)
10678 goto done;
10679 if (upa.conflicts > 0 && upa.missing == 0 &&
10680 upa.not_deleted == 0 && upa.unversioned == 0) {
10681 error = got_error_msg(GOT_ERR_CONFLICTS,
10682 "conflicts must be resolved before histedit "
10683 "can continue");
10684 } else if (upa.conflicts > 0) {
10685 error = got_error_msg(GOT_ERR_CONFLICTS,
10686 "conflicts must be resolved before histedit "
10687 "can continue; changes destined for some "
10688 "files were not yet merged and should be "
10689 "merged manually if required before the "
10690 "histedit operation is continued");
10691 } else {
10692 error = got_error_msg(GOT_ERR_CONFLICTS,
10693 "changes destined for some files were not "
10694 "yet merged and should be merged manually "
10695 "if required before the histedit operation "
10696 "is continued");
10698 } else
10699 error = histedit_complete(worktree, fileindex, tmp_branch,
10700 branch, repo);
10701 done:
10702 got_object_id_queue_free(&commits);
10703 histedit_free_list(&histedit_cmds);
10704 free(head_commit_id);
10705 free(base_commit_id);
10706 free(resume_commit_id);
10707 if (commit)
10708 got_object_commit_close(commit);
10709 if (branch)
10710 got_ref_close(branch);
10711 if (tmp_branch)
10712 got_ref_close(tmp_branch);
10713 if (worktree)
10714 got_worktree_close(worktree);
10715 if (repo) {
10716 const struct got_error *close_err = got_repo_close(repo);
10717 if (error == NULL)
10718 error = close_err;
10720 return error;
10723 __dead static void
10724 usage_integrate(void)
10726 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10727 exit(1);
10730 static const struct got_error *
10731 cmd_integrate(int argc, char *argv[])
10733 const struct got_error *error = NULL;
10734 struct got_repository *repo = NULL;
10735 struct got_worktree *worktree = NULL;
10736 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10737 const char *branch_arg = NULL;
10738 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10739 struct got_fileindex *fileindex = NULL;
10740 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10741 int ch;
10742 struct got_update_progress_arg upa;
10744 while ((ch = getopt(argc, argv, "")) != -1) {
10745 switch (ch) {
10746 default:
10747 usage_integrate();
10748 /* NOTREACHED */
10752 argc -= optind;
10753 argv += optind;
10755 if (argc != 1)
10756 usage_integrate();
10757 branch_arg = argv[0];
10758 #ifndef PROFILE
10759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10760 "unveil", NULL) == -1)
10761 err(1, "pledge");
10762 #endif
10763 cwd = getcwd(NULL, 0);
10764 if (cwd == NULL) {
10765 error = got_error_from_errno("getcwd");
10766 goto done;
10769 error = got_worktree_open(&worktree, cwd);
10770 if (error) {
10771 if (error->code == GOT_ERR_NOT_WORKTREE)
10772 error = wrap_not_worktree_error(error, "integrate",
10773 cwd);
10774 goto done;
10777 error = check_rebase_or_histedit_in_progress(worktree);
10778 if (error)
10779 goto done;
10781 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10782 NULL);
10783 if (error != NULL)
10784 goto done;
10786 error = apply_unveil(got_repo_get_path(repo), 0,
10787 got_worktree_get_root_path(worktree));
10788 if (error)
10789 goto done;
10791 error = check_merge_in_progress(worktree, repo);
10792 if (error)
10793 goto done;
10795 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10796 error = got_error_from_errno("asprintf");
10797 goto done;
10800 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10801 &base_branch_ref, worktree, refname, repo);
10802 if (error)
10803 goto done;
10805 refname = strdup(got_ref_get_name(branch_ref));
10806 if (refname == NULL) {
10807 error = got_error_from_errno("strdup");
10808 got_worktree_integrate_abort(worktree, fileindex, repo,
10809 branch_ref, base_branch_ref);
10810 goto done;
10812 base_refname = strdup(got_ref_get_name(base_branch_ref));
10813 if (base_refname == NULL) {
10814 error = got_error_from_errno("strdup");
10815 got_worktree_integrate_abort(worktree, fileindex, repo,
10816 branch_ref, base_branch_ref);
10817 goto done;
10820 error = got_ref_resolve(&commit_id, repo, branch_ref);
10821 if (error)
10822 goto done;
10824 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10825 if (error)
10826 goto done;
10828 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10829 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10830 "specified branch has already been integrated");
10831 got_worktree_integrate_abort(worktree, fileindex, repo,
10832 branch_ref, base_branch_ref);
10833 goto done;
10836 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10837 if (error) {
10838 if (error->code == GOT_ERR_ANCESTRY)
10839 error = got_error(GOT_ERR_REBASE_REQUIRED);
10840 got_worktree_integrate_abort(worktree, fileindex, repo,
10841 branch_ref, base_branch_ref);
10842 goto done;
10845 memset(&upa, 0, sizeof(upa));
10846 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10847 branch_ref, base_branch_ref, update_progress, &upa,
10848 check_cancelled, NULL);
10849 if (error)
10850 goto done;
10852 printf("Integrated %s into %s\n", refname, base_refname);
10853 print_update_progress_stats(&upa);
10854 done:
10855 if (repo) {
10856 const struct got_error *close_err = got_repo_close(repo);
10857 if (error == NULL)
10858 error = close_err;
10860 if (worktree)
10861 got_worktree_close(worktree);
10862 free(cwd);
10863 free(base_commit_id);
10864 free(commit_id);
10865 free(refname);
10866 free(base_refname);
10867 return error;
10870 __dead static void
10871 usage_merge(void)
10873 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
10874 getprogname());
10875 exit(1);
10878 static const struct got_error *
10879 cmd_merge(int argc, char *argv[])
10881 const struct got_error *error = NULL;
10882 struct got_worktree *worktree = NULL;
10883 struct got_repository *repo = NULL;
10884 struct got_fileindex *fileindex = NULL;
10885 char *cwd = NULL, *id_str = NULL, *author = NULL;
10886 struct got_reference *branch = NULL, *wt_branch = NULL;
10887 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
10888 struct got_object_id *wt_branch_tip = NULL;
10889 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
10890 int interrupt_merge = 0;
10891 struct got_update_progress_arg upa;
10892 struct got_object_id *merge_commit_id = NULL;
10893 char *branch_name = NULL;
10895 memset(&upa, 0, sizeof(upa));
10897 while ((ch = getopt(argc, argv, "acn")) != -1) {
10898 switch (ch) {
10899 case 'a':
10900 abort_merge = 1;
10901 break;
10902 case 'c':
10903 continue_merge = 1;
10904 break;
10905 case 'n':
10906 interrupt_merge = 1;
10907 break;
10908 default:
10909 usage_rebase();
10910 /* NOTREACHED */
10914 argc -= optind;
10915 argv += optind;
10917 #ifndef PROFILE
10918 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10919 "unveil", NULL) == -1)
10920 err(1, "pledge");
10921 #endif
10923 if (abort_merge && continue_merge)
10924 option_conflict('a', 'c');
10925 if (abort_merge || continue_merge) {
10926 if (argc != 0)
10927 usage_merge();
10928 } else if (argc != 1)
10929 usage_merge();
10931 cwd = getcwd(NULL, 0);
10932 if (cwd == NULL) {
10933 error = got_error_from_errno("getcwd");
10934 goto done;
10937 error = got_worktree_open(&worktree, cwd);
10938 if (error) {
10939 if (error->code == GOT_ERR_NOT_WORKTREE)
10940 error = wrap_not_worktree_error(error,
10941 "merge", cwd);
10942 goto done;
10945 error = got_repo_open(&repo,
10946 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
10947 if (error != NULL)
10948 goto done;
10950 error = apply_unveil(got_repo_get_path(repo), 0,
10951 worktree ? got_worktree_get_root_path(worktree) : NULL);
10952 if (error)
10953 goto done;
10955 error = check_rebase_or_histedit_in_progress(worktree);
10956 if (error)
10957 goto done;
10959 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10960 repo);
10961 if (error)
10962 goto done;
10964 if (abort_merge) {
10965 if (!merge_in_progress) {
10966 error = got_error(GOT_ERR_NOT_MERGING);
10967 goto done;
10969 error = got_worktree_merge_continue(&branch_name,
10970 &branch_tip, &fileindex, worktree, repo);
10971 if (error)
10972 goto done;
10973 error = got_worktree_merge_abort(worktree, fileindex, repo,
10974 abort_progress, &upa);
10975 if (error)
10976 goto done;
10977 printf("Merge of %s aborted\n", branch_name);
10978 goto done; /* nothing else to do */
10981 error = get_author(&author, repo, worktree);
10982 if (error)
10983 goto done;
10985 if (continue_merge) {
10986 if (!merge_in_progress) {
10987 error = got_error(GOT_ERR_NOT_MERGING);
10988 goto done;
10990 error = got_worktree_merge_continue(&branch_name,
10991 &branch_tip, &fileindex, worktree, repo);
10992 if (error)
10993 goto done;
10994 } else {
10995 error = got_ref_open(&branch, repo, argv[0], 0);
10996 if (error != NULL)
10997 goto done;
10998 branch_name = strdup(got_ref_get_name(branch));
10999 if (branch_name == NULL) {
11000 error = got_error_from_errno("strdup");
11001 goto done;
11003 error = got_ref_resolve(&branch_tip, repo, branch);
11004 if (error)
11005 goto done;
11008 error = got_ref_open(&wt_branch, repo,
11009 got_worktree_get_head_ref_name(worktree), 0);
11010 if (error)
11011 goto done;
11012 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11013 if (error)
11014 goto done;
11015 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11016 wt_branch_tip, branch_tip, 0, repo,
11017 check_cancelled, NULL);
11018 if (error && error->code != GOT_ERR_ANCESTRY)
11019 goto done;
11021 if (!continue_merge) {
11022 error = check_path_prefix(wt_branch_tip, branch_tip,
11023 got_worktree_get_path_prefix(worktree),
11024 GOT_ERR_MERGE_PATH, repo);
11025 if (error)
11026 goto done;
11027 if (yca_id) {
11028 error = check_same_branch(wt_branch_tip, branch,
11029 yca_id, repo);
11030 if (error) {
11031 if (error->code != GOT_ERR_ANCESTRY)
11032 goto done;
11033 error = NULL;
11034 } else {
11035 static char msg[512];
11036 snprintf(msg, sizeof(msg),
11037 "cannot create a merge commit because "
11038 "%s is based on %s; %s can be integrated "
11039 "with 'got integrate' instead", branch_name,
11040 got_worktree_get_head_ref_name(worktree),
11041 branch_name);
11042 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11043 goto done;
11046 error = got_worktree_merge_prepare(&fileindex, worktree,
11047 branch, repo);
11048 if (error)
11049 goto done;
11051 error = got_worktree_merge_branch(worktree, fileindex,
11052 yca_id, branch_tip, repo, update_progress, &upa,
11053 check_cancelled, NULL);
11054 if (error)
11055 goto done;
11056 print_merge_progress_stats(&upa);
11057 if (!upa.did_something) {
11058 error = got_worktree_merge_abort(worktree, fileindex,
11059 repo, abort_progress, &upa);
11060 if (error)
11061 goto done;
11062 printf("Already up-to-date\n");
11063 goto done;
11067 if (interrupt_merge) {
11068 error = got_worktree_merge_postpone(worktree, fileindex);
11069 if (error)
11070 goto done;
11071 printf("Merge of %s interrupted on request\n", branch_name);
11072 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11073 upa.not_deleted > 0 || upa.unversioned > 0) {
11074 error = got_worktree_merge_postpone(worktree, fileindex);
11075 if (error)
11076 goto done;
11077 if (upa.conflicts > 0 && upa.missing == 0 &&
11078 upa.not_deleted == 0 && upa.unversioned == 0) {
11079 error = got_error_msg(GOT_ERR_CONFLICTS,
11080 "conflicts must be resolved before merging "
11081 "can continue");
11082 } else if (upa.conflicts > 0) {
11083 error = got_error_msg(GOT_ERR_CONFLICTS,
11084 "conflicts must be resolved before merging "
11085 "can continue; changes destined for some "
11086 "files were not yet merged and "
11087 "should be merged manually if required before the "
11088 "merge operation is continued");
11089 } else {
11090 error = got_error_msg(GOT_ERR_CONFLICTS,
11091 "changes destined for some "
11092 "files were not yet merged and should be "
11093 "merged manually if required before the "
11094 "merge operation is continued");
11096 goto done;
11097 } else {
11098 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11099 fileindex, author, NULL, 1, branch_tip, branch_name,
11100 repo, continue_merge ? print_status : NULL, NULL);
11101 if (error)
11102 goto done;
11103 error = got_worktree_merge_complete(worktree, fileindex, repo);
11104 if (error)
11105 goto done;
11106 error = got_object_id_str(&id_str, merge_commit_id);
11107 if (error)
11108 goto done;
11109 printf("Merged %s into %s: %s\n", branch_name,
11110 got_worktree_get_head_ref_name(worktree),
11111 id_str);
11114 done:
11115 free(id_str);
11116 free(merge_commit_id);
11117 free(author);
11118 free(branch_tip);
11119 free(branch_name);
11120 free(yca_id);
11121 if (branch)
11122 got_ref_close(branch);
11123 if (wt_branch)
11124 got_ref_close(wt_branch);
11125 if (worktree)
11126 got_worktree_close(worktree);
11127 if (repo) {
11128 const struct got_error *close_err = got_repo_close(repo);
11129 if (error == NULL)
11130 error = close_err;
11132 return error;
11135 __dead static void
11136 usage_stage(void)
11138 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11139 "[-S] [file-path ...]\n",
11140 getprogname());
11141 exit(1);
11144 static const struct got_error *
11145 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11146 const char *path, struct got_object_id *blob_id,
11147 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11148 int dirfd, const char *de_name)
11150 const struct got_error *err = NULL;
11151 char *id_str = NULL;
11153 if (staged_status != GOT_STATUS_ADD &&
11154 staged_status != GOT_STATUS_MODIFY &&
11155 staged_status != GOT_STATUS_DELETE)
11156 return NULL;
11158 if (staged_status == GOT_STATUS_ADD ||
11159 staged_status == GOT_STATUS_MODIFY)
11160 err = got_object_id_str(&id_str, staged_blob_id);
11161 else
11162 err = got_object_id_str(&id_str, blob_id);
11163 if (err)
11164 return err;
11166 printf("%s %c %s\n", id_str, staged_status, path);
11167 free(id_str);
11168 return NULL;
11171 static const struct got_error *
11172 cmd_stage(int argc, char *argv[])
11174 const struct got_error *error = NULL;
11175 struct got_repository *repo = NULL;
11176 struct got_worktree *worktree = NULL;
11177 char *cwd = NULL;
11178 struct got_pathlist_head paths;
11179 struct got_pathlist_entry *pe;
11180 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11181 FILE *patch_script_file = NULL;
11182 const char *patch_script_path = NULL;
11183 struct choose_patch_arg cpa;
11185 TAILQ_INIT(&paths);
11187 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11188 switch (ch) {
11189 case 'l':
11190 list_stage = 1;
11191 break;
11192 case 'p':
11193 pflag = 1;
11194 break;
11195 case 'F':
11196 patch_script_path = optarg;
11197 break;
11198 case 'S':
11199 allow_bad_symlinks = 1;
11200 break;
11201 default:
11202 usage_stage();
11203 /* NOTREACHED */
11207 argc -= optind;
11208 argv += optind;
11210 #ifndef PROFILE
11211 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11212 "unveil", NULL) == -1)
11213 err(1, "pledge");
11214 #endif
11215 if (list_stage && (pflag || patch_script_path))
11216 errx(1, "-l option cannot be used with other options");
11217 if (patch_script_path && !pflag)
11218 errx(1, "-F option can only be used together with -p option");
11220 cwd = getcwd(NULL, 0);
11221 if (cwd == NULL) {
11222 error = got_error_from_errno("getcwd");
11223 goto done;
11226 error = got_worktree_open(&worktree, cwd);
11227 if (error) {
11228 if (error->code == GOT_ERR_NOT_WORKTREE)
11229 error = wrap_not_worktree_error(error, "stage", cwd);
11230 goto done;
11233 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11234 NULL);
11235 if (error != NULL)
11236 goto done;
11238 if (patch_script_path) {
11239 patch_script_file = fopen(patch_script_path, "r");
11240 if (patch_script_file == NULL) {
11241 error = got_error_from_errno2("fopen",
11242 patch_script_path);
11243 goto done;
11246 error = apply_unveil(got_repo_get_path(repo), 0,
11247 got_worktree_get_root_path(worktree));
11248 if (error)
11249 goto done;
11251 error = check_merge_in_progress(worktree, repo);
11252 if (error)
11253 goto done;
11255 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11256 if (error)
11257 goto done;
11259 if (list_stage)
11260 error = got_worktree_status(worktree, &paths, repo, 0,
11261 print_stage, NULL, check_cancelled, NULL);
11262 else {
11263 cpa.patch_script_file = patch_script_file;
11264 cpa.action = "stage";
11265 error = got_worktree_stage(worktree, &paths,
11266 pflag ? NULL : print_status, NULL,
11267 pflag ? choose_patch : NULL, &cpa,
11268 allow_bad_symlinks, repo);
11270 done:
11271 if (patch_script_file && fclose(patch_script_file) == EOF &&
11272 error == NULL)
11273 error = got_error_from_errno2("fclose", patch_script_path);
11274 if (repo) {
11275 const struct got_error *close_err = got_repo_close(repo);
11276 if (error == NULL)
11277 error = close_err;
11279 if (worktree)
11280 got_worktree_close(worktree);
11281 TAILQ_FOREACH(pe, &paths, entry)
11282 free((char *)pe->path);
11283 got_pathlist_free(&paths);
11284 free(cwd);
11285 return error;
11288 __dead static void
11289 usage_unstage(void)
11291 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11292 "[file-path ...]\n",
11293 getprogname());
11294 exit(1);
11298 static const struct got_error *
11299 cmd_unstage(int argc, char *argv[])
11301 const struct got_error *error = NULL;
11302 struct got_repository *repo = NULL;
11303 struct got_worktree *worktree = NULL;
11304 char *cwd = NULL;
11305 struct got_pathlist_head paths;
11306 struct got_pathlist_entry *pe;
11307 int ch, pflag = 0;
11308 struct got_update_progress_arg upa;
11309 FILE *patch_script_file = NULL;
11310 const char *patch_script_path = NULL;
11311 struct choose_patch_arg cpa;
11313 TAILQ_INIT(&paths);
11315 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11316 switch (ch) {
11317 case 'p':
11318 pflag = 1;
11319 break;
11320 case 'F':
11321 patch_script_path = optarg;
11322 break;
11323 default:
11324 usage_unstage();
11325 /* NOTREACHED */
11329 argc -= optind;
11330 argv += optind;
11332 #ifndef PROFILE
11333 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11334 "unveil", NULL) == -1)
11335 err(1, "pledge");
11336 #endif
11337 if (patch_script_path && !pflag)
11338 errx(1, "-F option can only be used together with -p option");
11340 cwd = getcwd(NULL, 0);
11341 if (cwd == NULL) {
11342 error = got_error_from_errno("getcwd");
11343 goto done;
11346 error = got_worktree_open(&worktree, cwd);
11347 if (error) {
11348 if (error->code == GOT_ERR_NOT_WORKTREE)
11349 error = wrap_not_worktree_error(error, "unstage", cwd);
11350 goto done;
11353 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11354 NULL);
11355 if (error != NULL)
11356 goto done;
11358 if (patch_script_path) {
11359 patch_script_file = fopen(patch_script_path, "r");
11360 if (patch_script_file == NULL) {
11361 error = got_error_from_errno2("fopen",
11362 patch_script_path);
11363 goto done;
11367 error = apply_unveil(got_repo_get_path(repo), 0,
11368 got_worktree_get_root_path(worktree));
11369 if (error)
11370 goto done;
11372 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11373 if (error)
11374 goto done;
11376 cpa.patch_script_file = patch_script_file;
11377 cpa.action = "unstage";
11378 memset(&upa, 0, sizeof(upa));
11379 error = got_worktree_unstage(worktree, &paths, update_progress,
11380 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11381 if (!error)
11382 print_merge_progress_stats(&upa);
11383 done:
11384 if (patch_script_file && fclose(patch_script_file) == EOF &&
11385 error == NULL)
11386 error = got_error_from_errno2("fclose", patch_script_path);
11387 if (repo) {
11388 const struct got_error *close_err = got_repo_close(repo);
11389 if (error == NULL)
11390 error = close_err;
11392 if (worktree)
11393 got_worktree_close(worktree);
11394 TAILQ_FOREACH(pe, &paths, entry)
11395 free((char *)pe->path);
11396 got_pathlist_free(&paths);
11397 free(cwd);
11398 return error;
11401 __dead static void
11402 usage_cat(void)
11404 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11405 "arg1 [arg2 ...]\n", getprogname());
11406 exit(1);
11409 static const struct got_error *
11410 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11412 const struct got_error *err;
11413 struct got_blob_object *blob;
11415 err = got_object_open_as_blob(&blob, repo, id, 8192);
11416 if (err)
11417 return err;
11419 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11420 got_object_blob_close(blob);
11421 return err;
11424 static const struct got_error *
11425 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11427 const struct got_error *err;
11428 struct got_tree_object *tree;
11429 int nentries, i;
11431 err = got_object_open_as_tree(&tree, repo, id);
11432 if (err)
11433 return err;
11435 nentries = got_object_tree_get_nentries(tree);
11436 for (i = 0; i < nentries; i++) {
11437 struct got_tree_entry *te;
11438 char *id_str;
11439 if (sigint_received || sigpipe_received)
11440 break;
11441 te = got_object_tree_get_entry(tree, i);
11442 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11443 if (err)
11444 break;
11445 fprintf(outfile, "%s %.7o %s\n", id_str,
11446 got_tree_entry_get_mode(te),
11447 got_tree_entry_get_name(te));
11448 free(id_str);
11451 got_object_tree_close(tree);
11452 return err;
11455 static const struct got_error *
11456 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11458 const struct got_error *err;
11459 struct got_commit_object *commit;
11460 const struct got_object_id_queue *parent_ids;
11461 struct got_object_qid *pid;
11462 char *id_str = NULL;
11463 const char *logmsg = NULL;
11465 err = got_object_open_as_commit(&commit, repo, id);
11466 if (err)
11467 return err;
11469 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11470 if (err)
11471 goto done;
11473 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11474 parent_ids = got_object_commit_get_parent_ids(commit);
11475 fprintf(outfile, "numparents %d\n",
11476 got_object_commit_get_nparents(commit));
11477 STAILQ_FOREACH(pid, parent_ids, entry) {
11478 char *pid_str;
11479 err = got_object_id_str(&pid_str, pid->id);
11480 if (err)
11481 goto done;
11482 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11483 free(pid_str);
11485 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
11486 got_object_commit_get_author(commit),
11487 (long long)got_object_commit_get_author_time(commit));
11489 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
11490 got_object_commit_get_author(commit),
11491 (long long)got_object_commit_get_committer_time(commit));
11493 logmsg = got_object_commit_get_logmsg_raw(commit);
11494 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11495 fprintf(outfile, "%s", logmsg);
11496 done:
11497 free(id_str);
11498 got_object_commit_close(commit);
11499 return err;
11502 static const struct got_error *
11503 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11505 const struct got_error *err;
11506 struct got_tag_object *tag;
11507 char *id_str = NULL;
11508 const char *tagmsg = NULL;
11510 err = got_object_open_as_tag(&tag, repo, id);
11511 if (err)
11512 return err;
11514 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11515 if (err)
11516 goto done;
11518 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11520 switch (got_object_tag_get_object_type(tag)) {
11521 case GOT_OBJ_TYPE_BLOB:
11522 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11523 GOT_OBJ_LABEL_BLOB);
11524 break;
11525 case GOT_OBJ_TYPE_TREE:
11526 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11527 GOT_OBJ_LABEL_TREE);
11528 break;
11529 case GOT_OBJ_TYPE_COMMIT:
11530 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11531 GOT_OBJ_LABEL_COMMIT);
11532 break;
11533 case GOT_OBJ_TYPE_TAG:
11534 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11535 GOT_OBJ_LABEL_TAG);
11536 break;
11537 default:
11538 break;
11541 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11542 got_object_tag_get_name(tag));
11544 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
11545 got_object_tag_get_tagger(tag),
11546 (long long)got_object_tag_get_tagger_time(tag));
11548 tagmsg = got_object_tag_get_message(tag);
11549 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11550 fprintf(outfile, "%s", tagmsg);
11551 done:
11552 free(id_str);
11553 got_object_tag_close(tag);
11554 return err;
11557 static const struct got_error *
11558 cmd_cat(int argc, char *argv[])
11560 const struct got_error *error;
11561 struct got_repository *repo = NULL;
11562 struct got_worktree *worktree = NULL;
11563 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11564 const char *commit_id_str = NULL;
11565 struct got_object_id *id = NULL, *commit_id = NULL;
11566 int ch, obj_type, i, force_path = 0;
11567 struct got_reflist_head refs;
11569 TAILQ_INIT(&refs);
11571 #ifndef PROFILE
11572 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11573 NULL) == -1)
11574 err(1, "pledge");
11575 #endif
11577 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11578 switch (ch) {
11579 case 'c':
11580 commit_id_str = optarg;
11581 break;
11582 case 'r':
11583 repo_path = realpath(optarg, NULL);
11584 if (repo_path == NULL)
11585 return got_error_from_errno2("realpath",
11586 optarg);
11587 got_path_strip_trailing_slashes(repo_path);
11588 break;
11589 case 'P':
11590 force_path = 1;
11591 break;
11592 default:
11593 usage_cat();
11594 /* NOTREACHED */
11598 argc -= optind;
11599 argv += optind;
11601 cwd = getcwd(NULL, 0);
11602 if (cwd == NULL) {
11603 error = got_error_from_errno("getcwd");
11604 goto done;
11606 error = got_worktree_open(&worktree, cwd);
11607 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11608 goto done;
11609 if (worktree) {
11610 if (repo_path == NULL) {
11611 repo_path = strdup(
11612 got_worktree_get_repo_path(worktree));
11613 if (repo_path == NULL) {
11614 error = got_error_from_errno("strdup");
11615 goto done;
11620 if (repo_path == NULL) {
11621 repo_path = getcwd(NULL, 0);
11622 if (repo_path == NULL)
11623 return got_error_from_errno("getcwd");
11626 error = got_repo_open(&repo, repo_path, NULL);
11627 free(repo_path);
11628 if (error != NULL)
11629 goto done;
11631 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11632 if (error)
11633 goto done;
11635 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11636 if (error)
11637 goto done;
11639 if (commit_id_str == NULL)
11640 commit_id_str = GOT_REF_HEAD;
11641 error = got_repo_match_object_id(&commit_id, NULL,
11642 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11643 if (error)
11644 goto done;
11646 for (i = 0; i < argc; i++) {
11647 if (force_path) {
11648 error = got_object_id_by_path(&id, repo, commit_id,
11649 argv[i]);
11650 if (error)
11651 break;
11652 } else {
11653 error = got_repo_match_object_id(&id, &label, argv[i],
11654 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11655 repo);
11656 if (error) {
11657 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11658 error->code != GOT_ERR_NOT_REF)
11659 break;
11660 error = got_object_id_by_path(&id, repo,
11661 commit_id, argv[i]);
11662 if (error)
11663 break;
11667 error = got_object_get_type(&obj_type, repo, id);
11668 if (error)
11669 break;
11671 switch (obj_type) {
11672 case GOT_OBJ_TYPE_BLOB:
11673 error = cat_blob(id, repo, stdout);
11674 break;
11675 case GOT_OBJ_TYPE_TREE:
11676 error = cat_tree(id, repo, stdout);
11677 break;
11678 case GOT_OBJ_TYPE_COMMIT:
11679 error = cat_commit(id, repo, stdout);
11680 break;
11681 case GOT_OBJ_TYPE_TAG:
11682 error = cat_tag(id, repo, stdout);
11683 break;
11684 default:
11685 error = got_error(GOT_ERR_OBJ_TYPE);
11686 break;
11688 if (error)
11689 break;
11690 free(label);
11691 label = NULL;
11692 free(id);
11693 id = NULL;
11695 done:
11696 free(label);
11697 free(id);
11698 free(commit_id);
11699 if (worktree)
11700 got_worktree_close(worktree);
11701 if (repo) {
11702 const struct got_error *close_err = got_repo_close(repo);
11703 if (error == NULL)
11704 error = close_err;
11706 got_ref_list_free(&refs);
11707 return error;
11710 __dead static void
11711 usage_info(void)
11713 fprintf(stderr, "usage: %s info [path ...]\n",
11714 getprogname());
11715 exit(1);
11718 static const struct got_error *
11719 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11720 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11721 struct got_object_id *commit_id)
11723 const struct got_error *err = NULL;
11724 char *id_str = NULL;
11725 char datebuf[128];
11726 struct tm mytm, *tm;
11727 struct got_pathlist_head *paths = arg;
11728 struct got_pathlist_entry *pe;
11731 * Clear error indication from any of the path arguments which
11732 * would cause this file index entry to be displayed.
11734 TAILQ_FOREACH(pe, paths, entry) {
11735 if (got_path_cmp(path, pe->path, strlen(path),
11736 pe->path_len) == 0 ||
11737 got_path_is_child(path, pe->path, pe->path_len))
11738 pe->data = NULL; /* no error */
11741 printf(GOT_COMMIT_SEP_STR);
11742 if (S_ISLNK(mode))
11743 printf("symlink: %s\n", path);
11744 else if (S_ISREG(mode)) {
11745 printf("file: %s\n", path);
11746 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11747 } else if (S_ISDIR(mode))
11748 printf("directory: %s\n", path);
11749 else
11750 printf("something: %s\n", path);
11752 tm = localtime_r(&mtime, &mytm);
11753 if (tm == NULL)
11754 return NULL;
11755 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11756 return got_error(GOT_ERR_NO_SPACE);
11757 printf("timestamp: %s\n", datebuf);
11759 if (blob_id) {
11760 err = got_object_id_str(&id_str, blob_id);
11761 if (err)
11762 return err;
11763 printf("based on blob: %s\n", id_str);
11764 free(id_str);
11767 if (staged_blob_id) {
11768 err = got_object_id_str(&id_str, staged_blob_id);
11769 if (err)
11770 return err;
11771 printf("based on staged blob: %s\n", id_str);
11772 free(id_str);
11775 if (commit_id) {
11776 err = got_object_id_str(&id_str, commit_id);
11777 if (err)
11778 return err;
11779 printf("based on commit: %s\n", id_str);
11780 free(id_str);
11783 return NULL;
11786 static const struct got_error *
11787 cmd_info(int argc, char *argv[])
11789 const struct got_error *error = NULL;
11790 struct got_worktree *worktree = NULL;
11791 char *cwd = NULL, *id_str = NULL;
11792 struct got_pathlist_head paths;
11793 struct got_pathlist_entry *pe;
11794 char *uuidstr = NULL;
11795 int ch, show_files = 0;
11797 TAILQ_INIT(&paths);
11799 while ((ch = getopt(argc, argv, "")) != -1) {
11800 switch (ch) {
11801 default:
11802 usage_info();
11803 /* NOTREACHED */
11807 argc -= optind;
11808 argv += optind;
11810 #ifndef PROFILE
11811 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11812 NULL) == -1)
11813 err(1, "pledge");
11814 #endif
11815 cwd = getcwd(NULL, 0);
11816 if (cwd == NULL) {
11817 error = got_error_from_errno("getcwd");
11818 goto done;
11821 error = got_worktree_open(&worktree, cwd);
11822 if (error) {
11823 if (error->code == GOT_ERR_NOT_WORKTREE)
11824 error = wrap_not_worktree_error(error, "info", cwd);
11825 goto done;
11828 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11829 if (error)
11830 goto done;
11832 if (argc >= 1) {
11833 error = get_worktree_paths_from_argv(&paths, argc, argv,
11834 worktree);
11835 if (error)
11836 goto done;
11837 show_files = 1;
11840 error = got_object_id_str(&id_str,
11841 got_worktree_get_base_commit_id(worktree));
11842 if (error)
11843 goto done;
11845 error = got_worktree_get_uuid(&uuidstr, worktree);
11846 if (error)
11847 goto done;
11849 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11850 printf("work tree base commit: %s\n", id_str);
11851 printf("work tree path prefix: %s\n",
11852 got_worktree_get_path_prefix(worktree));
11853 printf("work tree branch reference: %s\n",
11854 got_worktree_get_head_ref_name(worktree));
11855 printf("work tree UUID: %s\n", uuidstr);
11856 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11858 if (show_files) {
11859 struct got_pathlist_entry *pe;
11860 TAILQ_FOREACH(pe, &paths, entry) {
11861 if (pe->path_len == 0)
11862 continue;
11864 * Assume this path will fail. This will be corrected
11865 * in print_path_info() in case the path does suceeed.
11867 pe->data = (void *)got_error_path(pe->path,
11868 GOT_ERR_BAD_PATH);
11870 error = got_worktree_path_info(worktree, &paths,
11871 print_path_info, &paths, check_cancelled, NULL);
11872 if (error)
11873 goto done;
11874 TAILQ_FOREACH(pe, &paths, entry) {
11875 if (pe->data != NULL) {
11876 error = pe->data; /* bad path */
11877 break;
11881 done:
11882 TAILQ_FOREACH(pe, &paths, entry)
11883 free((char *)pe->path);
11884 got_pathlist_free(&paths);
11885 free(cwd);
11886 free(id_str);
11887 free(uuidstr);
11888 return error;