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 int i;
3245 if (argc == 0) {
3246 path = strdup("");
3247 if (path == NULL)
3248 return got_error_from_errno("strdup");
3249 return got_pathlist_append(paths, path, NULL);
3252 for (i = 0; i < argc; i++) {
3253 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3254 if (err)
3255 break;
3256 err = got_pathlist_append(paths, path, NULL);
3257 if (err) {
3258 free(path);
3259 break;
3263 return err;
3266 static const struct got_error *
3267 wrap_not_worktree_error(const struct got_error *orig_err,
3268 const char *cmdname, const char *path)
3270 const struct got_error *err;
3271 struct got_repository *repo;
3272 static char msg[512];
3274 err = got_repo_open(&repo, path, NULL);
3275 if (err)
3276 return orig_err;
3278 snprintf(msg, sizeof(msg),
3279 "'got %s' needs a work tree in addition to a git repository\n"
3280 "Work trees can be checked out from this Git repository with "
3281 "'got checkout'.\n"
3282 "The got(1) manual page contains more information.", cmdname);
3283 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3284 got_repo_close(repo);
3285 return err;
3288 static const struct got_error *
3289 cmd_update(int argc, char *argv[])
3291 const struct got_error *error = NULL;
3292 struct got_repository *repo = NULL;
3293 struct got_worktree *worktree = NULL;
3294 char *worktree_path = NULL;
3295 struct got_object_id *commit_id = NULL;
3296 char *commit_id_str = NULL;
3297 const char *branch_name = NULL;
3298 struct got_reference *head_ref = NULL;
3299 struct got_pathlist_head paths;
3300 struct got_pathlist_entry *pe;
3301 int ch, verbosity = 0;
3302 struct got_update_progress_arg upa;
3304 TAILQ_INIT(&paths);
3306 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3307 switch (ch) {
3308 case 'b':
3309 branch_name = optarg;
3310 break;
3311 case 'c':
3312 commit_id_str = strdup(optarg);
3313 if (commit_id_str == NULL)
3314 return got_error_from_errno("strdup");
3315 break;
3316 case 'q':
3317 verbosity = -1;
3318 break;
3319 default:
3320 usage_update();
3321 /* NOTREACHED */
3325 argc -= optind;
3326 argv += optind;
3328 #ifndef PROFILE
3329 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3330 "unveil", NULL) == -1)
3331 err(1, "pledge");
3332 #endif
3333 worktree_path = getcwd(NULL, 0);
3334 if (worktree_path == NULL) {
3335 error = got_error_from_errno("getcwd");
3336 goto done;
3338 error = got_worktree_open(&worktree, worktree_path);
3339 if (error) {
3340 if (error->code == GOT_ERR_NOT_WORKTREE)
3341 error = wrap_not_worktree_error(error, "update",
3342 worktree_path);
3343 goto done;
3346 error = check_rebase_or_histedit_in_progress(worktree);
3347 if (error)
3348 goto done;
3350 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3351 NULL);
3352 if (error != NULL)
3353 goto done;
3355 error = apply_unveil(got_repo_get_path(repo), 0,
3356 got_worktree_get_root_path(worktree));
3357 if (error)
3358 goto done;
3360 error = check_merge_in_progress(worktree, repo);
3361 if (error)
3362 goto done;
3364 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3365 if (error)
3366 goto done;
3368 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3369 got_worktree_get_head_ref_name(worktree), 0);
3370 if (error != NULL)
3371 goto done;
3372 if (commit_id_str == NULL) {
3373 error = got_ref_resolve(&commit_id, repo, head_ref);
3374 if (error != NULL)
3375 goto done;
3376 error = got_object_id_str(&commit_id_str, commit_id);
3377 if (error != NULL)
3378 goto done;
3379 } else {
3380 struct got_reflist_head refs;
3381 TAILQ_INIT(&refs);
3382 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3383 NULL);
3384 if (error)
3385 goto done;
3386 error = got_repo_match_object_id(&commit_id, NULL,
3387 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3388 got_ref_list_free(&refs);
3389 free(commit_id_str);
3390 commit_id_str = NULL;
3391 if (error)
3392 goto done;
3393 error = got_object_id_str(&commit_id_str, commit_id);
3394 if (error)
3395 goto done;
3398 if (branch_name) {
3399 struct got_object_id *head_commit_id;
3400 TAILQ_FOREACH(pe, &paths, entry) {
3401 if (pe->path_len == 0)
3402 continue;
3403 error = got_error_msg(GOT_ERR_BAD_PATH,
3404 "switching between branches requires that "
3405 "the entire work tree gets updated");
3406 goto done;
3408 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3409 if (error)
3410 goto done;
3411 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3412 repo);
3413 free(head_commit_id);
3414 if (error != NULL)
3415 goto done;
3416 error = check_same_branch(commit_id, head_ref, NULL, repo);
3417 if (error)
3418 goto done;
3419 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3420 if (error)
3421 goto done;
3422 } else {
3423 error = check_linear_ancestry(commit_id,
3424 got_worktree_get_base_commit_id(worktree), 0, repo);
3425 if (error != NULL) {
3426 if (error->code == GOT_ERR_ANCESTRY)
3427 error = got_error(GOT_ERR_BRANCH_MOVED);
3428 goto done;
3430 error = check_same_branch(commit_id, head_ref, NULL, repo);
3431 if (error)
3432 goto done;
3435 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3436 commit_id) != 0) {
3437 error = got_worktree_set_base_commit_id(worktree, repo,
3438 commit_id);
3439 if (error)
3440 goto done;
3443 memset(&upa, 0, sizeof(upa));
3444 upa.verbosity = verbosity;
3445 error = got_worktree_checkout_files(worktree, &paths, repo,
3446 update_progress, &upa, check_cancelled, NULL);
3447 if (error != NULL)
3448 goto done;
3450 if (upa.did_something) {
3451 printf("Updated to %s: %s\n",
3452 got_worktree_get_head_ref_name(worktree), commit_id_str);
3453 } else
3454 printf("Already up-to-date\n");
3455 print_update_progress_stats(&upa);
3456 done:
3457 free(worktree_path);
3458 TAILQ_FOREACH(pe, &paths, entry)
3459 free((char *)pe->path);
3460 got_pathlist_free(&paths);
3461 free(commit_id);
3462 free(commit_id_str);
3463 return error;
3466 static const struct got_error *
3467 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3468 const char *path, int diff_context, int ignore_whitespace,
3469 int force_text_diff, struct got_repository *repo)
3471 const struct got_error *err = NULL;
3472 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3474 if (blob_id1) {
3475 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3476 if (err)
3477 goto done;
3480 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3481 if (err)
3482 goto done;
3484 while (path[0] == '/')
3485 path++;
3486 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3487 diff_context, ignore_whitespace, force_text_diff, stdout);
3488 done:
3489 if (blob1)
3490 got_object_blob_close(blob1);
3491 got_object_blob_close(blob2);
3492 return err;
3495 static const struct got_error *
3496 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3497 const char *path, int diff_context, int ignore_whitespace,
3498 int force_text_diff, struct got_repository *repo)
3500 const struct got_error *err = NULL;
3501 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3502 struct got_diff_blob_output_unidiff_arg arg;
3504 if (tree_id1) {
3505 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3506 if (err)
3507 goto done;
3510 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3511 if (err)
3512 goto done;
3514 arg.diff_context = diff_context;
3515 arg.ignore_whitespace = ignore_whitespace;
3516 arg.force_text_diff = force_text_diff;
3517 arg.outfile = stdout;
3518 arg.line_offsets = NULL;
3519 arg.nlines = 0;
3520 while (path[0] == '/')
3521 path++;
3522 err = got_diff_tree(tree1, tree2, path, path, repo,
3523 got_diff_blob_output_unidiff, &arg, 1);
3524 done:
3525 if (tree1)
3526 got_object_tree_close(tree1);
3527 if (tree2)
3528 got_object_tree_close(tree2);
3529 return err;
3532 static const struct got_error *
3533 get_changed_paths(struct got_pathlist_head *paths,
3534 struct got_commit_object *commit, struct got_repository *repo)
3536 const struct got_error *err = NULL;
3537 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3538 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3539 struct got_object_qid *qid;
3541 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3542 if (qid != NULL) {
3543 struct got_commit_object *pcommit;
3544 err = got_object_open_as_commit(&pcommit, repo,
3545 qid->id);
3546 if (err)
3547 return err;
3549 tree_id1 = got_object_id_dup(
3550 got_object_commit_get_tree_id(pcommit));
3551 if (tree_id1 == NULL) {
3552 got_object_commit_close(pcommit);
3553 return got_error_from_errno("got_object_id_dup");
3555 got_object_commit_close(pcommit);
3559 if (tree_id1) {
3560 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3561 if (err)
3562 goto done;
3565 tree_id2 = got_object_commit_get_tree_id(commit);
3566 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3567 if (err)
3568 goto done;
3570 err = got_diff_tree(tree1, tree2, "", "", repo,
3571 got_diff_tree_collect_changed_paths, paths, 0);
3572 done:
3573 if (tree1)
3574 got_object_tree_close(tree1);
3575 if (tree2)
3576 got_object_tree_close(tree2);
3577 free(tree_id1);
3578 return err;
3581 static const struct got_error *
3582 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3583 const char *path, int diff_context, struct got_repository *repo)
3585 const struct got_error *err = NULL;
3586 struct got_commit_object *pcommit = NULL;
3587 char *id_str1 = NULL, *id_str2 = NULL;
3588 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3589 struct got_object_qid *qid;
3591 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3592 if (qid != NULL) {
3593 err = got_object_open_as_commit(&pcommit, repo,
3594 qid->id);
3595 if (err)
3596 return err;
3599 if (path && path[0] != '\0') {
3600 int obj_type;
3601 err = got_object_id_by_path(&obj_id2, repo, id, path);
3602 if (err)
3603 goto done;
3604 err = got_object_id_str(&id_str2, obj_id2);
3605 if (err) {
3606 free(obj_id2);
3607 goto done;
3609 if (pcommit) {
3610 err = got_object_id_by_path(&obj_id1, repo,
3611 qid->id, path);
3612 if (err) {
3613 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3614 free(obj_id2);
3615 goto done;
3617 } else {
3618 err = got_object_id_str(&id_str1, obj_id1);
3619 if (err) {
3620 free(obj_id2);
3621 goto done;
3625 err = got_object_get_type(&obj_type, repo, obj_id2);
3626 if (err) {
3627 free(obj_id2);
3628 goto done;
3630 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3631 switch (obj_type) {
3632 case GOT_OBJ_TYPE_BLOB:
3633 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3634 0, 0, repo);
3635 break;
3636 case GOT_OBJ_TYPE_TREE:
3637 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3638 0, 0, repo);
3639 break;
3640 default:
3641 err = got_error(GOT_ERR_OBJ_TYPE);
3642 break;
3644 free(obj_id1);
3645 free(obj_id2);
3646 } else {
3647 obj_id2 = got_object_commit_get_tree_id(commit);
3648 err = got_object_id_str(&id_str2, obj_id2);
3649 if (err)
3650 goto done;
3651 if (pcommit) {
3652 obj_id1 = got_object_commit_get_tree_id(pcommit);
3653 err = got_object_id_str(&id_str1, obj_id1);
3654 if (err)
3655 goto done;
3657 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3658 id_str2);
3659 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3660 repo);
3662 done:
3663 free(id_str1);
3664 free(id_str2);
3665 if (pcommit)
3666 got_object_commit_close(pcommit);
3667 return err;
3670 static char *
3671 get_datestr(time_t *time, char *datebuf)
3673 struct tm mytm, *tm;
3674 char *p, *s;
3676 tm = gmtime_r(time, &mytm);
3677 if (tm == NULL)
3678 return NULL;
3679 s = asctime_r(tm, datebuf);
3680 if (s == NULL)
3681 return NULL;
3682 p = strchr(s, '\n');
3683 if (p)
3684 *p = '\0';
3685 return s;
3688 static const struct got_error *
3689 match_logmsg(int *have_match, struct got_object_id *id,
3690 struct got_commit_object *commit, regex_t *regex)
3692 const struct got_error *err = NULL;
3693 regmatch_t regmatch;
3694 char *id_str = NULL, *logmsg = NULL;
3696 *have_match = 0;
3698 err = got_object_id_str(&id_str, id);
3699 if (err)
3700 return err;
3702 err = got_object_commit_get_logmsg(&logmsg, commit);
3703 if (err)
3704 goto done;
3706 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3707 *have_match = 1;
3708 done:
3709 free(id_str);
3710 free(logmsg);
3711 return err;
3714 static void
3715 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3716 regex_t *regex)
3718 regmatch_t regmatch;
3719 struct got_pathlist_entry *pe;
3721 *have_match = 0;
3723 TAILQ_FOREACH(pe, changed_paths, entry) {
3724 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3725 *have_match = 1;
3726 break;
3731 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3733 static const struct got_error*
3734 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3735 struct got_object_id *id, struct got_repository *repo)
3737 static const struct got_error *err = NULL;
3738 struct got_reflist_entry *re;
3739 char *s;
3740 const char *name;
3742 *refs_str = NULL;
3744 TAILQ_FOREACH(re, refs, entry) {
3745 struct got_tag_object *tag = NULL;
3746 struct got_object_id *ref_id;
3747 int cmp;
3749 name = got_ref_get_name(re->ref);
3750 if (strcmp(name, GOT_REF_HEAD) == 0)
3751 continue;
3752 if (strncmp(name, "refs/", 5) == 0)
3753 name += 5;
3754 if (strncmp(name, "got/", 4) == 0)
3755 continue;
3756 if (strncmp(name, "heads/", 6) == 0)
3757 name += 6;
3758 if (strncmp(name, "remotes/", 8) == 0) {
3759 name += 8;
3760 s = strstr(name, "/" GOT_REF_HEAD);
3761 if (s != NULL && s[strlen(s)] == '\0')
3762 continue;
3764 err = got_ref_resolve(&ref_id, repo, re->ref);
3765 if (err)
3766 break;
3767 if (strncmp(name, "tags/", 5) == 0) {
3768 err = got_object_open_as_tag(&tag, repo, ref_id);
3769 if (err) {
3770 if (err->code != GOT_ERR_OBJ_TYPE) {
3771 free(ref_id);
3772 break;
3774 /* Ref points at something other than a tag. */
3775 err = NULL;
3776 tag = NULL;
3779 cmp = got_object_id_cmp(tag ?
3780 got_object_tag_get_object_id(tag) : ref_id, id);
3781 free(ref_id);
3782 if (tag)
3783 got_object_tag_close(tag);
3784 if (cmp != 0)
3785 continue;
3786 s = *refs_str;
3787 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3788 s ? ", " : "", name) == -1) {
3789 err = got_error_from_errno("asprintf");
3790 free(s);
3791 *refs_str = NULL;
3792 break;
3794 free(s);
3797 return err;
3800 static const struct got_error *
3801 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3802 struct got_repository *repo, const char *path,
3803 struct got_pathlist_head *changed_paths, int show_patch,
3804 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3805 const char *custom_refs_str)
3807 const struct got_error *err = NULL;
3808 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3809 char datebuf[26];
3810 time_t committer_time;
3811 const char *author, *committer;
3812 char *refs_str = NULL;
3814 err = got_object_id_str(&id_str, id);
3815 if (err)
3816 return err;
3818 if (custom_refs_str == NULL) {
3819 struct got_reflist_head *refs;
3820 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3821 if (refs) {
3822 err = build_refs_str(&refs_str, refs, id, repo);
3823 if (err)
3824 goto done;
3828 printf(GOT_COMMIT_SEP_STR);
3829 if (custom_refs_str)
3830 printf("commit %s (%s)\n", id_str, custom_refs_str);
3831 else
3832 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3833 refs_str ? refs_str : "", refs_str ? ")" : "");
3834 free(id_str);
3835 id_str = NULL;
3836 free(refs_str);
3837 refs_str = NULL;
3838 printf("from: %s\n", got_object_commit_get_author(commit));
3839 committer_time = got_object_commit_get_committer_time(commit);
3840 datestr = get_datestr(&committer_time, datebuf);
3841 if (datestr)
3842 printf("date: %s UTC\n", datestr);
3843 author = got_object_commit_get_author(commit);
3844 committer = got_object_commit_get_committer(commit);
3845 if (strcmp(author, committer) != 0)
3846 printf("via: %s\n", committer);
3847 if (got_object_commit_get_nparents(commit) > 1) {
3848 const struct got_object_id_queue *parent_ids;
3849 struct got_object_qid *qid;
3850 int n = 1;
3851 parent_ids = got_object_commit_get_parent_ids(commit);
3852 STAILQ_FOREACH(qid, parent_ids, entry) {
3853 err = got_object_id_str(&id_str, qid->id);
3854 if (err)
3855 goto done;
3856 printf("parent %d: %s\n", n++, id_str);
3857 free(id_str);
3858 id_str = NULL;
3862 err = got_object_commit_get_logmsg(&logmsg0, commit);
3863 if (err)
3864 goto done;
3866 logmsg = logmsg0;
3867 do {
3868 line = strsep(&logmsg, "\n");
3869 if (line)
3870 printf(" %s\n", line);
3871 } while (line);
3872 free(logmsg0);
3874 if (changed_paths) {
3875 struct got_pathlist_entry *pe;
3876 TAILQ_FOREACH(pe, changed_paths, entry) {
3877 struct got_diff_changed_path *cp = pe->data;
3878 printf(" %c %s\n", cp->status, pe->path);
3880 printf("\n");
3882 if (show_patch) {
3883 err = print_patch(commit, id, path, diff_context, repo);
3884 if (err == 0)
3885 printf("\n");
3888 if (fflush(stdout) != 0 && err == NULL)
3889 err = got_error_from_errno("fflush");
3890 done:
3891 free(id_str);
3892 free(refs_str);
3893 return err;
3896 static const struct got_error *
3897 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3898 struct got_repository *repo, const char *path, int show_changed_paths,
3899 int show_patch, const char *search_pattern, int diff_context, int limit,
3900 int log_branches, int reverse_display_order,
3901 struct got_reflist_object_id_map *refs_idmap)
3903 const struct got_error *err;
3904 struct got_commit_graph *graph;
3905 regex_t regex;
3906 int have_match;
3907 struct got_object_id_queue reversed_commits;
3908 struct got_object_qid *qid;
3909 struct got_commit_object *commit;
3910 struct got_pathlist_head changed_paths;
3911 struct got_pathlist_entry *pe;
3913 STAILQ_INIT(&reversed_commits);
3914 TAILQ_INIT(&changed_paths);
3916 if (search_pattern && regcomp(&regex, search_pattern,
3917 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3918 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3920 err = got_commit_graph_open(&graph, path, !log_branches);
3921 if (err)
3922 return err;
3923 err = got_commit_graph_iter_start(graph, root_id, repo,
3924 check_cancelled, NULL);
3925 if (err)
3926 goto done;
3927 for (;;) {
3928 struct got_object_id *id;
3930 if (sigint_received || sigpipe_received)
3931 break;
3933 err = got_commit_graph_iter_next(&id, graph, repo,
3934 check_cancelled, NULL);
3935 if (err) {
3936 if (err->code == GOT_ERR_ITER_COMPLETED)
3937 err = NULL;
3938 break;
3940 if (id == NULL)
3941 break;
3943 err = got_object_open_as_commit(&commit, repo, id);
3944 if (err)
3945 break;
3947 if (show_changed_paths && !reverse_display_order) {
3948 err = get_changed_paths(&changed_paths, commit, repo);
3949 if (err)
3950 break;
3953 if (search_pattern) {
3954 err = match_logmsg(&have_match, id, commit, &regex);
3955 if (err) {
3956 got_object_commit_close(commit);
3957 break;
3959 if (have_match == 0 && show_changed_paths)
3960 match_changed_paths(&have_match,
3961 &changed_paths, &regex);
3962 if (have_match == 0) {
3963 got_object_commit_close(commit);
3964 TAILQ_FOREACH(pe, &changed_paths, entry) {
3965 free((char *)pe->path);
3966 free(pe->data);
3968 got_pathlist_free(&changed_paths);
3969 continue;
3973 if (reverse_display_order) {
3974 err = got_object_qid_alloc(&qid, id);
3975 if (err)
3976 break;
3977 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3978 got_object_commit_close(commit);
3979 } else {
3980 err = print_commit(commit, id, repo, path,
3981 show_changed_paths ? &changed_paths : NULL,
3982 show_patch, diff_context, refs_idmap, NULL);
3983 got_object_commit_close(commit);
3984 if (err)
3985 break;
3987 if ((limit && --limit == 0) ||
3988 (end_id && got_object_id_cmp(id, end_id) == 0))
3989 break;
3991 TAILQ_FOREACH(pe, &changed_paths, entry) {
3992 free((char *)pe->path);
3993 free(pe->data);
3995 got_pathlist_free(&changed_paths);
3997 if (reverse_display_order) {
3998 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3999 err = got_object_open_as_commit(&commit, repo, qid->id);
4000 if (err)
4001 break;
4002 if (show_changed_paths) {
4003 err = get_changed_paths(&changed_paths,
4004 commit, repo);
4005 if (err)
4006 break;
4008 err = print_commit(commit, qid->id, repo, path,
4009 show_changed_paths ? &changed_paths : NULL,
4010 show_patch, diff_context, refs_idmap, NULL);
4011 got_object_commit_close(commit);
4012 if (err)
4013 break;
4014 TAILQ_FOREACH(pe, &changed_paths, entry) {
4015 free((char *)pe->path);
4016 free(pe->data);
4018 got_pathlist_free(&changed_paths);
4021 done:
4022 while (!STAILQ_EMPTY(&reversed_commits)) {
4023 qid = STAILQ_FIRST(&reversed_commits);
4024 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4025 got_object_qid_free(qid);
4027 TAILQ_FOREACH(pe, &changed_paths, entry) {
4028 free((char *)pe->path);
4029 free(pe->data);
4031 got_pathlist_free(&changed_paths);
4032 if (search_pattern)
4033 regfree(&regex);
4034 got_commit_graph_close(graph);
4035 return err;
4038 __dead static void
4039 usage_log(void)
4041 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4042 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4043 "[-R] [path]\n", getprogname());
4044 exit(1);
4047 static int
4048 get_default_log_limit(void)
4050 const char *got_default_log_limit;
4051 long long n;
4052 const char *errstr;
4054 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4055 if (got_default_log_limit == NULL)
4056 return 0;
4057 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4058 if (errstr != NULL)
4059 return 0;
4060 return n;
4063 static const struct got_error *
4064 cmd_log(int argc, char *argv[])
4066 const struct got_error *error;
4067 struct got_repository *repo = NULL;
4068 struct got_worktree *worktree = NULL;
4069 struct got_object_id *start_id = NULL, *end_id = NULL;
4070 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4071 const char *start_commit = NULL, *end_commit = NULL;
4072 const char *search_pattern = NULL;
4073 int diff_context = -1, ch;
4074 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4075 int reverse_display_order = 0;
4076 const char *errstr;
4077 struct got_reflist_head refs;
4078 struct got_reflist_object_id_map *refs_idmap = NULL;
4080 TAILQ_INIT(&refs);
4082 #ifndef PROFILE
4083 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4084 NULL)
4085 == -1)
4086 err(1, "pledge");
4087 #endif
4089 limit = get_default_log_limit();
4091 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4092 switch (ch) {
4093 case 'p':
4094 show_patch = 1;
4095 break;
4096 case 'P':
4097 show_changed_paths = 1;
4098 break;
4099 case 'c':
4100 start_commit = optarg;
4101 break;
4102 case 'C':
4103 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4104 &errstr);
4105 if (errstr != NULL)
4106 err(1, "-C option %s", errstr);
4107 break;
4108 case 'l':
4109 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4110 if (errstr != NULL)
4111 err(1, "-l option %s", errstr);
4112 break;
4113 case 'b':
4114 log_branches = 1;
4115 break;
4116 case 'r':
4117 repo_path = realpath(optarg, NULL);
4118 if (repo_path == NULL)
4119 return got_error_from_errno2("realpath",
4120 optarg);
4121 got_path_strip_trailing_slashes(repo_path);
4122 break;
4123 case 'R':
4124 reverse_display_order = 1;
4125 break;
4126 case 's':
4127 search_pattern = optarg;
4128 break;
4129 case 'x':
4130 end_commit = optarg;
4131 break;
4132 default:
4133 usage_log();
4134 /* NOTREACHED */
4138 argc -= optind;
4139 argv += optind;
4141 if (diff_context == -1)
4142 diff_context = 3;
4143 else if (!show_patch)
4144 errx(1, "-C requires -p");
4146 cwd = getcwd(NULL, 0);
4147 if (cwd == NULL) {
4148 error = got_error_from_errno("getcwd");
4149 goto done;
4152 if (repo_path == NULL) {
4153 error = got_worktree_open(&worktree, cwd);
4154 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4155 goto done;
4156 error = NULL;
4159 if (argc == 1) {
4160 if (worktree) {
4161 error = got_worktree_resolve_path(&path, worktree,
4162 argv[0]);
4163 if (error)
4164 goto done;
4165 } else {
4166 path = strdup(argv[0]);
4167 if (path == NULL) {
4168 error = got_error_from_errno("strdup");
4169 goto done;
4172 } else if (argc != 0)
4173 usage_log();
4175 if (repo_path == NULL) {
4176 repo_path = worktree ?
4177 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4179 if (repo_path == NULL) {
4180 error = got_error_from_errno("strdup");
4181 goto done;
4184 error = got_repo_open(&repo, repo_path, NULL);
4185 if (error != NULL)
4186 goto done;
4188 error = apply_unveil(got_repo_get_path(repo), 1,
4189 worktree ? got_worktree_get_root_path(worktree) : NULL);
4190 if (error)
4191 goto done;
4193 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4194 if (error)
4195 goto done;
4197 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4198 if (error)
4199 goto done;
4201 if (start_commit == NULL) {
4202 struct got_reference *head_ref;
4203 struct got_commit_object *commit = NULL;
4204 error = got_ref_open(&head_ref, repo,
4205 worktree ? got_worktree_get_head_ref_name(worktree)
4206 : GOT_REF_HEAD, 0);
4207 if (error != NULL)
4208 goto done;
4209 error = got_ref_resolve(&start_id, repo, head_ref);
4210 got_ref_close(head_ref);
4211 if (error != NULL)
4212 goto done;
4213 error = got_object_open_as_commit(&commit, repo,
4214 start_id);
4215 if (error != NULL)
4216 goto done;
4217 got_object_commit_close(commit);
4218 } else {
4219 error = got_repo_match_object_id(&start_id, NULL,
4220 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4221 if (error != NULL)
4222 goto done;
4224 if (end_commit != NULL) {
4225 error = got_repo_match_object_id(&end_id, NULL,
4226 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4227 if (error != NULL)
4228 goto done;
4231 if (worktree) {
4233 * If a path was specified on the command line it was resolved
4234 * to a path in the work tree above. Prepend the work tree's
4235 * path prefix to obtain the corresponding in-repository path.
4237 if (path) {
4238 const char *prefix;
4239 prefix = got_worktree_get_path_prefix(worktree);
4240 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4241 (path[0] != '\0') ? "/" : "", path) == -1) {
4242 error = got_error_from_errno("asprintf");
4243 goto done;
4246 } else
4247 error = got_repo_map_path(&in_repo_path, repo,
4248 path ? path : "");
4249 if (error != NULL)
4250 goto done;
4251 if (in_repo_path) {
4252 free(path);
4253 path = in_repo_path;
4256 error = print_commits(start_id, end_id, repo, path ? path : "",
4257 show_changed_paths, show_patch, search_pattern, diff_context,
4258 limit, log_branches, reverse_display_order, refs_idmap);
4259 done:
4260 free(path);
4261 free(repo_path);
4262 free(cwd);
4263 if (worktree)
4264 got_worktree_close(worktree);
4265 if (repo) {
4266 const struct got_error *close_err = got_repo_close(repo);
4267 if (error == NULL)
4268 error = close_err;
4270 if (refs_idmap)
4271 got_reflist_object_id_map_free(refs_idmap);
4272 got_ref_list_free(&refs);
4273 return error;
4276 __dead static void
4277 usage_diff(void)
4279 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4280 "[-s] [-w] [-P] [object1 object2 | path ...]\n", getprogname());
4281 exit(1);
4284 struct print_diff_arg {
4285 struct got_repository *repo;
4286 struct got_worktree *worktree;
4287 int diff_context;
4288 const char *id_str;
4289 int header_shown;
4290 int diff_staged;
4291 int ignore_whitespace;
4292 int force_text_diff;
4296 * Create a file which contains the target path of a symlink so we can feed
4297 * it as content to the diff engine.
4299 static const struct got_error *
4300 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4301 const char *abspath)
4303 const struct got_error *err = NULL;
4304 char target_path[PATH_MAX];
4305 ssize_t target_len, outlen;
4307 *fd = -1;
4309 if (dirfd != -1) {
4310 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4311 if (target_len == -1)
4312 return got_error_from_errno2("readlinkat", abspath);
4313 } else {
4314 target_len = readlink(abspath, target_path, PATH_MAX);
4315 if (target_len == -1)
4316 return got_error_from_errno2("readlink", abspath);
4319 *fd = got_opentempfd();
4320 if (*fd == -1)
4321 return got_error_from_errno("got_opentempfd");
4323 outlen = write(*fd, target_path, target_len);
4324 if (outlen == -1) {
4325 err = got_error_from_errno("got_opentempfd");
4326 goto done;
4329 if (lseek(*fd, 0, SEEK_SET) == -1) {
4330 err = got_error_from_errno2("lseek", abspath);
4331 goto done;
4333 done:
4334 if (err) {
4335 close(*fd);
4336 *fd = -1;
4338 return err;
4341 static const struct got_error *
4342 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4343 const char *path, struct got_object_id *blob_id,
4344 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4345 int dirfd, const char *de_name)
4347 struct print_diff_arg *a = arg;
4348 const struct got_error *err = NULL;
4349 struct got_blob_object *blob1 = NULL;
4350 int fd = -1;
4351 FILE *f2 = NULL;
4352 char *abspath = NULL, *label1 = NULL;
4353 struct stat sb;
4355 if (a->diff_staged) {
4356 if (staged_status != GOT_STATUS_MODIFY &&
4357 staged_status != GOT_STATUS_ADD &&
4358 staged_status != GOT_STATUS_DELETE)
4359 return NULL;
4360 } else {
4361 if (staged_status == GOT_STATUS_DELETE)
4362 return NULL;
4363 if (status == GOT_STATUS_NONEXISTENT)
4364 return got_error_set_errno(ENOENT, path);
4365 if (status != GOT_STATUS_MODIFY &&
4366 status != GOT_STATUS_ADD &&
4367 status != GOT_STATUS_DELETE &&
4368 status != GOT_STATUS_CONFLICT)
4369 return NULL;
4372 if (!a->header_shown) {
4373 printf("diff %s %s%s\n", a->id_str,
4374 got_worktree_get_root_path(a->worktree),
4375 a->diff_staged ? " (staged changes)" : "");
4376 a->header_shown = 1;
4379 if (a->diff_staged) {
4380 const char *label1 = NULL, *label2 = NULL;
4381 switch (staged_status) {
4382 case GOT_STATUS_MODIFY:
4383 label1 = path;
4384 label2 = path;
4385 break;
4386 case GOT_STATUS_ADD:
4387 label2 = path;
4388 break;
4389 case GOT_STATUS_DELETE:
4390 label1 = path;
4391 break;
4392 default:
4393 return got_error(GOT_ERR_FILE_STATUS);
4395 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4396 staged_blob_id, label1, label2, a->diff_context,
4397 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4400 if (staged_status == GOT_STATUS_ADD ||
4401 staged_status == GOT_STATUS_MODIFY) {
4402 char *id_str;
4403 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4404 8192);
4405 if (err)
4406 goto done;
4407 err = got_object_id_str(&id_str, staged_blob_id);
4408 if (err)
4409 goto done;
4410 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4411 err = got_error_from_errno("asprintf");
4412 free(id_str);
4413 goto done;
4415 free(id_str);
4416 } else if (status != GOT_STATUS_ADD) {
4417 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4418 if (err)
4419 goto done;
4422 if (status != GOT_STATUS_DELETE) {
4423 if (asprintf(&abspath, "%s/%s",
4424 got_worktree_get_root_path(a->worktree), path) == -1) {
4425 err = got_error_from_errno("asprintf");
4426 goto done;
4429 if (dirfd != -1) {
4430 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4431 if (fd == -1) {
4432 if (!got_err_open_nofollow_on_symlink()) {
4433 err = got_error_from_errno2("openat",
4434 abspath);
4435 goto done;
4437 err = get_symlink_target_file(&fd, dirfd,
4438 de_name, abspath);
4439 if (err)
4440 goto done;
4442 } else {
4443 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4444 if (fd == -1) {
4445 if (!got_err_open_nofollow_on_symlink()) {
4446 err = got_error_from_errno2("open",
4447 abspath);
4448 goto done;
4450 err = get_symlink_target_file(&fd, dirfd,
4451 de_name, abspath);
4452 if (err)
4453 goto done;
4456 if (fstat(fd, &sb) == -1) {
4457 err = got_error_from_errno2("fstat", abspath);
4458 goto done;
4460 f2 = fdopen(fd, "r");
4461 if (f2 == NULL) {
4462 err = got_error_from_errno2("fdopen", abspath);
4463 goto done;
4465 fd = -1;
4466 } else
4467 sb.st_size = 0;
4469 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4470 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4471 done:
4472 if (blob1)
4473 got_object_blob_close(blob1);
4474 if (f2 && fclose(f2) == EOF && err == NULL)
4475 err = got_error_from_errno("fclose");
4476 if (fd != -1 && close(fd) == -1 && err == NULL)
4477 err = got_error_from_errno("close");
4478 free(abspath);
4479 return err;
4482 static const struct got_error *
4483 cmd_diff(int argc, char *argv[])
4485 const struct got_error *error;
4486 struct got_repository *repo = NULL;
4487 struct got_worktree *worktree = NULL;
4488 char *cwd = NULL, *repo_path = NULL;
4489 struct got_object_id *ids[2] = { NULL, NULL };
4490 char *labels[2] = { NULL, NULL };
4491 int type1, type2;
4492 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4493 int force_text_diff = 0, force_path = 0, rflag = 0;
4494 const char *errstr;
4495 struct got_reflist_head refs;
4496 struct got_pathlist_head paths;
4497 struct got_pathlist_entry *pe;
4499 TAILQ_INIT(&refs);
4500 TAILQ_INIT(&paths);
4502 #ifndef PROFILE
4503 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4504 NULL) == -1)
4505 err(1, "pledge");
4506 #endif
4508 while ((ch = getopt(argc, argv, "aC:r:swP")) != -1) {
4509 switch (ch) {
4510 case 'a':
4511 force_text_diff = 1;
4512 break;
4513 case 'C':
4514 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4515 &errstr);
4516 if (errstr != NULL)
4517 err(1, "-C option %s", errstr);
4518 break;
4519 case 'r':
4520 repo_path = realpath(optarg, NULL);
4521 if (repo_path == NULL)
4522 return got_error_from_errno2("realpath",
4523 optarg);
4524 got_path_strip_trailing_slashes(repo_path);
4525 rflag = 1;
4526 break;
4527 case 's':
4528 diff_staged = 1;
4529 break;
4530 case 'w':
4531 ignore_whitespace = 1;
4532 break;
4533 case 'P':
4534 force_path = 1;
4535 break;
4536 default:
4537 usage_diff();
4538 /* NOTREACHED */
4542 argc -= optind;
4543 argv += optind;
4545 cwd = getcwd(NULL, 0);
4546 if (cwd == NULL) {
4547 error = got_error_from_errno("getcwd");
4548 goto done;
4551 if (repo_path == NULL) {
4552 error = got_worktree_open(&worktree, cwd);
4553 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4554 goto done;
4555 else
4556 error = NULL;
4557 if (worktree) {
4558 repo_path =
4559 strdup(got_worktree_get_repo_path(worktree));
4560 if (repo_path == NULL) {
4561 error = got_error_from_errno("strdup");
4562 goto done;
4564 } else {
4565 repo_path = strdup(cwd);
4566 if (repo_path == NULL) {
4567 error = got_error_from_errno("strdup");
4568 goto done;
4573 if (worktree) {
4574 repo_path = strdup(got_worktree_get_repo_path(worktree));
4575 if (repo_path == NULL) {
4576 error = got_error_from_errno("strdup");
4577 goto done;
4579 } else {
4580 if (repo_path == NULL) {
4581 repo_path = strdup(cwd);
4582 if (repo_path == NULL) {
4583 error = got_error_from_errno("strdup");
4584 goto done;
4589 if (force_path && (rflag || worktree == NULL))
4590 errx(1, "-P option can only be used when diffing a work tree");
4592 error = got_repo_open(&repo, repo_path, NULL);
4593 free(repo_path);
4594 if (error != NULL)
4595 goto done;
4597 error = apply_unveil(got_repo_get_path(repo), 1,
4598 worktree ? got_worktree_get_root_path(worktree) : NULL);
4599 if (error)
4600 goto done;
4602 if (!force_path && argc == 2) {
4603 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4604 NULL);
4605 if (error)
4606 goto done;
4607 for (i = 0; i < argc; i++) {
4608 error = got_repo_match_object_id(&ids[i], &labels[i],
4609 argv[i], GOT_OBJ_TYPE_ANY, &refs, repo);
4610 if (error) {
4611 if (error->code != GOT_ERR_NOT_REF &&
4612 error->code != GOT_ERR_NO_OBJ)
4613 goto done;
4614 error = NULL;
4615 break;
4620 if (worktree != NULL && (ids[0] == NULL || ids[1] == NULL)) {
4621 error = get_worktree_paths_from_argv(&paths,
4622 argc, argv, worktree);
4623 if (error)
4624 goto done;
4627 if (!TAILQ_EMPTY(&paths)) {
4628 struct print_diff_arg arg;
4629 char *id_str;
4631 error = got_object_id_str(&id_str,
4632 got_worktree_get_base_commit_id(worktree));
4633 if (error)
4634 goto done;
4635 arg.repo = repo;
4636 arg.worktree = worktree;
4637 arg.diff_context = diff_context;
4638 arg.id_str = id_str;
4639 arg.header_shown = 0;
4640 arg.diff_staged = diff_staged;
4641 arg.ignore_whitespace = ignore_whitespace;
4642 arg.force_text_diff = force_text_diff;
4644 error = got_worktree_status(worktree, &paths, repo, 0,
4645 print_diff, &arg, check_cancelled, NULL);
4646 free(id_str);
4647 goto done;
4650 if (ids[0] == NULL || ids[1] == NULL) {
4651 if (argc == 2) {
4652 error = got_error_fmt(GOT_ERR_NO_OBJ, "%s",
4653 ids[0] ? argv[1] : argv[0]);
4654 goto done;
4655 } if (worktree == NULL) {
4656 error = got_error(GOT_ERR_NOT_WORKTREE);
4657 goto done;
4658 } else
4659 usage_diff();
4661 if (diff_staged)
4662 errx(1, "-s option can't be used when diffing "
4663 "objects in repository");
4665 error = got_object_get_type(&type1, repo, ids[0]);
4666 if (error)
4667 goto done;
4669 error = got_object_get_type(&type2, repo, ids[1]);
4670 if (error)
4671 goto done;
4672 if (type1 != type2) {
4673 error = got_error(GOT_ERR_OBJ_TYPE);
4674 goto done;
4677 switch (type1) {
4678 case GOT_OBJ_TYPE_BLOB:
4679 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4680 NULL, NULL, diff_context, ignore_whitespace,
4681 force_text_diff, repo, stdout);
4682 break;
4683 case GOT_OBJ_TYPE_TREE:
4684 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4685 "", "", diff_context, ignore_whitespace, force_text_diff,
4686 repo, stdout);
4687 break;
4688 case GOT_OBJ_TYPE_COMMIT:
4689 printf("diff %s %s\n", labels[0], labels[1]);
4690 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4691 diff_context, ignore_whitespace, force_text_diff, repo,
4692 stdout);
4693 break;
4694 default:
4695 error = got_error(GOT_ERR_OBJ_TYPE);
4697 done:
4698 free(labels[0]);
4699 free(labels[1]);
4700 free(ids[0]);
4701 free(ids[1]);
4702 if (worktree)
4703 got_worktree_close(worktree);
4704 if (repo) {
4705 const struct got_error *close_err = got_repo_close(repo);
4706 if (error == NULL)
4707 error = close_err;
4709 TAILQ_FOREACH(pe, &paths, entry)
4710 free((char *)pe->path);
4711 got_pathlist_free(&paths);
4712 got_ref_list_free(&refs);
4713 return error;
4716 __dead static void
4717 usage_blame(void)
4719 fprintf(stderr,
4720 "usage: %s blame [-c commit] [-r repository-path] path\n",
4721 getprogname());
4722 exit(1);
4725 struct blame_line {
4726 int annotated;
4727 char *id_str;
4728 char *committer;
4729 char datebuf[11]; /* YYYY-MM-DD + NUL */
4732 struct blame_cb_args {
4733 struct blame_line *lines;
4734 int nlines;
4735 int nlines_prec;
4736 int lineno_cur;
4737 off_t *line_offsets;
4738 FILE *f;
4739 struct got_repository *repo;
4742 static const struct got_error *
4743 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4745 const struct got_error *err = NULL;
4746 struct blame_cb_args *a = arg;
4747 struct blame_line *bline;
4748 char *line = NULL;
4749 size_t linesize = 0;
4750 struct got_commit_object *commit = NULL;
4751 off_t offset;
4752 struct tm tm;
4753 time_t committer_time;
4755 if (nlines != a->nlines ||
4756 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4757 return got_error(GOT_ERR_RANGE);
4759 if (sigint_received)
4760 return got_error(GOT_ERR_ITER_COMPLETED);
4762 if (lineno == -1)
4763 return NULL; /* no change in this commit */
4765 /* Annotate this line. */
4766 bline = &a->lines[lineno - 1];
4767 if (bline->annotated)
4768 return NULL;
4769 err = got_object_id_str(&bline->id_str, id);
4770 if (err)
4771 return err;
4773 err = got_object_open_as_commit(&commit, a->repo, id);
4774 if (err)
4775 goto done;
4777 bline->committer = strdup(got_object_commit_get_committer(commit));
4778 if (bline->committer == NULL) {
4779 err = got_error_from_errno("strdup");
4780 goto done;
4783 committer_time = got_object_commit_get_committer_time(commit);
4784 if (gmtime_r(&committer_time, &tm) == NULL)
4785 return got_error_from_errno("gmtime_r");
4786 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4787 &tm) == 0) {
4788 err = got_error(GOT_ERR_NO_SPACE);
4789 goto done;
4791 bline->annotated = 1;
4793 /* Print lines annotated so far. */
4794 bline = &a->lines[a->lineno_cur - 1];
4795 if (!bline->annotated)
4796 goto done;
4798 offset = a->line_offsets[a->lineno_cur - 1];
4799 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4800 err = got_error_from_errno("fseeko");
4801 goto done;
4804 while (bline->annotated) {
4805 char *smallerthan, *at, *nl, *committer;
4806 size_t len;
4808 if (getline(&line, &linesize, a->f) == -1) {
4809 if (ferror(a->f))
4810 err = got_error_from_errno("getline");
4811 break;
4814 committer = bline->committer;
4815 smallerthan = strchr(committer, '<');
4816 if (smallerthan && smallerthan[1] != '\0')
4817 committer = smallerthan + 1;
4818 at = strchr(committer, '@');
4819 if (at)
4820 *at = '\0';
4821 len = strlen(committer);
4822 if (len >= 9)
4823 committer[8] = '\0';
4825 nl = strchr(line, '\n');
4826 if (nl)
4827 *nl = '\0';
4828 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4829 bline->id_str, bline->datebuf, committer, line);
4831 a->lineno_cur++;
4832 bline = &a->lines[a->lineno_cur - 1];
4834 done:
4835 if (commit)
4836 got_object_commit_close(commit);
4837 free(line);
4838 return err;
4841 static const struct got_error *
4842 cmd_blame(int argc, char *argv[])
4844 const struct got_error *error;
4845 struct got_repository *repo = NULL;
4846 struct got_worktree *worktree = NULL;
4847 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4848 char *link_target = NULL;
4849 struct got_object_id *obj_id = NULL;
4850 struct got_object_id *commit_id = NULL;
4851 struct got_blob_object *blob = NULL;
4852 char *commit_id_str = NULL;
4853 struct blame_cb_args bca;
4854 int ch, obj_type, i;
4855 off_t filesize;
4857 memset(&bca, 0, sizeof(bca));
4859 #ifndef PROFILE
4860 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4861 NULL) == -1)
4862 err(1, "pledge");
4863 #endif
4865 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4866 switch (ch) {
4867 case 'c':
4868 commit_id_str = optarg;
4869 break;
4870 case 'r':
4871 repo_path = realpath(optarg, NULL);
4872 if (repo_path == NULL)
4873 return got_error_from_errno2("realpath",
4874 optarg);
4875 got_path_strip_trailing_slashes(repo_path);
4876 break;
4877 default:
4878 usage_blame();
4879 /* NOTREACHED */
4883 argc -= optind;
4884 argv += optind;
4886 if (argc == 1)
4887 path = argv[0];
4888 else
4889 usage_blame();
4891 cwd = getcwd(NULL, 0);
4892 if (cwd == NULL) {
4893 error = got_error_from_errno("getcwd");
4894 goto done;
4896 if (repo_path == NULL) {
4897 error = got_worktree_open(&worktree, cwd);
4898 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4899 goto done;
4900 else
4901 error = NULL;
4902 if (worktree) {
4903 repo_path =
4904 strdup(got_worktree_get_repo_path(worktree));
4905 if (repo_path == NULL) {
4906 error = got_error_from_errno("strdup");
4907 if (error)
4908 goto done;
4910 } else {
4911 repo_path = strdup(cwd);
4912 if (repo_path == NULL) {
4913 error = got_error_from_errno("strdup");
4914 goto done;
4919 error = got_repo_open(&repo, repo_path, NULL);
4920 if (error != NULL)
4921 goto done;
4923 if (worktree) {
4924 const char *prefix = got_worktree_get_path_prefix(worktree);
4925 char *p;
4927 error = got_worktree_resolve_path(&p, worktree, path);
4928 if (error)
4929 goto done;
4930 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4931 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4932 p) == -1) {
4933 error = got_error_from_errno("asprintf");
4934 free(p);
4935 goto done;
4937 free(p);
4938 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4939 } else {
4940 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4941 if (error)
4942 goto done;
4943 error = got_repo_map_path(&in_repo_path, repo, path);
4945 if (error)
4946 goto done;
4948 if (commit_id_str == NULL) {
4949 struct got_reference *head_ref;
4950 error = got_ref_open(&head_ref, repo, worktree ?
4951 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4952 if (error != NULL)
4953 goto done;
4954 error = got_ref_resolve(&commit_id, repo, head_ref);
4955 got_ref_close(head_ref);
4956 if (error != NULL)
4957 goto done;
4958 } else {
4959 struct got_reflist_head refs;
4960 TAILQ_INIT(&refs);
4961 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4962 NULL);
4963 if (error)
4964 goto done;
4965 error = got_repo_match_object_id(&commit_id, NULL,
4966 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4967 got_ref_list_free(&refs);
4968 if (error)
4969 goto done;
4972 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4973 commit_id, repo);
4974 if (error)
4975 goto done;
4977 error = got_object_id_by_path(&obj_id, repo, commit_id,
4978 link_target ? link_target : in_repo_path);
4979 if (error)
4980 goto done;
4982 error = got_object_get_type(&obj_type, repo, obj_id);
4983 if (error)
4984 goto done;
4986 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4987 error = got_error_path(link_target ? link_target : in_repo_path,
4988 GOT_ERR_OBJ_TYPE);
4989 goto done;
4992 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4993 if (error)
4994 goto done;
4995 bca.f = got_opentemp();
4996 if (bca.f == NULL) {
4997 error = got_error_from_errno("got_opentemp");
4998 goto done;
5000 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5001 &bca.line_offsets, bca.f, blob);
5002 if (error || bca.nlines == 0)
5003 goto done;
5005 /* Don't include \n at EOF in the blame line count. */
5006 if (bca.line_offsets[bca.nlines - 1] == filesize)
5007 bca.nlines--;
5009 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5010 if (bca.lines == NULL) {
5011 error = got_error_from_errno("calloc");
5012 goto done;
5014 bca.lineno_cur = 1;
5015 bca.nlines_prec = 0;
5016 i = bca.nlines;
5017 while (i > 0) {
5018 i /= 10;
5019 bca.nlines_prec++;
5021 bca.repo = repo;
5023 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5024 repo, blame_cb, &bca, check_cancelled, NULL);
5025 done:
5026 free(in_repo_path);
5027 free(link_target);
5028 free(repo_path);
5029 free(cwd);
5030 free(commit_id);
5031 free(obj_id);
5032 if (blob)
5033 got_object_blob_close(blob);
5034 if (worktree)
5035 got_worktree_close(worktree);
5036 if (repo) {
5037 const struct got_error *close_err = got_repo_close(repo);
5038 if (error == NULL)
5039 error = close_err;
5041 if (bca.lines) {
5042 for (i = 0; i < bca.nlines; i++) {
5043 struct blame_line *bline = &bca.lines[i];
5044 free(bline->id_str);
5045 free(bline->committer);
5047 free(bca.lines);
5049 free(bca.line_offsets);
5050 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5051 error = got_error_from_errno("fclose");
5052 return error;
5055 __dead static void
5056 usage_tree(void)
5058 fprintf(stderr,
5059 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5060 getprogname());
5061 exit(1);
5064 static const struct got_error *
5065 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5066 const char *root_path, struct got_repository *repo)
5068 const struct got_error *err = NULL;
5069 int is_root_path = (strcmp(path, root_path) == 0);
5070 const char *modestr = "";
5071 mode_t mode = got_tree_entry_get_mode(te);
5072 char *link_target = NULL;
5074 path += strlen(root_path);
5075 while (path[0] == '/')
5076 path++;
5078 if (got_object_tree_entry_is_submodule(te))
5079 modestr = "$";
5080 else if (S_ISLNK(mode)) {
5081 int i;
5083 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5084 if (err)
5085 return err;
5086 for (i = 0; i < strlen(link_target); i++) {
5087 if (!isprint((unsigned char)link_target[i]))
5088 link_target[i] = '?';
5091 modestr = "@";
5093 else if (S_ISDIR(mode))
5094 modestr = "/";
5095 else if (mode & S_IXUSR)
5096 modestr = "*";
5098 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5099 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5100 link_target ? " -> ": "", link_target ? link_target : "");
5102 free(link_target);
5103 return NULL;
5106 static const struct got_error *
5107 print_tree(const char *path, struct got_object_id *commit_id,
5108 int show_ids, int recurse, const char *root_path,
5109 struct got_repository *repo)
5111 const struct got_error *err = NULL;
5112 struct got_object_id *tree_id = NULL;
5113 struct got_tree_object *tree = NULL;
5114 int nentries, i;
5116 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5117 if (err)
5118 goto done;
5120 err = got_object_open_as_tree(&tree, repo, tree_id);
5121 if (err)
5122 goto done;
5123 nentries = got_object_tree_get_nentries(tree);
5124 for (i = 0; i < nentries; i++) {
5125 struct got_tree_entry *te;
5126 char *id = NULL;
5128 if (sigint_received || sigpipe_received)
5129 break;
5131 te = got_object_tree_get_entry(tree, i);
5132 if (show_ids) {
5133 char *id_str;
5134 err = got_object_id_str(&id_str,
5135 got_tree_entry_get_id(te));
5136 if (err)
5137 goto done;
5138 if (asprintf(&id, "%s ", id_str) == -1) {
5139 err = got_error_from_errno("asprintf");
5140 free(id_str);
5141 goto done;
5143 free(id_str);
5145 err = print_entry(te, id, path, root_path, repo);
5146 free(id);
5147 if (err)
5148 goto done;
5150 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5151 char *child_path;
5152 if (asprintf(&child_path, "%s%s%s", path,
5153 path[0] == '/' && path[1] == '\0' ? "" : "/",
5154 got_tree_entry_get_name(te)) == -1) {
5155 err = got_error_from_errno("asprintf");
5156 goto done;
5158 err = print_tree(child_path, commit_id, show_ids, 1,
5159 root_path, repo);
5160 free(child_path);
5161 if (err)
5162 goto done;
5165 done:
5166 if (tree)
5167 got_object_tree_close(tree);
5168 free(tree_id);
5169 return err;
5172 static const struct got_error *
5173 cmd_tree(int argc, char *argv[])
5175 const struct got_error *error;
5176 struct got_repository *repo = NULL;
5177 struct got_worktree *worktree = NULL;
5178 const char *path, *refname = NULL;
5179 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5180 struct got_object_id *commit_id = NULL;
5181 char *commit_id_str = NULL;
5182 int show_ids = 0, recurse = 0;
5183 int ch;
5185 #ifndef PROFILE
5186 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5187 NULL) == -1)
5188 err(1, "pledge");
5189 #endif
5191 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5192 switch (ch) {
5193 case 'c':
5194 commit_id_str = optarg;
5195 break;
5196 case 'r':
5197 repo_path = realpath(optarg, NULL);
5198 if (repo_path == NULL)
5199 return got_error_from_errno2("realpath",
5200 optarg);
5201 got_path_strip_trailing_slashes(repo_path);
5202 break;
5203 case 'i':
5204 show_ids = 1;
5205 break;
5206 case 'R':
5207 recurse = 1;
5208 break;
5209 default:
5210 usage_tree();
5211 /* NOTREACHED */
5215 argc -= optind;
5216 argv += optind;
5218 if (argc == 1)
5219 path = argv[0];
5220 else if (argc > 1)
5221 usage_tree();
5222 else
5223 path = NULL;
5225 cwd = getcwd(NULL, 0);
5226 if (cwd == NULL) {
5227 error = got_error_from_errno("getcwd");
5228 goto done;
5230 if (repo_path == NULL) {
5231 error = got_worktree_open(&worktree, cwd);
5232 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5233 goto done;
5234 else
5235 error = NULL;
5236 if (worktree) {
5237 repo_path =
5238 strdup(got_worktree_get_repo_path(worktree));
5239 if (repo_path == NULL)
5240 error = got_error_from_errno("strdup");
5241 if (error)
5242 goto done;
5243 } else {
5244 repo_path = strdup(cwd);
5245 if (repo_path == NULL) {
5246 error = got_error_from_errno("strdup");
5247 goto done;
5252 error = got_repo_open(&repo, repo_path, NULL);
5253 if (error != NULL)
5254 goto done;
5256 if (worktree) {
5257 const char *prefix = got_worktree_get_path_prefix(worktree);
5258 char *p;
5260 if (path == NULL)
5261 path = "";
5262 error = got_worktree_resolve_path(&p, worktree, path);
5263 if (error)
5264 goto done;
5265 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5266 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5267 p) == -1) {
5268 error = got_error_from_errno("asprintf");
5269 free(p);
5270 goto done;
5272 free(p);
5273 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5274 if (error)
5275 goto done;
5276 } else {
5277 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5278 if (error)
5279 goto done;
5280 if (path == NULL)
5281 path = "/";
5282 error = got_repo_map_path(&in_repo_path, repo, path);
5283 if (error != NULL)
5284 goto done;
5287 if (commit_id_str == NULL) {
5288 struct got_reference *head_ref;
5289 if (worktree)
5290 refname = got_worktree_get_head_ref_name(worktree);
5291 else
5292 refname = GOT_REF_HEAD;
5293 error = got_ref_open(&head_ref, repo, refname, 0);
5294 if (error != NULL)
5295 goto done;
5296 error = got_ref_resolve(&commit_id, repo, head_ref);
5297 got_ref_close(head_ref);
5298 if (error != NULL)
5299 goto done;
5300 } else {
5301 struct got_reflist_head refs;
5302 TAILQ_INIT(&refs);
5303 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5304 NULL);
5305 if (error)
5306 goto done;
5307 error = got_repo_match_object_id(&commit_id, NULL,
5308 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5309 got_ref_list_free(&refs);
5310 if (error)
5311 goto done;
5314 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5315 in_repo_path, repo);
5316 done:
5317 free(in_repo_path);
5318 free(repo_path);
5319 free(cwd);
5320 free(commit_id);
5321 if (worktree)
5322 got_worktree_close(worktree);
5323 if (repo) {
5324 const struct got_error *close_err = got_repo_close(repo);
5325 if (error == NULL)
5326 error = close_err;
5328 return error;
5331 __dead static void
5332 usage_status(void)
5334 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5335 "[-S status-codes] [path ...]\n", getprogname());
5336 exit(1);
5339 struct got_status_arg {
5340 char *status_codes;
5341 int suppress;
5344 static const struct got_error *
5345 print_status(void *arg, unsigned char status, unsigned char staged_status,
5346 const char *path, struct got_object_id *blob_id,
5347 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5348 int dirfd, const char *de_name)
5350 struct got_status_arg *st = arg;
5352 if (status == staged_status && (status == GOT_STATUS_DELETE))
5353 status = GOT_STATUS_NO_CHANGE;
5354 if (st != NULL && st->status_codes) {
5355 size_t ncodes = strlen(st->status_codes);
5356 int i, j = 0;
5358 for (i = 0; i < ncodes ; i++) {
5359 if (st->suppress) {
5360 if (status == st->status_codes[i] ||
5361 staged_status == st->status_codes[i]) {
5362 j++;
5363 continue;
5365 } else {
5366 if (status == st->status_codes[i] ||
5367 staged_status == st->status_codes[i])
5368 break;
5372 if (st->suppress && j == 0)
5373 goto print;
5375 if (i == ncodes)
5376 return NULL;
5378 print:
5379 printf("%c%c %s\n", status, staged_status, path);
5380 return NULL;
5383 static const struct got_error *
5384 cmd_status(int argc, char *argv[])
5386 const struct got_error *error = NULL;
5387 struct got_repository *repo = NULL;
5388 struct got_worktree *worktree = NULL;
5389 struct got_status_arg st;
5390 char *cwd = NULL;
5391 struct got_pathlist_head paths;
5392 struct got_pathlist_entry *pe;
5393 int ch, i, no_ignores = 0;
5395 TAILQ_INIT(&paths);
5397 memset(&st, 0, sizeof(st));
5398 st.status_codes = NULL;
5399 st.suppress = 0;
5401 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5402 switch (ch) {
5403 case 'I':
5404 no_ignores = 1;
5405 break;
5406 case 'S':
5407 if (st.status_codes != NULL && st.suppress == 0)
5408 option_conflict('S', 's');
5409 st.suppress = 1;
5410 /* fallthrough */
5411 case 's':
5412 for (i = 0; i < strlen(optarg); i++) {
5413 switch (optarg[i]) {
5414 case GOT_STATUS_MODIFY:
5415 case GOT_STATUS_ADD:
5416 case GOT_STATUS_DELETE:
5417 case GOT_STATUS_CONFLICT:
5418 case GOT_STATUS_MISSING:
5419 case GOT_STATUS_OBSTRUCTED:
5420 case GOT_STATUS_UNVERSIONED:
5421 case GOT_STATUS_MODE_CHANGE:
5422 case GOT_STATUS_NONEXISTENT:
5423 break;
5424 default:
5425 errx(1, "invalid status code '%c'",
5426 optarg[i]);
5429 if (ch == 's' && st.suppress)
5430 option_conflict('s', 'S');
5431 st.status_codes = optarg;
5432 break;
5433 default:
5434 usage_status();
5435 /* NOTREACHED */
5439 argc -= optind;
5440 argv += optind;
5442 #ifndef PROFILE
5443 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5444 NULL) == -1)
5445 err(1, "pledge");
5446 #endif
5447 cwd = getcwd(NULL, 0);
5448 if (cwd == NULL) {
5449 error = got_error_from_errno("getcwd");
5450 goto done;
5453 error = got_worktree_open(&worktree, cwd);
5454 if (error) {
5455 if (error->code == GOT_ERR_NOT_WORKTREE)
5456 error = wrap_not_worktree_error(error, "status", cwd);
5457 goto done;
5460 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5461 NULL);
5462 if (error != NULL)
5463 goto done;
5465 error = apply_unveil(got_repo_get_path(repo), 1,
5466 got_worktree_get_root_path(worktree));
5467 if (error)
5468 goto done;
5470 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5471 if (error)
5472 goto done;
5474 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5475 print_status, &st, check_cancelled, NULL);
5476 done:
5477 TAILQ_FOREACH(pe, &paths, entry)
5478 free((char *)pe->path);
5479 got_pathlist_free(&paths);
5480 free(cwd);
5481 return error;
5484 __dead static void
5485 usage_ref(void)
5487 fprintf(stderr,
5488 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5489 "[-d] [name]\n",
5490 getprogname());
5491 exit(1);
5494 static const struct got_error *
5495 list_refs(struct got_repository *repo, const char *refname)
5497 static const struct got_error *err = NULL;
5498 struct got_reflist_head refs;
5499 struct got_reflist_entry *re;
5501 TAILQ_INIT(&refs);
5502 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5503 if (err)
5504 return err;
5506 TAILQ_FOREACH(re, &refs, entry) {
5507 char *refstr;
5508 refstr = got_ref_to_str(re->ref);
5509 if (refstr == NULL)
5510 return got_error_from_errno("got_ref_to_str");
5511 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5512 free(refstr);
5515 got_ref_list_free(&refs);
5516 return NULL;
5519 static const struct got_error *
5520 delete_ref_by_name(struct got_repository *repo, const char *refname)
5522 const struct got_error *err;
5523 struct got_reference *ref;
5525 err = got_ref_open(&ref, repo, refname, 0);
5526 if (err)
5527 return err;
5529 err = delete_ref(repo, ref);
5530 got_ref_close(ref);
5531 return err;
5534 static const struct got_error *
5535 add_ref(struct got_repository *repo, const char *refname, const char *target)
5537 const struct got_error *err = NULL;
5538 struct got_object_id *id;
5539 struct got_reference *ref = NULL;
5542 * Don't let the user create a reference name with a leading '-'.
5543 * While technically a valid reference name, this case is usually
5544 * an unintended typo.
5546 if (refname[0] == '-')
5547 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5549 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5550 repo);
5551 if (err) {
5552 struct got_reference *target_ref;
5554 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5555 return err;
5556 err = got_ref_open(&target_ref, repo, target, 0);
5557 if (err)
5558 return err;
5559 err = got_ref_resolve(&id, repo, target_ref);
5560 got_ref_close(target_ref);
5561 if (err)
5562 return err;
5565 err = got_ref_alloc(&ref, refname, id);
5566 if (err)
5567 goto done;
5569 err = got_ref_write(ref, repo);
5570 done:
5571 if (ref)
5572 got_ref_close(ref);
5573 free(id);
5574 return err;
5577 static const struct got_error *
5578 add_symref(struct got_repository *repo, const char *refname, const char *target)
5580 const struct got_error *err = NULL;
5581 struct got_reference *ref = NULL;
5582 struct got_reference *target_ref = NULL;
5585 * Don't let the user create a reference name with a leading '-'.
5586 * While technically a valid reference name, this case is usually
5587 * an unintended typo.
5589 if (refname[0] == '-')
5590 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5592 err = got_ref_open(&target_ref, repo, target, 0);
5593 if (err)
5594 return err;
5596 err = got_ref_alloc_symref(&ref, refname, target_ref);
5597 if (err)
5598 goto done;
5600 err = got_ref_write(ref, repo);
5601 done:
5602 if (target_ref)
5603 got_ref_close(target_ref);
5604 if (ref)
5605 got_ref_close(ref);
5606 return err;
5609 static const struct got_error *
5610 cmd_ref(int argc, char *argv[])
5612 const struct got_error *error = NULL;
5613 struct got_repository *repo = NULL;
5614 struct got_worktree *worktree = NULL;
5615 char *cwd = NULL, *repo_path = NULL;
5616 int ch, do_list = 0, do_delete = 0;
5617 const char *obj_arg = NULL, *symref_target= NULL;
5618 char *refname = NULL;
5620 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5621 switch (ch) {
5622 case 'c':
5623 obj_arg = optarg;
5624 break;
5625 case 'd':
5626 do_delete = 1;
5627 break;
5628 case 'r':
5629 repo_path = realpath(optarg, NULL);
5630 if (repo_path == NULL)
5631 return got_error_from_errno2("realpath",
5632 optarg);
5633 got_path_strip_trailing_slashes(repo_path);
5634 break;
5635 case 'l':
5636 do_list = 1;
5637 break;
5638 case 's':
5639 symref_target = optarg;
5640 break;
5641 default:
5642 usage_ref();
5643 /* NOTREACHED */
5647 if (obj_arg && do_list)
5648 option_conflict('c', 'l');
5649 if (obj_arg && do_delete)
5650 option_conflict('c', 'd');
5651 if (obj_arg && symref_target)
5652 option_conflict('c', 's');
5653 if (symref_target && do_delete)
5654 option_conflict('s', 'd');
5655 if (symref_target && do_list)
5656 option_conflict('s', 'l');
5657 if (do_delete && do_list)
5658 option_conflict('d', 'l');
5660 argc -= optind;
5661 argv += optind;
5663 if (do_list) {
5664 if (argc != 0 && argc != 1)
5665 usage_ref();
5666 if (argc == 1) {
5667 refname = strdup(argv[0]);
5668 if (refname == NULL) {
5669 error = got_error_from_errno("strdup");
5670 goto done;
5673 } else {
5674 if (argc != 1)
5675 usage_ref();
5676 refname = strdup(argv[0]);
5677 if (refname == NULL) {
5678 error = got_error_from_errno("strdup");
5679 goto done;
5683 if (refname)
5684 got_path_strip_trailing_slashes(refname);
5686 #ifndef PROFILE
5687 if (do_list) {
5688 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5689 NULL) == -1)
5690 err(1, "pledge");
5691 } else {
5692 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5693 "sendfd unveil", NULL) == -1)
5694 err(1, "pledge");
5696 #endif
5697 cwd = getcwd(NULL, 0);
5698 if (cwd == NULL) {
5699 error = got_error_from_errno("getcwd");
5700 goto done;
5703 if (repo_path == NULL) {
5704 error = got_worktree_open(&worktree, cwd);
5705 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5706 goto done;
5707 else
5708 error = NULL;
5709 if (worktree) {
5710 repo_path =
5711 strdup(got_worktree_get_repo_path(worktree));
5712 if (repo_path == NULL)
5713 error = got_error_from_errno("strdup");
5714 if (error)
5715 goto done;
5716 } else {
5717 repo_path = strdup(cwd);
5718 if (repo_path == NULL) {
5719 error = got_error_from_errno("strdup");
5720 goto done;
5725 error = got_repo_open(&repo, repo_path, NULL);
5726 if (error != NULL)
5727 goto done;
5729 error = apply_unveil(got_repo_get_path(repo), do_list,
5730 worktree ? got_worktree_get_root_path(worktree) : NULL);
5731 if (error)
5732 goto done;
5734 if (do_list)
5735 error = list_refs(repo, refname);
5736 else if (do_delete)
5737 error = delete_ref_by_name(repo, refname);
5738 else if (symref_target)
5739 error = add_symref(repo, refname, symref_target);
5740 else {
5741 if (obj_arg == NULL)
5742 usage_ref();
5743 error = add_ref(repo, refname, obj_arg);
5745 done:
5746 free(refname);
5747 if (repo) {
5748 const struct got_error *close_err = got_repo_close(repo);
5749 if (error == NULL)
5750 error = close_err;
5752 if (worktree)
5753 got_worktree_close(worktree);
5754 free(cwd);
5755 free(repo_path);
5756 return error;
5759 __dead static void
5760 usage_branch(void)
5762 fprintf(stderr,
5763 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5764 "[name]\n", getprogname());
5765 exit(1);
5768 static const struct got_error *
5769 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5770 struct got_reference *ref)
5772 const struct got_error *err = NULL;
5773 const char *refname, *marker = " ";
5774 char *refstr;
5776 refname = got_ref_get_name(ref);
5777 if (worktree && strcmp(refname,
5778 got_worktree_get_head_ref_name(worktree)) == 0) {
5779 struct got_object_id *id = NULL;
5781 err = got_ref_resolve(&id, repo, ref);
5782 if (err)
5783 return err;
5784 if (got_object_id_cmp(id,
5785 got_worktree_get_base_commit_id(worktree)) == 0)
5786 marker = "* ";
5787 else
5788 marker = "~ ";
5789 free(id);
5792 if (strncmp(refname, "refs/heads/", 11) == 0)
5793 refname += 11;
5794 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5795 refname += 18;
5796 if (strncmp(refname, "refs/remotes/", 13) == 0)
5797 refname += 13;
5799 refstr = got_ref_to_str(ref);
5800 if (refstr == NULL)
5801 return got_error_from_errno("got_ref_to_str");
5803 printf("%s%s: %s\n", marker, refname, refstr);
5804 free(refstr);
5805 return NULL;
5808 static const struct got_error *
5809 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5811 const char *refname;
5813 if (worktree == NULL)
5814 return got_error(GOT_ERR_NOT_WORKTREE);
5816 refname = got_worktree_get_head_ref_name(worktree);
5818 if (strncmp(refname, "refs/heads/", 11) == 0)
5819 refname += 11;
5820 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5821 refname += 18;
5823 printf("%s\n", refname);
5825 return NULL;
5828 static const struct got_error *
5829 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5831 static const struct got_error *err = NULL;
5832 struct got_reflist_head refs;
5833 struct got_reflist_entry *re;
5834 struct got_reference *temp_ref = NULL;
5835 int rebase_in_progress, histedit_in_progress;
5837 TAILQ_INIT(&refs);
5839 if (worktree) {
5840 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5841 worktree);
5842 if (err)
5843 return err;
5845 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5846 worktree);
5847 if (err)
5848 return err;
5850 if (rebase_in_progress || histedit_in_progress) {
5851 err = got_ref_open(&temp_ref, repo,
5852 got_worktree_get_head_ref_name(worktree), 0);
5853 if (err)
5854 return err;
5855 list_branch(repo, worktree, temp_ref);
5856 got_ref_close(temp_ref);
5860 err = got_ref_list(&refs, repo, "refs/heads",
5861 got_ref_cmp_by_name, NULL);
5862 if (err)
5863 return err;
5865 TAILQ_FOREACH(re, &refs, entry)
5866 list_branch(repo, worktree, re->ref);
5868 got_ref_list_free(&refs);
5870 err = got_ref_list(&refs, repo, "refs/remotes",
5871 got_ref_cmp_by_name, NULL);
5872 if (err)
5873 return err;
5875 TAILQ_FOREACH(re, &refs, entry)
5876 list_branch(repo, worktree, re->ref);
5878 got_ref_list_free(&refs);
5880 return NULL;
5883 static const struct got_error *
5884 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5885 const char *branch_name)
5887 const struct got_error *err = NULL;
5888 struct got_reference *ref = NULL;
5889 char *refname, *remote_refname = NULL;
5891 if (strncmp(branch_name, "refs/", 5) == 0)
5892 branch_name += 5;
5893 if (strncmp(branch_name, "heads/", 6) == 0)
5894 branch_name += 6;
5895 else if (strncmp(branch_name, "remotes/", 8) == 0)
5896 branch_name += 8;
5898 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5899 return got_error_from_errno("asprintf");
5901 if (asprintf(&remote_refname, "refs/remotes/%s",
5902 branch_name) == -1) {
5903 err = got_error_from_errno("asprintf");
5904 goto done;
5907 err = got_ref_open(&ref, repo, refname, 0);
5908 if (err) {
5909 const struct got_error *err2;
5910 if (err->code != GOT_ERR_NOT_REF)
5911 goto done;
5913 * Keep 'err' intact such that if neither branch exists
5914 * we report "refs/heads" rather than "refs/remotes" in
5915 * our error message.
5917 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5918 if (err2)
5919 goto done;
5920 err = NULL;
5923 if (worktree &&
5924 strcmp(got_worktree_get_head_ref_name(worktree),
5925 got_ref_get_name(ref)) == 0) {
5926 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5927 "will not delete this work tree's current branch");
5928 goto done;
5931 err = delete_ref(repo, ref);
5932 done:
5933 if (ref)
5934 got_ref_close(ref);
5935 free(refname);
5936 free(remote_refname);
5937 return err;
5940 static const struct got_error *
5941 add_branch(struct got_repository *repo, const char *branch_name,
5942 struct got_object_id *base_commit_id)
5944 const struct got_error *err = NULL;
5945 struct got_reference *ref = NULL;
5946 char *base_refname = NULL, *refname = NULL;
5949 * Don't let the user create a branch name with a leading '-'.
5950 * While technically a valid reference name, this case is usually
5951 * an unintended typo.
5953 if (branch_name[0] == '-')
5954 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5956 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5957 branch_name += 11;
5959 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5960 err = got_error_from_errno("asprintf");
5961 goto done;
5964 err = got_ref_open(&ref, repo, refname, 0);
5965 if (err == NULL) {
5966 err = got_error(GOT_ERR_BRANCH_EXISTS);
5967 goto done;
5968 } else if (err->code != GOT_ERR_NOT_REF)
5969 goto done;
5971 err = got_ref_alloc(&ref, refname, base_commit_id);
5972 if (err)
5973 goto done;
5975 err = got_ref_write(ref, repo);
5976 done:
5977 if (ref)
5978 got_ref_close(ref);
5979 free(base_refname);
5980 free(refname);
5981 return err;
5984 static const struct got_error *
5985 cmd_branch(int argc, char *argv[])
5987 const struct got_error *error = NULL;
5988 struct got_repository *repo = NULL;
5989 struct got_worktree *worktree = NULL;
5990 char *cwd = NULL, *repo_path = NULL;
5991 int ch, do_list = 0, do_show = 0, do_update = 1;
5992 const char *delref = NULL, *commit_id_arg = NULL;
5993 struct got_reference *ref = NULL;
5994 struct got_pathlist_head paths;
5995 struct got_pathlist_entry *pe;
5996 struct got_object_id *commit_id = NULL;
5997 char *commit_id_str = NULL;
5999 TAILQ_INIT(&paths);
6001 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
6002 switch (ch) {
6003 case 'c':
6004 commit_id_arg = optarg;
6005 break;
6006 case 'd':
6007 delref = optarg;
6008 break;
6009 case 'r':
6010 repo_path = realpath(optarg, NULL);
6011 if (repo_path == NULL)
6012 return got_error_from_errno2("realpath",
6013 optarg);
6014 got_path_strip_trailing_slashes(repo_path);
6015 break;
6016 case 'l':
6017 do_list = 1;
6018 break;
6019 case 'n':
6020 do_update = 0;
6021 break;
6022 default:
6023 usage_branch();
6024 /* NOTREACHED */
6028 if (do_list && delref)
6029 option_conflict('l', 'd');
6031 argc -= optind;
6032 argv += optind;
6034 if (!do_list && !delref && argc == 0)
6035 do_show = 1;
6037 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6038 errx(1, "-c option can only be used when creating a branch");
6040 if (do_list || delref) {
6041 if (argc > 0)
6042 usage_branch();
6043 } else if (!do_show && argc != 1)
6044 usage_branch();
6046 #ifndef PROFILE
6047 if (do_list || do_show) {
6048 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6049 NULL) == -1)
6050 err(1, "pledge");
6051 } else {
6052 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6053 "sendfd unveil", NULL) == -1)
6054 err(1, "pledge");
6056 #endif
6057 cwd = getcwd(NULL, 0);
6058 if (cwd == NULL) {
6059 error = got_error_from_errno("getcwd");
6060 goto done;
6063 if (repo_path == NULL) {
6064 error = got_worktree_open(&worktree, cwd);
6065 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6066 goto done;
6067 else
6068 error = NULL;
6069 if (worktree) {
6070 repo_path =
6071 strdup(got_worktree_get_repo_path(worktree));
6072 if (repo_path == NULL)
6073 error = got_error_from_errno("strdup");
6074 if (error)
6075 goto done;
6076 } else {
6077 repo_path = strdup(cwd);
6078 if (repo_path == NULL) {
6079 error = got_error_from_errno("strdup");
6080 goto done;
6085 error = got_repo_open(&repo, repo_path, NULL);
6086 if (error != NULL)
6087 goto done;
6089 error = apply_unveil(got_repo_get_path(repo), do_list,
6090 worktree ? got_worktree_get_root_path(worktree) : NULL);
6091 if (error)
6092 goto done;
6094 if (do_show)
6095 error = show_current_branch(repo, worktree);
6096 else if (do_list)
6097 error = list_branches(repo, worktree);
6098 else if (delref)
6099 error = delete_branch(repo, worktree, delref);
6100 else {
6101 struct got_reflist_head refs;
6102 TAILQ_INIT(&refs);
6103 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6104 NULL);
6105 if (error)
6106 goto done;
6107 if (commit_id_arg == NULL)
6108 commit_id_arg = worktree ?
6109 got_worktree_get_head_ref_name(worktree) :
6110 GOT_REF_HEAD;
6111 error = got_repo_match_object_id(&commit_id, NULL,
6112 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6113 got_ref_list_free(&refs);
6114 if (error)
6115 goto done;
6116 error = add_branch(repo, argv[0], commit_id);
6117 if (error)
6118 goto done;
6119 if (worktree && do_update) {
6120 struct got_update_progress_arg upa;
6121 char *branch_refname = NULL;
6123 error = got_object_id_str(&commit_id_str, commit_id);
6124 if (error)
6125 goto done;
6126 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6127 worktree);
6128 if (error)
6129 goto done;
6130 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6131 == -1) {
6132 error = got_error_from_errno("asprintf");
6133 goto done;
6135 error = got_ref_open(&ref, repo, branch_refname, 0);
6136 free(branch_refname);
6137 if (error)
6138 goto done;
6139 error = switch_head_ref(ref, commit_id, worktree,
6140 repo);
6141 if (error)
6142 goto done;
6143 error = got_worktree_set_base_commit_id(worktree, repo,
6144 commit_id);
6145 if (error)
6146 goto done;
6147 memset(&upa, 0, sizeof(upa));
6148 error = got_worktree_checkout_files(worktree, &paths,
6149 repo, update_progress, &upa, check_cancelled,
6150 NULL);
6151 if (error)
6152 goto done;
6153 if (upa.did_something) {
6154 printf("Updated to %s: %s\n",
6155 got_worktree_get_head_ref_name(worktree),
6156 commit_id_str);
6158 print_update_progress_stats(&upa);
6161 done:
6162 if (ref)
6163 got_ref_close(ref);
6164 if (repo) {
6165 const struct got_error *close_err = got_repo_close(repo);
6166 if (error == NULL)
6167 error = close_err;
6169 if (worktree)
6170 got_worktree_close(worktree);
6171 free(cwd);
6172 free(repo_path);
6173 free(commit_id);
6174 free(commit_id_str);
6175 TAILQ_FOREACH(pe, &paths, entry)
6176 free((char *)pe->path);
6177 got_pathlist_free(&paths);
6178 return error;
6182 __dead static void
6183 usage_tag(void)
6185 fprintf(stderr,
6186 "usage: %s tag [-c commit] [-r repository] [-l] "
6187 "[-m message] name\n", getprogname());
6188 exit(1);
6191 #if 0
6192 static const struct got_error *
6193 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6195 const struct got_error *err = NULL;
6196 struct got_reflist_entry *re, *se, *new;
6197 struct got_object_id *re_id, *se_id;
6198 struct got_tag_object *re_tag, *se_tag;
6199 time_t re_time, se_time;
6201 STAILQ_FOREACH(re, tags, entry) {
6202 se = STAILQ_FIRST(sorted);
6203 if (se == NULL) {
6204 err = got_reflist_entry_dup(&new, re);
6205 if (err)
6206 return err;
6207 STAILQ_INSERT_HEAD(sorted, new, entry);
6208 continue;
6209 } else {
6210 err = got_ref_resolve(&re_id, repo, re->ref);
6211 if (err)
6212 break;
6213 err = got_object_open_as_tag(&re_tag, repo, re_id);
6214 free(re_id);
6215 if (err)
6216 break;
6217 re_time = got_object_tag_get_tagger_time(re_tag);
6218 got_object_tag_close(re_tag);
6221 while (se) {
6222 err = got_ref_resolve(&se_id, repo, re->ref);
6223 if (err)
6224 break;
6225 err = got_object_open_as_tag(&se_tag, repo, se_id);
6226 free(se_id);
6227 if (err)
6228 break;
6229 se_time = got_object_tag_get_tagger_time(se_tag);
6230 got_object_tag_close(se_tag);
6232 if (se_time > re_time) {
6233 err = got_reflist_entry_dup(&new, re);
6234 if (err)
6235 return err;
6236 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6237 break;
6239 se = STAILQ_NEXT(se, entry);
6240 continue;
6243 done:
6244 return err;
6246 #endif
6248 static const struct got_error *
6249 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6251 static const struct got_error *err = NULL;
6252 struct got_reflist_head refs;
6253 struct got_reflist_entry *re;
6255 TAILQ_INIT(&refs);
6257 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6258 if (err)
6259 return err;
6261 TAILQ_FOREACH(re, &refs, entry) {
6262 const char *refname;
6263 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6264 char datebuf[26];
6265 const char *tagger;
6266 time_t tagger_time;
6267 struct got_object_id *id;
6268 struct got_tag_object *tag;
6269 struct got_commit_object *commit = NULL;
6271 refname = got_ref_get_name(re->ref);
6272 if (strncmp(refname, "refs/tags/", 10) != 0)
6273 continue;
6274 refname += 10;
6275 refstr = got_ref_to_str(re->ref);
6276 if (refstr == NULL) {
6277 err = got_error_from_errno("got_ref_to_str");
6278 break;
6280 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6281 free(refstr);
6283 err = got_ref_resolve(&id, repo, re->ref);
6284 if (err)
6285 break;
6286 err = got_object_open_as_tag(&tag, repo, id);
6287 if (err) {
6288 if (err->code != GOT_ERR_OBJ_TYPE) {
6289 free(id);
6290 break;
6292 /* "lightweight" tag */
6293 err = got_object_open_as_commit(&commit, repo, id);
6294 if (err) {
6295 free(id);
6296 break;
6298 tagger = got_object_commit_get_committer(commit);
6299 tagger_time =
6300 got_object_commit_get_committer_time(commit);
6301 err = got_object_id_str(&id_str, id);
6302 free(id);
6303 if (err)
6304 break;
6305 } else {
6306 free(id);
6307 tagger = got_object_tag_get_tagger(tag);
6308 tagger_time = got_object_tag_get_tagger_time(tag);
6309 err = got_object_id_str(&id_str,
6310 got_object_tag_get_object_id(tag));
6311 if (err)
6312 break;
6314 printf("from: %s\n", tagger);
6315 datestr = get_datestr(&tagger_time, datebuf);
6316 if (datestr)
6317 printf("date: %s UTC\n", datestr);
6318 if (commit)
6319 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6320 else {
6321 switch (got_object_tag_get_object_type(tag)) {
6322 case GOT_OBJ_TYPE_BLOB:
6323 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6324 id_str);
6325 break;
6326 case GOT_OBJ_TYPE_TREE:
6327 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6328 id_str);
6329 break;
6330 case GOT_OBJ_TYPE_COMMIT:
6331 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6332 id_str);
6333 break;
6334 case GOT_OBJ_TYPE_TAG:
6335 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6336 id_str);
6337 break;
6338 default:
6339 break;
6342 free(id_str);
6343 if (commit) {
6344 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6345 if (err)
6346 break;
6347 got_object_commit_close(commit);
6348 } else {
6349 tagmsg0 = strdup(got_object_tag_get_message(tag));
6350 got_object_tag_close(tag);
6351 if (tagmsg0 == NULL) {
6352 err = got_error_from_errno("strdup");
6353 break;
6357 tagmsg = tagmsg0;
6358 do {
6359 line = strsep(&tagmsg, "\n");
6360 if (line)
6361 printf(" %s\n", line);
6362 } while (line);
6363 free(tagmsg0);
6366 got_ref_list_free(&refs);
6367 return NULL;
6370 static const struct got_error *
6371 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6372 const char *tag_name, const char *repo_path)
6374 const struct got_error *err = NULL;
6375 char *template = NULL, *initial_content = NULL;
6376 char *editor = NULL;
6377 int initial_content_len;
6378 int fd = -1;
6380 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6381 err = got_error_from_errno("asprintf");
6382 goto done;
6385 initial_content_len = asprintf(&initial_content,
6386 "\n# tagging commit %s as %s\n",
6387 commit_id_str, tag_name);
6388 if (initial_content_len == -1) {
6389 err = got_error_from_errno("asprintf");
6390 goto done;
6393 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6394 if (err)
6395 goto done;
6397 if (write(fd, initial_content, initial_content_len) == -1) {
6398 err = got_error_from_errno2("write", *tagmsg_path);
6399 goto done;
6402 err = get_editor(&editor);
6403 if (err)
6404 goto done;
6405 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6406 initial_content_len, 1);
6407 done:
6408 free(initial_content);
6409 free(template);
6410 free(editor);
6412 if (fd != -1 && close(fd) == -1 && err == NULL)
6413 err = got_error_from_errno2("close", *tagmsg_path);
6415 /* Editor is done; we can now apply unveil(2) */
6416 if (err == NULL)
6417 err = apply_unveil(repo_path, 0, NULL);
6418 if (err) {
6419 free(*tagmsg);
6420 *tagmsg = NULL;
6422 return err;
6425 static const struct got_error *
6426 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6427 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6429 const struct got_error *err = NULL;
6430 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6431 char *label = NULL, *commit_id_str = NULL;
6432 struct got_reference *ref = NULL;
6433 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6434 char *tagmsg_path = NULL, *tag_id_str = NULL;
6435 int preserve_tagmsg = 0;
6436 struct got_reflist_head refs;
6438 TAILQ_INIT(&refs);
6441 * Don't let the user create a tag name with a leading '-'.
6442 * While technically a valid reference name, this case is usually
6443 * an unintended typo.
6445 if (tag_name[0] == '-')
6446 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6448 err = get_author(&tagger, repo, worktree);
6449 if (err)
6450 return err;
6452 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6453 if (err)
6454 goto done;
6456 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6457 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6458 if (err)
6459 goto done;
6461 err = got_object_id_str(&commit_id_str, commit_id);
6462 if (err)
6463 goto done;
6465 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6466 refname = strdup(tag_name);
6467 if (refname == NULL) {
6468 err = got_error_from_errno("strdup");
6469 goto done;
6471 tag_name += 10;
6472 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6473 err = got_error_from_errno("asprintf");
6474 goto done;
6477 err = got_ref_open(&ref, repo, refname, 0);
6478 if (err == NULL) {
6479 err = got_error(GOT_ERR_TAG_EXISTS);
6480 goto done;
6481 } else if (err->code != GOT_ERR_NOT_REF)
6482 goto done;
6484 if (tagmsg_arg == NULL) {
6485 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6486 tag_name, got_repo_get_path(repo));
6487 if (err) {
6488 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6489 tagmsg_path != NULL)
6490 preserve_tagmsg = 1;
6491 goto done;
6495 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6496 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6497 if (err) {
6498 if (tagmsg_path)
6499 preserve_tagmsg = 1;
6500 goto done;
6503 err = got_ref_alloc(&ref, refname, tag_id);
6504 if (err) {
6505 if (tagmsg_path)
6506 preserve_tagmsg = 1;
6507 goto done;
6510 err = got_ref_write(ref, repo);
6511 if (err) {
6512 if (tagmsg_path)
6513 preserve_tagmsg = 1;
6514 goto done;
6517 err = got_object_id_str(&tag_id_str, tag_id);
6518 if (err) {
6519 if (tagmsg_path)
6520 preserve_tagmsg = 1;
6521 goto done;
6523 printf("Created tag %s\n", tag_id_str);
6524 done:
6525 if (preserve_tagmsg) {
6526 fprintf(stderr, "%s: tag message preserved in %s\n",
6527 getprogname(), tagmsg_path);
6528 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6529 err = got_error_from_errno2("unlink", tagmsg_path);
6530 free(tag_id_str);
6531 if (ref)
6532 got_ref_close(ref);
6533 free(commit_id);
6534 free(commit_id_str);
6535 free(refname);
6536 free(tagmsg);
6537 free(tagmsg_path);
6538 free(tagger);
6539 got_ref_list_free(&refs);
6540 return err;
6543 static const struct got_error *
6544 cmd_tag(int argc, char *argv[])
6546 const struct got_error *error = NULL;
6547 struct got_repository *repo = NULL;
6548 struct got_worktree *worktree = NULL;
6549 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6550 char *gitconfig_path = NULL;
6551 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6552 int ch, do_list = 0;
6554 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6555 switch (ch) {
6556 case 'c':
6557 commit_id_arg = optarg;
6558 break;
6559 case 'm':
6560 tagmsg = optarg;
6561 break;
6562 case 'r':
6563 repo_path = realpath(optarg, NULL);
6564 if (repo_path == NULL)
6565 return got_error_from_errno2("realpath",
6566 optarg);
6567 got_path_strip_trailing_slashes(repo_path);
6568 break;
6569 case 'l':
6570 do_list = 1;
6571 break;
6572 default:
6573 usage_tag();
6574 /* NOTREACHED */
6578 argc -= optind;
6579 argv += optind;
6581 if (do_list) {
6582 if (commit_id_arg != NULL)
6583 errx(1,
6584 "-c option can only be used when creating a tag");
6585 if (tagmsg)
6586 option_conflict('l', 'm');
6587 if (argc > 0)
6588 usage_tag();
6589 } else if (argc != 1)
6590 usage_tag();
6592 tag_name = argv[0];
6594 #ifndef PROFILE
6595 if (do_list) {
6596 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6597 NULL) == -1)
6598 err(1, "pledge");
6599 } else {
6600 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6601 "sendfd unveil", NULL) == -1)
6602 err(1, "pledge");
6604 #endif
6605 cwd = getcwd(NULL, 0);
6606 if (cwd == NULL) {
6607 error = got_error_from_errno("getcwd");
6608 goto done;
6611 if (repo_path == NULL) {
6612 error = got_worktree_open(&worktree, cwd);
6613 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6614 goto done;
6615 else
6616 error = NULL;
6617 if (worktree) {
6618 repo_path =
6619 strdup(got_worktree_get_repo_path(worktree));
6620 if (repo_path == NULL)
6621 error = got_error_from_errno("strdup");
6622 if (error)
6623 goto done;
6624 } else {
6625 repo_path = strdup(cwd);
6626 if (repo_path == NULL) {
6627 error = got_error_from_errno("strdup");
6628 goto done;
6633 if (do_list) {
6634 error = got_repo_open(&repo, repo_path, NULL);
6635 if (error != NULL)
6636 goto done;
6637 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6638 if (error)
6639 goto done;
6640 error = list_tags(repo, worktree);
6641 } else {
6642 error = get_gitconfig_path(&gitconfig_path);
6643 if (error)
6644 goto done;
6645 error = got_repo_open(&repo, repo_path, gitconfig_path);
6646 if (error != NULL)
6647 goto done;
6649 if (tagmsg) {
6650 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6651 if (error)
6652 goto done;
6655 if (commit_id_arg == NULL) {
6656 struct got_reference *head_ref;
6657 struct got_object_id *commit_id;
6658 error = got_ref_open(&head_ref, repo,
6659 worktree ? got_worktree_get_head_ref_name(worktree)
6660 : GOT_REF_HEAD, 0);
6661 if (error)
6662 goto done;
6663 error = got_ref_resolve(&commit_id, repo, head_ref);
6664 got_ref_close(head_ref);
6665 if (error)
6666 goto done;
6667 error = got_object_id_str(&commit_id_str, commit_id);
6668 free(commit_id);
6669 if (error)
6670 goto done;
6673 error = add_tag(repo, worktree, tag_name,
6674 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6676 done:
6677 if (repo) {
6678 const struct got_error *close_err = got_repo_close(repo);
6679 if (error == NULL)
6680 error = close_err;
6682 if (worktree)
6683 got_worktree_close(worktree);
6684 free(cwd);
6685 free(repo_path);
6686 free(gitconfig_path);
6687 free(commit_id_str);
6688 return error;
6691 __dead static void
6692 usage_add(void)
6694 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6695 getprogname());
6696 exit(1);
6699 static const struct got_error *
6700 add_progress(void *arg, unsigned char status, const char *path)
6702 while (path[0] == '/')
6703 path++;
6704 printf("%c %s\n", status, path);
6705 return NULL;
6708 static const struct got_error *
6709 cmd_add(int argc, char *argv[])
6711 const struct got_error *error = NULL;
6712 struct got_repository *repo = NULL;
6713 struct got_worktree *worktree = NULL;
6714 char *cwd = NULL;
6715 struct got_pathlist_head paths;
6716 struct got_pathlist_entry *pe;
6717 int ch, can_recurse = 0, no_ignores = 0;
6719 TAILQ_INIT(&paths);
6721 while ((ch = getopt(argc, argv, "IR")) != -1) {
6722 switch (ch) {
6723 case 'I':
6724 no_ignores = 1;
6725 break;
6726 case 'R':
6727 can_recurse = 1;
6728 break;
6729 default:
6730 usage_add();
6731 /* NOTREACHED */
6735 argc -= optind;
6736 argv += optind;
6738 #ifndef PROFILE
6739 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6740 NULL) == -1)
6741 err(1, "pledge");
6742 #endif
6743 if (argc < 1)
6744 usage_add();
6746 cwd = getcwd(NULL, 0);
6747 if (cwd == NULL) {
6748 error = got_error_from_errno("getcwd");
6749 goto done;
6752 error = got_worktree_open(&worktree, cwd);
6753 if (error) {
6754 if (error->code == GOT_ERR_NOT_WORKTREE)
6755 error = wrap_not_worktree_error(error, "add", cwd);
6756 goto done;
6759 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6760 NULL);
6761 if (error != NULL)
6762 goto done;
6764 error = apply_unveil(got_repo_get_path(repo), 1,
6765 got_worktree_get_root_path(worktree));
6766 if (error)
6767 goto done;
6769 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6770 if (error)
6771 goto done;
6773 if (!can_recurse) {
6774 char *ondisk_path;
6775 struct stat sb;
6776 TAILQ_FOREACH(pe, &paths, entry) {
6777 if (asprintf(&ondisk_path, "%s/%s",
6778 got_worktree_get_root_path(worktree),
6779 pe->path) == -1) {
6780 error = got_error_from_errno("asprintf");
6781 goto done;
6783 if (lstat(ondisk_path, &sb) == -1) {
6784 if (errno == ENOENT) {
6785 free(ondisk_path);
6786 continue;
6788 error = got_error_from_errno2("lstat",
6789 ondisk_path);
6790 free(ondisk_path);
6791 goto done;
6793 free(ondisk_path);
6794 if (S_ISDIR(sb.st_mode)) {
6795 error = got_error_msg(GOT_ERR_BAD_PATH,
6796 "adding directories requires -R option");
6797 goto done;
6802 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6803 NULL, repo, no_ignores);
6804 done:
6805 if (repo) {
6806 const struct got_error *close_err = got_repo_close(repo);
6807 if (error == NULL)
6808 error = close_err;
6810 if (worktree)
6811 got_worktree_close(worktree);
6812 TAILQ_FOREACH(pe, &paths, entry)
6813 free((char *)pe->path);
6814 got_pathlist_free(&paths);
6815 free(cwd);
6816 return error;
6819 __dead static void
6820 usage_remove(void)
6822 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6823 "path ...\n", getprogname());
6824 exit(1);
6827 static const struct got_error *
6828 print_remove_status(void *arg, unsigned char status,
6829 unsigned char staged_status, const char *path)
6831 while (path[0] == '/')
6832 path++;
6833 if (status == GOT_STATUS_NONEXISTENT)
6834 return NULL;
6835 if (status == staged_status && (status == GOT_STATUS_DELETE))
6836 status = GOT_STATUS_NO_CHANGE;
6837 printf("%c%c %s\n", status, staged_status, path);
6838 return NULL;
6841 static const struct got_error *
6842 cmd_remove(int argc, char *argv[])
6844 const struct got_error *error = NULL;
6845 struct got_worktree *worktree = NULL;
6846 struct got_repository *repo = NULL;
6847 const char *status_codes = NULL;
6848 char *cwd = NULL;
6849 struct got_pathlist_head paths;
6850 struct got_pathlist_entry *pe;
6851 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6853 TAILQ_INIT(&paths);
6855 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6856 switch (ch) {
6857 case 'f':
6858 delete_local_mods = 1;
6859 break;
6860 case 'k':
6861 keep_on_disk = 1;
6862 break;
6863 case 'R':
6864 can_recurse = 1;
6865 break;
6866 case 's':
6867 for (i = 0; i < strlen(optarg); i++) {
6868 switch (optarg[i]) {
6869 case GOT_STATUS_MODIFY:
6870 delete_local_mods = 1;
6871 break;
6872 case GOT_STATUS_MISSING:
6873 break;
6874 default:
6875 errx(1, "invalid status code '%c'",
6876 optarg[i]);
6879 status_codes = optarg;
6880 break;
6881 default:
6882 usage_remove();
6883 /* NOTREACHED */
6887 argc -= optind;
6888 argv += optind;
6890 #ifndef PROFILE
6891 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6892 NULL) == -1)
6893 err(1, "pledge");
6894 #endif
6895 if (argc < 1)
6896 usage_remove();
6898 cwd = getcwd(NULL, 0);
6899 if (cwd == NULL) {
6900 error = got_error_from_errno("getcwd");
6901 goto done;
6903 error = got_worktree_open(&worktree, cwd);
6904 if (error) {
6905 if (error->code == GOT_ERR_NOT_WORKTREE)
6906 error = wrap_not_worktree_error(error, "remove", cwd);
6907 goto done;
6910 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6911 NULL);
6912 if (error)
6913 goto done;
6915 error = apply_unveil(got_repo_get_path(repo), 1,
6916 got_worktree_get_root_path(worktree));
6917 if (error)
6918 goto done;
6920 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6921 if (error)
6922 goto done;
6924 if (!can_recurse) {
6925 char *ondisk_path;
6926 struct stat sb;
6927 TAILQ_FOREACH(pe, &paths, entry) {
6928 if (asprintf(&ondisk_path, "%s/%s",
6929 got_worktree_get_root_path(worktree),
6930 pe->path) == -1) {
6931 error = got_error_from_errno("asprintf");
6932 goto done;
6934 if (lstat(ondisk_path, &sb) == -1) {
6935 if (errno == ENOENT) {
6936 free(ondisk_path);
6937 continue;
6939 error = got_error_from_errno2("lstat",
6940 ondisk_path);
6941 free(ondisk_path);
6942 goto done;
6944 free(ondisk_path);
6945 if (S_ISDIR(sb.st_mode)) {
6946 error = got_error_msg(GOT_ERR_BAD_PATH,
6947 "removing directories requires -R option");
6948 goto done;
6953 error = got_worktree_schedule_delete(worktree, &paths,
6954 delete_local_mods, status_codes, print_remove_status, NULL,
6955 repo, keep_on_disk);
6956 done:
6957 if (repo) {
6958 const struct got_error *close_err = got_repo_close(repo);
6959 if (error == NULL)
6960 error = close_err;
6962 if (worktree)
6963 got_worktree_close(worktree);
6964 TAILQ_FOREACH(pe, &paths, entry)
6965 free((char *)pe->path);
6966 got_pathlist_free(&paths);
6967 free(cwd);
6968 return error;
6971 __dead static void
6972 usage_revert(void)
6974 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6975 "path ...\n", getprogname());
6976 exit(1);
6979 static const struct got_error *
6980 revert_progress(void *arg, unsigned char status, const char *path)
6982 if (status == GOT_STATUS_UNVERSIONED)
6983 return NULL;
6985 while (path[0] == '/')
6986 path++;
6987 printf("%c %s\n", status, path);
6988 return NULL;
6991 struct choose_patch_arg {
6992 FILE *patch_script_file;
6993 const char *action;
6996 static const struct got_error *
6997 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6998 int nchanges, const char *action)
7000 char *line = NULL;
7001 size_t linesize = 0;
7002 ssize_t linelen;
7004 switch (status) {
7005 case GOT_STATUS_ADD:
7006 printf("A %s\n%s this addition? [y/n] ", path, action);
7007 break;
7008 case GOT_STATUS_DELETE:
7009 printf("D %s\n%s this deletion? [y/n] ", path, action);
7010 break;
7011 case GOT_STATUS_MODIFY:
7012 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7013 return got_error_from_errno("fseek");
7014 printf(GOT_COMMIT_SEP_STR);
7015 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7016 printf("%s", line);
7017 if (ferror(patch_file))
7018 return got_error_from_errno("getline");
7019 printf(GOT_COMMIT_SEP_STR);
7020 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7021 path, n, nchanges, action);
7022 break;
7023 default:
7024 return got_error_path(path, GOT_ERR_FILE_STATUS);
7027 return NULL;
7030 static const struct got_error *
7031 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7032 FILE *patch_file, int n, int nchanges)
7034 const struct got_error *err = NULL;
7035 char *line = NULL;
7036 size_t linesize = 0;
7037 ssize_t linelen;
7038 int resp = ' ';
7039 struct choose_patch_arg *a = arg;
7041 *choice = GOT_PATCH_CHOICE_NONE;
7043 if (a->patch_script_file) {
7044 char *nl;
7045 err = show_change(status, path, patch_file, n, nchanges,
7046 a->action);
7047 if (err)
7048 return err;
7049 linelen = getline(&line, &linesize, a->patch_script_file);
7050 if (linelen == -1) {
7051 if (ferror(a->patch_script_file))
7052 return got_error_from_errno("getline");
7053 return NULL;
7055 nl = strchr(line, '\n');
7056 if (nl)
7057 *nl = '\0';
7058 if (strcmp(line, "y") == 0) {
7059 *choice = GOT_PATCH_CHOICE_YES;
7060 printf("y\n");
7061 } else if (strcmp(line, "n") == 0) {
7062 *choice = GOT_PATCH_CHOICE_NO;
7063 printf("n\n");
7064 } else if (strcmp(line, "q") == 0 &&
7065 status == GOT_STATUS_MODIFY) {
7066 *choice = GOT_PATCH_CHOICE_QUIT;
7067 printf("q\n");
7068 } else
7069 printf("invalid response '%s'\n", line);
7070 free(line);
7071 return NULL;
7074 while (resp != 'y' && resp != 'n' && resp != 'q') {
7075 err = show_change(status, path, patch_file, n, nchanges,
7076 a->action);
7077 if (err)
7078 return err;
7079 resp = getchar();
7080 if (resp == '\n')
7081 resp = getchar();
7082 if (status == GOT_STATUS_MODIFY) {
7083 if (resp != 'y' && resp != 'n' && resp != 'q') {
7084 printf("invalid response '%c'\n", resp);
7085 resp = ' ';
7087 } else if (resp != 'y' && resp != 'n') {
7088 printf("invalid response '%c'\n", resp);
7089 resp = ' ';
7093 if (resp == 'y')
7094 *choice = GOT_PATCH_CHOICE_YES;
7095 else if (resp == 'n')
7096 *choice = GOT_PATCH_CHOICE_NO;
7097 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7098 *choice = GOT_PATCH_CHOICE_QUIT;
7100 return NULL;
7104 static const struct got_error *
7105 cmd_revert(int argc, char *argv[])
7107 const struct got_error *error = NULL;
7108 struct got_worktree *worktree = NULL;
7109 struct got_repository *repo = NULL;
7110 char *cwd = NULL, *path = NULL;
7111 struct got_pathlist_head paths;
7112 struct got_pathlist_entry *pe;
7113 int ch, can_recurse = 0, pflag = 0;
7114 FILE *patch_script_file = NULL;
7115 const char *patch_script_path = NULL;
7116 struct choose_patch_arg cpa;
7118 TAILQ_INIT(&paths);
7120 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7121 switch (ch) {
7122 case 'p':
7123 pflag = 1;
7124 break;
7125 case 'F':
7126 patch_script_path = optarg;
7127 break;
7128 case 'R':
7129 can_recurse = 1;
7130 break;
7131 default:
7132 usage_revert();
7133 /* NOTREACHED */
7137 argc -= optind;
7138 argv += optind;
7140 #ifndef PROFILE
7141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7142 "unveil", NULL) == -1)
7143 err(1, "pledge");
7144 #endif
7145 if (argc < 1)
7146 usage_revert();
7147 if (patch_script_path && !pflag)
7148 errx(1, "-F option can only be used together with -p option");
7150 cwd = getcwd(NULL, 0);
7151 if (cwd == NULL) {
7152 error = got_error_from_errno("getcwd");
7153 goto done;
7155 error = got_worktree_open(&worktree, cwd);
7156 if (error) {
7157 if (error->code == GOT_ERR_NOT_WORKTREE)
7158 error = wrap_not_worktree_error(error, "revert", cwd);
7159 goto done;
7162 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7163 NULL);
7164 if (error != NULL)
7165 goto done;
7167 if (patch_script_path) {
7168 patch_script_file = fopen(patch_script_path, "r");
7169 if (patch_script_file == NULL) {
7170 error = got_error_from_errno2("fopen",
7171 patch_script_path);
7172 goto done;
7175 error = apply_unveil(got_repo_get_path(repo), 1,
7176 got_worktree_get_root_path(worktree));
7177 if (error)
7178 goto done;
7180 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7181 if (error)
7182 goto done;
7184 if (!can_recurse) {
7185 char *ondisk_path;
7186 struct stat sb;
7187 TAILQ_FOREACH(pe, &paths, entry) {
7188 if (asprintf(&ondisk_path, "%s/%s",
7189 got_worktree_get_root_path(worktree),
7190 pe->path) == -1) {
7191 error = got_error_from_errno("asprintf");
7192 goto done;
7194 if (lstat(ondisk_path, &sb) == -1) {
7195 if (errno == ENOENT) {
7196 free(ondisk_path);
7197 continue;
7199 error = got_error_from_errno2("lstat",
7200 ondisk_path);
7201 free(ondisk_path);
7202 goto done;
7204 free(ondisk_path);
7205 if (S_ISDIR(sb.st_mode)) {
7206 error = got_error_msg(GOT_ERR_BAD_PATH,
7207 "reverting directories requires -R option");
7208 goto done;
7213 cpa.patch_script_file = patch_script_file;
7214 cpa.action = "revert";
7215 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7216 pflag ? choose_patch : NULL, &cpa, repo);
7217 done:
7218 if (patch_script_file && fclose(patch_script_file) == EOF &&
7219 error == NULL)
7220 error = got_error_from_errno2("fclose", patch_script_path);
7221 if (repo) {
7222 const struct got_error *close_err = got_repo_close(repo);
7223 if (error == NULL)
7224 error = close_err;
7226 if (worktree)
7227 got_worktree_close(worktree);
7228 free(path);
7229 free(cwd);
7230 return error;
7233 __dead static void
7234 usage_commit(void)
7236 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7237 "[path ...]\n", getprogname());
7238 exit(1);
7241 struct collect_commit_logmsg_arg {
7242 const char *cmdline_log;
7243 const char *prepared_log;
7244 int non_interactive;
7245 const char *editor;
7246 const char *worktree_path;
7247 const char *branch_name;
7248 const char *repo_path;
7249 char *logmsg_path;
7253 static const struct got_error *
7254 read_prepared_logmsg(char **logmsg, const char *path)
7256 const struct got_error *err = NULL;
7257 FILE *f = NULL;
7258 struct stat sb;
7259 size_t r;
7261 *logmsg = NULL;
7262 memset(&sb, 0, sizeof(sb));
7264 f = fopen(path, "r");
7265 if (f == NULL)
7266 return got_error_from_errno2("fopen", path);
7268 if (fstat(fileno(f), &sb) == -1) {
7269 err = got_error_from_errno2("fstat", path);
7270 goto done;
7272 if (sb.st_size == 0) {
7273 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7274 goto done;
7277 *logmsg = malloc(sb.st_size + 1);
7278 if (*logmsg == NULL) {
7279 err = got_error_from_errno("malloc");
7280 goto done;
7283 r = fread(*logmsg, 1, sb.st_size, f);
7284 if (r != sb.st_size) {
7285 if (ferror(f))
7286 err = got_error_from_errno2("fread", path);
7287 else
7288 err = got_error(GOT_ERR_IO);
7289 goto done;
7291 (*logmsg)[sb.st_size] = '\0';
7292 done:
7293 if (fclose(f) == EOF && err == NULL)
7294 err = got_error_from_errno2("fclose", path);
7295 if (err) {
7296 free(*logmsg);
7297 *logmsg = NULL;
7299 return err;
7303 static const struct got_error *
7304 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7305 void *arg)
7307 char *initial_content = NULL;
7308 struct got_pathlist_entry *pe;
7309 const struct got_error *err = NULL;
7310 char *template = NULL;
7311 struct collect_commit_logmsg_arg *a = arg;
7312 int initial_content_len;
7313 int fd = -1;
7314 size_t len;
7316 /* if a message was specified on the command line, just use it */
7317 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7318 len = strlen(a->cmdline_log) + 1;
7319 *logmsg = malloc(len + 1);
7320 if (*logmsg == NULL)
7321 return got_error_from_errno("malloc");
7322 strlcpy(*logmsg, a->cmdline_log, len);
7323 return NULL;
7324 } else if (a->prepared_log != NULL && a->non_interactive)
7325 return read_prepared_logmsg(logmsg, a->prepared_log);
7327 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7328 return got_error_from_errno("asprintf");
7330 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7331 if (err)
7332 goto done;
7334 if (a->prepared_log) {
7335 char *msg;
7336 err = read_prepared_logmsg(&msg, a->prepared_log);
7337 if (err)
7338 goto done;
7339 if (write(fd, msg, strlen(msg)) == -1) {
7340 err = got_error_from_errno2("write", a->logmsg_path);
7341 free(msg);
7342 goto done;
7344 free(msg);
7347 initial_content_len = asprintf(&initial_content,
7348 "\n# changes to be committed on branch %s:\n",
7349 a->branch_name);
7350 if (initial_content_len == -1) {
7351 err = got_error_from_errno("asprintf");
7352 goto done;
7355 if (write(fd, initial_content, initial_content_len) == -1) {
7356 err = got_error_from_errno2("write", a->logmsg_path);
7357 goto done;
7360 TAILQ_FOREACH(pe, commitable_paths, entry) {
7361 struct got_commitable *ct = pe->data;
7362 dprintf(fd, "# %c %s\n",
7363 got_commitable_get_status(ct),
7364 got_commitable_get_path(ct));
7367 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7368 initial_content_len, a->prepared_log ? 0 : 1);
7369 done:
7370 free(initial_content);
7371 free(template);
7373 if (fd != -1 && close(fd) == -1 && err == NULL)
7374 err = got_error_from_errno2("close", a->logmsg_path);
7376 /* Editor is done; we can now apply unveil(2) */
7377 if (err == NULL)
7378 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7379 if (err) {
7380 free(*logmsg);
7381 *logmsg = NULL;
7383 return err;
7386 static const struct got_error *
7387 cmd_commit(int argc, char *argv[])
7389 const struct got_error *error = NULL;
7390 struct got_worktree *worktree = NULL;
7391 struct got_repository *repo = NULL;
7392 char *cwd = NULL, *id_str = NULL;
7393 struct got_object_id *id = NULL;
7394 const char *logmsg = NULL;
7395 char *prepared_logmsg = NULL;
7396 struct collect_commit_logmsg_arg cl_arg;
7397 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7398 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7399 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7400 struct got_pathlist_head paths;
7402 TAILQ_INIT(&paths);
7403 cl_arg.logmsg_path = NULL;
7405 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7406 switch (ch) {
7407 case 'F':
7408 if (logmsg != NULL)
7409 option_conflict('F', 'm');
7410 prepared_logmsg = realpath(optarg, NULL);
7411 if (prepared_logmsg == NULL)
7412 return got_error_from_errno2("realpath",
7413 optarg);
7414 break;
7415 case 'm':
7416 if (prepared_logmsg)
7417 option_conflict('m', 'F');
7418 logmsg = optarg;
7419 break;
7420 case 'N':
7421 non_interactive = 1;
7422 break;
7423 case 'S':
7424 allow_bad_symlinks = 1;
7425 break;
7426 default:
7427 usage_commit();
7428 /* NOTREACHED */
7432 argc -= optind;
7433 argv += optind;
7435 #ifndef PROFILE
7436 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7437 "unveil", NULL) == -1)
7438 err(1, "pledge");
7439 #endif
7440 cwd = getcwd(NULL, 0);
7441 if (cwd == NULL) {
7442 error = got_error_from_errno("getcwd");
7443 goto done;
7445 error = got_worktree_open(&worktree, cwd);
7446 if (error) {
7447 if (error->code == GOT_ERR_NOT_WORKTREE)
7448 error = wrap_not_worktree_error(error, "commit", cwd);
7449 goto done;
7452 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7453 if (error)
7454 goto done;
7455 if (rebase_in_progress) {
7456 error = got_error(GOT_ERR_REBASING);
7457 goto done;
7460 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7461 worktree);
7462 if (error)
7463 goto done;
7465 error = get_gitconfig_path(&gitconfig_path);
7466 if (error)
7467 goto done;
7468 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7469 gitconfig_path);
7470 if (error != NULL)
7471 goto done;
7473 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7474 if (error)
7475 goto done;
7476 if (merge_in_progress) {
7477 error = got_error(GOT_ERR_MERGE_BUSY);
7478 goto done;
7481 error = get_author(&author, repo, worktree);
7482 if (error)
7483 return error;
7486 * unveil(2) traverses exec(2); if an editor is used we have
7487 * to apply unveil after the log message has been written.
7489 if (logmsg == NULL || strlen(logmsg) == 0)
7490 error = get_editor(&editor);
7491 else
7492 error = apply_unveil(got_repo_get_path(repo), 0,
7493 got_worktree_get_root_path(worktree));
7494 if (error)
7495 goto done;
7497 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7498 if (error)
7499 goto done;
7501 cl_arg.editor = editor;
7502 cl_arg.cmdline_log = logmsg;
7503 cl_arg.prepared_log = prepared_logmsg;
7504 cl_arg.non_interactive = non_interactive;
7505 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7506 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7507 if (!histedit_in_progress) {
7508 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7509 error = got_error(GOT_ERR_COMMIT_BRANCH);
7510 goto done;
7512 cl_arg.branch_name += 11;
7514 cl_arg.repo_path = got_repo_get_path(repo);
7515 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7516 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7517 print_status, NULL, repo);
7518 if (error) {
7519 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7520 cl_arg.logmsg_path != NULL)
7521 preserve_logmsg = 1;
7522 goto done;
7525 error = got_object_id_str(&id_str, id);
7526 if (error)
7527 goto done;
7528 printf("Created commit %s\n", id_str);
7529 done:
7530 if (preserve_logmsg) {
7531 fprintf(stderr, "%s: log message preserved in %s\n",
7532 getprogname(), cl_arg.logmsg_path);
7533 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7534 error == NULL)
7535 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7536 free(cl_arg.logmsg_path);
7537 if (repo) {
7538 const struct got_error *close_err = got_repo_close(repo);
7539 if (error == NULL)
7540 error = close_err;
7542 if (worktree)
7543 got_worktree_close(worktree);
7544 free(cwd);
7545 free(id_str);
7546 free(gitconfig_path);
7547 free(editor);
7548 free(author);
7549 free(prepared_logmsg);
7550 return error;
7553 __dead static void
7554 usage_send(void)
7556 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7557 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7558 "[remote-repository]\n", getprogname());
7559 exit(1);
7562 struct got_send_progress_arg {
7563 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7564 int verbosity;
7565 int last_ncommits;
7566 int last_nobj_total;
7567 int last_p_deltify;
7568 int last_p_written;
7569 int last_p_sent;
7570 int printed_something;
7571 int sent_something;
7572 struct got_pathlist_head *delete_branches;
7575 static const struct got_error *
7576 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7577 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7578 int success)
7580 struct got_send_progress_arg *a = arg;
7581 char scaled_packsize[FMT_SCALED_STRSIZE];
7582 char scaled_sent[FMT_SCALED_STRSIZE];
7583 int p_deltify = 0, p_written = 0, p_sent = 0;
7584 int print_searching = 0, print_total = 0;
7585 int print_deltify = 0, print_written = 0, print_sent = 0;
7587 if (a->verbosity < 0)
7588 return NULL;
7590 if (refname) {
7591 const char *status = success ? "accepted" : "rejected";
7593 if (success) {
7594 struct got_pathlist_entry *pe;
7595 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7596 const char *branchname = pe->path;
7597 if (got_path_cmp(branchname, refname,
7598 strlen(branchname), strlen(refname)) == 0) {
7599 status = "deleted";
7600 a->sent_something = 1;
7601 break;
7606 if (a->printed_something)
7607 putchar('\n');
7608 printf("Server has %s %s", status, refname);
7609 a->printed_something = 1;
7610 return NULL;
7613 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7614 return got_error_from_errno("fmt_scaled");
7615 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7616 return got_error_from_errno("fmt_scaled");
7618 if (a->last_ncommits != ncommits) {
7619 print_searching = 1;
7620 a->last_ncommits = ncommits;
7623 if (a->last_nobj_total != nobj_total) {
7624 print_searching = 1;
7625 print_total = 1;
7626 a->last_nobj_total = nobj_total;
7629 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7630 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7631 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7632 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7633 return got_error(GOT_ERR_NO_SPACE);
7636 if (nobj_deltify > 0 || nobj_written > 0) {
7637 if (nobj_deltify > 0) {
7638 p_deltify = (nobj_deltify * 100) / nobj_total;
7639 if (p_deltify != a->last_p_deltify) {
7640 a->last_p_deltify = p_deltify;
7641 print_searching = 1;
7642 print_total = 1;
7643 print_deltify = 1;
7646 if (nobj_written > 0) {
7647 p_written = (nobj_written * 100) / nobj_total;
7648 if (p_written != a->last_p_written) {
7649 a->last_p_written = p_written;
7650 print_searching = 1;
7651 print_total = 1;
7652 print_deltify = 1;
7653 print_written = 1;
7658 if (bytes_sent > 0) {
7659 p_sent = (bytes_sent * 100) / packfile_size;
7660 if (p_sent != a->last_p_sent) {
7661 a->last_p_sent = p_sent;
7662 print_searching = 1;
7663 print_total = 1;
7664 print_deltify = 1;
7665 print_written = 1;
7666 print_sent = 1;
7668 a->sent_something = 1;
7671 if (print_searching || print_total || print_deltify || print_written ||
7672 print_sent)
7673 printf("\r");
7674 if (print_searching)
7675 printf("packing %d reference%s", ncommits,
7676 ncommits == 1 ? "" : "s");
7677 if (print_total)
7678 printf("; %d object%s", nobj_total,
7679 nobj_total == 1 ? "" : "s");
7680 if (print_deltify)
7681 printf("; deltify: %d%%", p_deltify);
7682 if (print_sent)
7683 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7684 scaled_packsize, p_sent);
7685 else if (print_written)
7686 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7687 scaled_packsize, p_written);
7688 if (print_searching || print_total || print_deltify ||
7689 print_written || print_sent) {
7690 a->printed_something = 1;
7691 fflush(stdout);
7693 return NULL;
7696 static const struct got_error *
7697 cmd_send(int argc, char *argv[])
7699 const struct got_error *error = NULL;
7700 char *cwd = NULL, *repo_path = NULL;
7701 const char *remote_name;
7702 char *proto = NULL, *host = NULL, *port = NULL;
7703 char *repo_name = NULL, *server_path = NULL;
7704 const struct got_remote_repo *remotes, *remote = NULL;
7705 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7706 struct got_repository *repo = NULL;
7707 struct got_worktree *worktree = NULL;
7708 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7709 struct got_pathlist_head branches;
7710 struct got_pathlist_head tags;
7711 struct got_reflist_head all_branches;
7712 struct got_reflist_head all_tags;
7713 struct got_pathlist_head delete_args;
7714 struct got_pathlist_head delete_branches;
7715 struct got_reflist_entry *re;
7716 struct got_pathlist_entry *pe;
7717 int i, ch, sendfd = -1, sendstatus;
7718 pid_t sendpid = -1;
7719 struct got_send_progress_arg spa;
7720 int verbosity = 0, overwrite_refs = 0;
7721 int send_all_branches = 0, send_all_tags = 0;
7722 struct got_reference *ref = NULL;
7724 TAILQ_INIT(&branches);
7725 TAILQ_INIT(&tags);
7726 TAILQ_INIT(&all_branches);
7727 TAILQ_INIT(&all_tags);
7728 TAILQ_INIT(&delete_args);
7729 TAILQ_INIT(&delete_branches);
7731 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7732 switch (ch) {
7733 case 'a':
7734 send_all_branches = 1;
7735 break;
7736 case 'b':
7737 error = got_pathlist_append(&branches, optarg, NULL);
7738 if (error)
7739 return error;
7740 nbranches++;
7741 break;
7742 case 'd':
7743 error = got_pathlist_append(&delete_args, optarg, NULL);
7744 if (error)
7745 return error;
7746 break;
7747 case 'f':
7748 overwrite_refs = 1;
7749 break;
7750 case 'r':
7751 repo_path = realpath(optarg, NULL);
7752 if (repo_path == NULL)
7753 return got_error_from_errno2("realpath",
7754 optarg);
7755 got_path_strip_trailing_slashes(repo_path);
7756 break;
7757 case 't':
7758 error = got_pathlist_append(&tags, optarg, NULL);
7759 if (error)
7760 return error;
7761 ntags++;
7762 break;
7763 case 'T':
7764 send_all_tags = 1;
7765 break;
7766 case 'v':
7767 if (verbosity < 0)
7768 verbosity = 0;
7769 else if (verbosity < 3)
7770 verbosity++;
7771 break;
7772 case 'q':
7773 verbosity = -1;
7774 break;
7775 default:
7776 usage_send();
7777 /* NOTREACHED */
7780 argc -= optind;
7781 argv += optind;
7783 if (send_all_branches && !TAILQ_EMPTY(&branches))
7784 option_conflict('a', 'b');
7785 if (send_all_tags && !TAILQ_EMPTY(&tags))
7786 option_conflict('T', 't');
7789 if (argc == 0)
7790 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7791 else if (argc == 1)
7792 remote_name = argv[0];
7793 else
7794 usage_send();
7796 cwd = getcwd(NULL, 0);
7797 if (cwd == NULL) {
7798 error = got_error_from_errno("getcwd");
7799 goto done;
7802 if (repo_path == NULL) {
7803 error = got_worktree_open(&worktree, cwd);
7804 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7805 goto done;
7806 else
7807 error = NULL;
7808 if (worktree) {
7809 repo_path =
7810 strdup(got_worktree_get_repo_path(worktree));
7811 if (repo_path == NULL)
7812 error = got_error_from_errno("strdup");
7813 if (error)
7814 goto done;
7815 } else {
7816 repo_path = strdup(cwd);
7817 if (repo_path == NULL) {
7818 error = got_error_from_errno("strdup");
7819 goto done;
7824 error = got_repo_open(&repo, repo_path, NULL);
7825 if (error)
7826 goto done;
7828 if (worktree) {
7829 worktree_conf = got_worktree_get_gotconfig(worktree);
7830 if (worktree_conf) {
7831 got_gotconfig_get_remotes(&nremotes, &remotes,
7832 worktree_conf);
7833 for (i = 0; i < nremotes; i++) {
7834 if (strcmp(remotes[i].name, remote_name) == 0) {
7835 remote = &remotes[i];
7836 break;
7841 if (remote == NULL) {
7842 repo_conf = got_repo_get_gotconfig(repo);
7843 if (repo_conf) {
7844 got_gotconfig_get_remotes(&nremotes, &remotes,
7845 repo_conf);
7846 for (i = 0; i < nremotes; i++) {
7847 if (strcmp(remotes[i].name, remote_name) == 0) {
7848 remote = &remotes[i];
7849 break;
7854 if (remote == NULL) {
7855 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7856 for (i = 0; i < nremotes; i++) {
7857 if (strcmp(remotes[i].name, remote_name) == 0) {
7858 remote = &remotes[i];
7859 break;
7863 if (remote == NULL) {
7864 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7865 goto done;
7868 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7869 &repo_name, remote->send_url);
7870 if (error)
7871 goto done;
7873 if (strcmp(proto, "git") == 0) {
7874 #ifndef PROFILE
7875 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7876 "sendfd dns inet unveil", NULL) == -1)
7877 err(1, "pledge");
7878 #endif
7879 } else if (strcmp(proto, "git+ssh") == 0 ||
7880 strcmp(proto, "ssh") == 0) {
7881 #ifndef PROFILE
7882 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7883 "sendfd unveil", NULL) == -1)
7884 err(1, "pledge");
7885 #endif
7886 } else if (strcmp(proto, "http") == 0 ||
7887 strcmp(proto, "git+http") == 0) {
7888 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7889 goto done;
7890 } else {
7891 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7892 goto done;
7895 error = got_dial_apply_unveil(proto);
7896 if (error)
7897 goto done;
7899 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7900 if (error)
7901 goto done;
7903 if (send_all_branches) {
7904 error = got_ref_list(&all_branches, repo, "refs/heads",
7905 got_ref_cmp_by_name, NULL);
7906 if (error)
7907 goto done;
7908 TAILQ_FOREACH(re, &all_branches, entry) {
7909 const char *branchname = got_ref_get_name(re->ref);
7910 error = got_pathlist_append(&branches,
7911 branchname, NULL);
7912 if (error)
7913 goto done;
7914 nbranches++;
7916 } else if (nbranches == 0) {
7917 for (i = 0; i < remote->nsend_branches; i++) {
7918 got_pathlist_append(&branches,
7919 remote->send_branches[i], NULL);
7923 if (send_all_tags) {
7924 error = got_ref_list(&all_tags, repo, "refs/tags",
7925 got_ref_cmp_by_name, NULL);
7926 if (error)
7927 goto done;
7928 TAILQ_FOREACH(re, &all_tags, entry) {
7929 const char *tagname = got_ref_get_name(re->ref);
7930 error = got_pathlist_append(&tags,
7931 tagname, NULL);
7932 if (error)
7933 goto done;
7934 ntags++;
7939 * To prevent accidents only branches in refs/heads/ can be deleted
7940 * with 'got send -d'.
7941 * Deleting anything else requires local repository access or Git.
7943 TAILQ_FOREACH(pe, &delete_args, entry) {
7944 const char *branchname = pe->path;
7945 char *s;
7946 struct got_pathlist_entry *new;
7947 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7948 s = strdup(branchname);
7949 if (s == NULL) {
7950 error = got_error_from_errno("strdup");
7951 goto done;
7953 } else {
7954 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7955 error = got_error_from_errno("asprintf");
7956 goto done;
7959 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7960 if (error || new == NULL /* duplicate */)
7961 free(s);
7962 if (error)
7963 goto done;
7964 ndelete_branches++;
7967 if (nbranches == 0 && ndelete_branches == 0) {
7968 struct got_reference *head_ref;
7969 if (worktree)
7970 error = got_ref_open(&head_ref, repo,
7971 got_worktree_get_head_ref_name(worktree), 0);
7972 else
7973 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7974 if (error)
7975 goto done;
7976 if (got_ref_is_symbolic(head_ref)) {
7977 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7978 got_ref_close(head_ref);
7979 if (error)
7980 goto done;
7981 } else
7982 ref = head_ref;
7983 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7984 NULL);
7985 if (error)
7986 goto done;
7987 nbranches++;
7990 if (verbosity >= 0)
7991 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7992 port ? ":" : "", port ? port : "");
7994 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7995 server_path, verbosity);
7996 if (error)
7997 goto done;
7999 memset(&spa, 0, sizeof(spa));
8000 spa.last_scaled_packsize[0] = '\0';
8001 spa.last_p_deltify = -1;
8002 spa.last_p_written = -1;
8003 spa.verbosity = verbosity;
8004 spa.delete_branches = &delete_branches;
8005 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8006 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8007 check_cancelled, NULL);
8008 if (spa.printed_something)
8009 putchar('\n');
8010 if (error)
8011 goto done;
8012 if (!spa.sent_something && verbosity >= 0)
8013 printf("Already up-to-date\n");
8014 done:
8015 if (sendpid > 0) {
8016 if (kill(sendpid, SIGTERM) == -1)
8017 error = got_error_from_errno("kill");
8018 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8019 error = got_error_from_errno("waitpid");
8021 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8022 error = got_error_from_errno("close");
8023 if (repo) {
8024 const struct got_error *close_err = got_repo_close(repo);
8025 if (error == NULL)
8026 error = close_err;
8028 if (worktree)
8029 got_worktree_close(worktree);
8030 if (ref)
8031 got_ref_close(ref);
8032 got_pathlist_free(&branches);
8033 got_pathlist_free(&tags);
8034 got_ref_list_free(&all_branches);
8035 got_ref_list_free(&all_tags);
8036 got_pathlist_free(&delete_args);
8037 TAILQ_FOREACH(pe, &delete_branches, entry)
8038 free((char *)pe->path);
8039 got_pathlist_free(&delete_branches);
8040 free(cwd);
8041 free(repo_path);
8042 free(proto);
8043 free(host);
8044 free(port);
8045 free(server_path);
8046 free(repo_name);
8047 return error;
8050 __dead static void
8051 usage_cherrypick(void)
8053 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8054 exit(1);
8057 static const struct got_error *
8058 cmd_cherrypick(int argc, char *argv[])
8060 const struct got_error *error = NULL;
8061 struct got_worktree *worktree = NULL;
8062 struct got_repository *repo = NULL;
8063 char *cwd = NULL, *commit_id_str = NULL;
8064 struct got_object_id *commit_id = NULL;
8065 struct got_commit_object *commit = NULL;
8066 struct got_object_qid *pid;
8067 int ch;
8068 struct got_update_progress_arg upa;
8070 while ((ch = getopt(argc, argv, "")) != -1) {
8071 switch (ch) {
8072 default:
8073 usage_cherrypick();
8074 /* NOTREACHED */
8078 argc -= optind;
8079 argv += optind;
8081 #ifndef PROFILE
8082 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8083 "unveil", NULL) == -1)
8084 err(1, "pledge");
8085 #endif
8086 if (argc != 1)
8087 usage_cherrypick();
8089 cwd = getcwd(NULL, 0);
8090 if (cwd == NULL) {
8091 error = got_error_from_errno("getcwd");
8092 goto done;
8094 error = got_worktree_open(&worktree, cwd);
8095 if (error) {
8096 if (error->code == GOT_ERR_NOT_WORKTREE)
8097 error = wrap_not_worktree_error(error, "cherrypick",
8098 cwd);
8099 goto done;
8102 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8103 NULL);
8104 if (error != NULL)
8105 goto done;
8107 error = apply_unveil(got_repo_get_path(repo), 0,
8108 got_worktree_get_root_path(worktree));
8109 if (error)
8110 goto done;
8112 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8113 GOT_OBJ_TYPE_COMMIT, repo);
8114 if (error != NULL) {
8115 struct got_reference *ref;
8116 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8117 goto done;
8118 error = got_ref_open(&ref, repo, argv[0], 0);
8119 if (error != NULL)
8120 goto done;
8121 error = got_ref_resolve(&commit_id, repo, ref);
8122 got_ref_close(ref);
8123 if (error != NULL)
8124 goto done;
8126 error = got_object_id_str(&commit_id_str, commit_id);
8127 if (error)
8128 goto done;
8130 error = got_object_open_as_commit(&commit, repo, commit_id);
8131 if (error)
8132 goto done;
8133 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8134 memset(&upa, 0, sizeof(upa));
8135 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8136 commit_id, repo, update_progress, &upa, check_cancelled,
8137 NULL);
8138 if (error != NULL)
8139 goto done;
8141 if (upa.did_something)
8142 printf("Merged commit %s\n", commit_id_str);
8143 print_merge_progress_stats(&upa);
8144 done:
8145 if (commit)
8146 got_object_commit_close(commit);
8147 free(commit_id_str);
8148 if (worktree)
8149 got_worktree_close(worktree);
8150 if (repo) {
8151 const struct got_error *close_err = got_repo_close(repo);
8152 if (error == NULL)
8153 error = close_err;
8155 return error;
8158 __dead static void
8159 usage_backout(void)
8161 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8162 exit(1);
8165 static const struct got_error *
8166 cmd_backout(int argc, char *argv[])
8168 const struct got_error *error = NULL;
8169 struct got_worktree *worktree = NULL;
8170 struct got_repository *repo = NULL;
8171 char *cwd = NULL, *commit_id_str = NULL;
8172 struct got_object_id *commit_id = NULL;
8173 struct got_commit_object *commit = NULL;
8174 struct got_object_qid *pid;
8175 int ch;
8176 struct got_update_progress_arg upa;
8178 while ((ch = getopt(argc, argv, "")) != -1) {
8179 switch (ch) {
8180 default:
8181 usage_backout();
8182 /* NOTREACHED */
8186 argc -= optind;
8187 argv += optind;
8189 #ifndef PROFILE
8190 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8191 "unveil", NULL) == -1)
8192 err(1, "pledge");
8193 #endif
8194 if (argc != 1)
8195 usage_backout();
8197 cwd = getcwd(NULL, 0);
8198 if (cwd == NULL) {
8199 error = got_error_from_errno("getcwd");
8200 goto done;
8202 error = got_worktree_open(&worktree, cwd);
8203 if (error) {
8204 if (error->code == GOT_ERR_NOT_WORKTREE)
8205 error = wrap_not_worktree_error(error, "backout", cwd);
8206 goto done;
8209 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8210 NULL);
8211 if (error != NULL)
8212 goto done;
8214 error = apply_unveil(got_repo_get_path(repo), 0,
8215 got_worktree_get_root_path(worktree));
8216 if (error)
8217 goto done;
8219 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8220 GOT_OBJ_TYPE_COMMIT, repo);
8221 if (error != NULL) {
8222 struct got_reference *ref;
8223 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8224 goto done;
8225 error = got_ref_open(&ref, repo, argv[0], 0);
8226 if (error != NULL)
8227 goto done;
8228 error = got_ref_resolve(&commit_id, repo, ref);
8229 got_ref_close(ref);
8230 if (error != NULL)
8231 goto done;
8233 error = got_object_id_str(&commit_id_str, commit_id);
8234 if (error)
8235 goto done;
8237 error = got_object_open_as_commit(&commit, repo, commit_id);
8238 if (error)
8239 goto done;
8240 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8241 if (pid == NULL) {
8242 error = got_error(GOT_ERR_ROOT_COMMIT);
8243 goto done;
8246 memset(&upa, 0, sizeof(upa));
8247 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8248 repo, update_progress, &upa, check_cancelled, NULL);
8249 if (error != NULL)
8250 goto done;
8252 if (upa.did_something)
8253 printf("Backed out commit %s\n", commit_id_str);
8254 print_merge_progress_stats(&upa);
8255 done:
8256 if (commit)
8257 got_object_commit_close(commit);
8258 free(commit_id_str);
8259 if (worktree)
8260 got_worktree_close(worktree);
8261 if (repo) {
8262 const struct got_error *close_err = got_repo_close(repo);
8263 if (error == NULL)
8264 error = close_err;
8266 return error;
8269 __dead static void
8270 usage_rebase(void)
8272 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8273 getprogname());
8274 exit(1);
8277 void
8278 trim_logmsg(char *logmsg, int limit)
8280 char *nl;
8281 size_t len;
8283 len = strlen(logmsg);
8284 if (len > limit)
8285 len = limit;
8286 logmsg[len] = '\0';
8287 nl = strchr(logmsg, '\n');
8288 if (nl)
8289 *nl = '\0';
8292 static const struct got_error *
8293 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8295 const struct got_error *err;
8296 char *logmsg0 = NULL;
8297 const char *s;
8299 err = got_object_commit_get_logmsg(&logmsg0, commit);
8300 if (err)
8301 return err;
8303 s = logmsg0;
8304 while (isspace((unsigned char)s[0]))
8305 s++;
8307 *logmsg = strdup(s);
8308 if (*logmsg == NULL) {
8309 err = got_error_from_errno("strdup");
8310 goto done;
8313 trim_logmsg(*logmsg, limit);
8314 done:
8315 free(logmsg0);
8316 return err;
8319 static const struct got_error *
8320 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8322 const struct got_error *err;
8323 struct got_commit_object *commit = NULL;
8324 char *id_str = NULL, *logmsg = NULL;
8326 err = got_object_open_as_commit(&commit, repo, id);
8327 if (err)
8328 return err;
8330 err = got_object_id_str(&id_str, id);
8331 if (err)
8332 goto done;
8334 id_str[12] = '\0';
8336 err = get_short_logmsg(&logmsg, 42, commit);
8337 if (err)
8338 goto done;
8340 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8341 done:
8342 free(id_str);
8343 got_object_commit_close(commit);
8344 free(logmsg);
8345 return err;
8348 static const struct got_error *
8349 show_rebase_progress(struct got_commit_object *commit,
8350 struct got_object_id *old_id, struct got_object_id *new_id)
8352 const struct got_error *err;
8353 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8355 err = got_object_id_str(&old_id_str, old_id);
8356 if (err)
8357 goto done;
8359 if (new_id) {
8360 err = got_object_id_str(&new_id_str, new_id);
8361 if (err)
8362 goto done;
8365 old_id_str[12] = '\0';
8366 if (new_id_str)
8367 new_id_str[12] = '\0';
8369 err = get_short_logmsg(&logmsg, 42, commit);
8370 if (err)
8371 goto done;
8373 printf("%s -> %s: %s\n", old_id_str,
8374 new_id_str ? new_id_str : "no-op change", logmsg);
8375 done:
8376 free(old_id_str);
8377 free(new_id_str);
8378 free(logmsg);
8379 return err;
8382 static const struct got_error *
8383 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8384 struct got_reference *branch, struct got_reference *new_base_branch,
8385 struct got_reference *tmp_branch, struct got_repository *repo,
8386 int create_backup)
8388 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8389 return got_worktree_rebase_complete(worktree, fileindex,
8390 new_base_branch, tmp_branch, branch, repo, create_backup);
8393 static const struct got_error *
8394 rebase_commit(struct got_pathlist_head *merged_paths,
8395 struct got_worktree *worktree, struct got_fileindex *fileindex,
8396 struct got_reference *tmp_branch,
8397 struct got_object_id *commit_id, struct got_repository *repo)
8399 const struct got_error *error;
8400 struct got_commit_object *commit;
8401 struct got_object_id *new_commit_id;
8403 error = got_object_open_as_commit(&commit, repo, commit_id);
8404 if (error)
8405 return error;
8407 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8408 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8409 if (error) {
8410 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8411 goto done;
8412 error = show_rebase_progress(commit, commit_id, NULL);
8413 } else {
8414 error = show_rebase_progress(commit, commit_id, new_commit_id);
8415 free(new_commit_id);
8417 done:
8418 got_object_commit_close(commit);
8419 return error;
8422 struct check_path_prefix_arg {
8423 const char *path_prefix;
8424 size_t len;
8425 int errcode;
8428 static const struct got_error *
8429 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8430 struct got_blob_object *blob2, struct got_object_id *id1,
8431 struct got_object_id *id2, const char *path1, const char *path2,
8432 mode_t mode1, mode_t mode2, struct got_repository *repo)
8434 struct check_path_prefix_arg *a = arg;
8436 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8437 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8438 return got_error(a->errcode);
8440 return NULL;
8443 static const struct got_error *
8444 check_path_prefix(struct got_object_id *parent_id,
8445 struct got_object_id *commit_id, const char *path_prefix,
8446 int errcode, struct got_repository *repo)
8448 const struct got_error *err;
8449 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8450 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8451 struct check_path_prefix_arg cpp_arg;
8453 if (got_path_is_root_dir(path_prefix))
8454 return NULL;
8456 err = got_object_open_as_commit(&commit, repo, commit_id);
8457 if (err)
8458 goto done;
8460 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8461 if (err)
8462 goto done;
8464 err = got_object_open_as_tree(&tree1, repo,
8465 got_object_commit_get_tree_id(parent_commit));
8466 if (err)
8467 goto done;
8469 err = got_object_open_as_tree(&tree2, repo,
8470 got_object_commit_get_tree_id(commit));
8471 if (err)
8472 goto done;
8474 cpp_arg.path_prefix = path_prefix;
8475 while (cpp_arg.path_prefix[0] == '/')
8476 cpp_arg.path_prefix++;
8477 cpp_arg.len = strlen(cpp_arg.path_prefix);
8478 cpp_arg.errcode = errcode;
8479 err = got_diff_tree(tree1, tree2, "", "", repo,
8480 check_path_prefix_in_diff, &cpp_arg, 0);
8481 done:
8482 if (tree1)
8483 got_object_tree_close(tree1);
8484 if (tree2)
8485 got_object_tree_close(tree2);
8486 if (commit)
8487 got_object_commit_close(commit);
8488 if (parent_commit)
8489 got_object_commit_close(parent_commit);
8490 return err;
8493 static const struct got_error *
8494 collect_commits(struct got_object_id_queue *commits,
8495 struct got_object_id *initial_commit_id,
8496 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8497 const char *path_prefix, int path_prefix_errcode,
8498 struct got_repository *repo)
8500 const struct got_error *err = NULL;
8501 struct got_commit_graph *graph = NULL;
8502 struct got_object_id *parent_id = NULL;
8503 struct got_object_qid *qid;
8504 struct got_object_id *commit_id = initial_commit_id;
8506 err = got_commit_graph_open(&graph, "/", 1);
8507 if (err)
8508 return err;
8510 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8511 check_cancelled, NULL);
8512 if (err)
8513 goto done;
8514 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8515 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8516 check_cancelled, NULL);
8517 if (err) {
8518 if (err->code == GOT_ERR_ITER_COMPLETED) {
8519 err = got_error_msg(GOT_ERR_ANCESTRY,
8520 "ran out of commits to rebase before "
8521 "youngest common ancestor commit has "
8522 "been reached?!?");
8524 goto done;
8525 } else {
8526 err = check_path_prefix(parent_id, commit_id,
8527 path_prefix, path_prefix_errcode, repo);
8528 if (err)
8529 goto done;
8531 err = got_object_qid_alloc(&qid, commit_id);
8532 if (err)
8533 goto done;
8534 STAILQ_INSERT_HEAD(commits, qid, entry);
8535 commit_id = parent_id;
8538 done:
8539 got_commit_graph_close(graph);
8540 return err;
8543 static const struct got_error *
8544 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8546 const struct got_error *err = NULL;
8547 time_t committer_time;
8548 struct tm tm;
8549 char datebuf[11]; /* YYYY-MM-DD + NUL */
8550 char *author0 = NULL, *author, *smallerthan;
8551 char *logmsg0 = NULL, *logmsg, *newline;
8553 committer_time = got_object_commit_get_committer_time(commit);
8554 if (gmtime_r(&committer_time, &tm) == NULL)
8555 return got_error_from_errno("gmtime_r");
8556 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8557 return got_error(GOT_ERR_NO_SPACE);
8559 author0 = strdup(got_object_commit_get_author(commit));
8560 if (author0 == NULL)
8561 return got_error_from_errno("strdup");
8562 author = author0;
8563 smallerthan = strchr(author, '<');
8564 if (smallerthan && smallerthan[1] != '\0')
8565 author = smallerthan + 1;
8566 author[strcspn(author, "@>")] = '\0';
8568 err = got_object_commit_get_logmsg(&logmsg0, commit);
8569 if (err)
8570 goto done;
8571 logmsg = logmsg0;
8572 while (*logmsg == '\n')
8573 logmsg++;
8574 newline = strchr(logmsg, '\n');
8575 if (newline)
8576 *newline = '\0';
8578 if (asprintf(brief_str, "%s %s %s",
8579 datebuf, author, logmsg) == -1)
8580 err = got_error_from_errno("asprintf");
8581 done:
8582 free(author0);
8583 free(logmsg0);
8584 return err;
8587 static const struct got_error *
8588 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8589 struct got_repository *repo)
8591 const struct got_error *err;
8592 char *id_str;
8594 err = got_object_id_str(&id_str, id);
8595 if (err)
8596 return err;
8598 err = got_ref_delete(ref, repo);
8599 if (err)
8600 goto done;
8602 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8603 done:
8604 free(id_str);
8605 return err;
8608 static const struct got_error *
8609 print_backup_ref(const char *branch_name, const char *new_id_str,
8610 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8611 struct got_reflist_object_id_map *refs_idmap,
8612 struct got_repository *repo)
8614 const struct got_error *err = NULL;
8615 struct got_reflist_head *refs;
8616 char *refs_str = NULL;
8617 struct got_object_id *new_commit_id = NULL;
8618 struct got_commit_object *new_commit = NULL;
8619 char *new_commit_brief_str = NULL;
8620 struct got_object_id *yca_id = NULL;
8621 struct got_commit_object *yca_commit = NULL;
8622 char *yca_id_str = NULL, *yca_brief_str = NULL;
8623 char *custom_refs_str;
8625 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8626 return got_error_from_errno("asprintf");
8628 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8629 0, 0, refs_idmap, custom_refs_str);
8630 if (err)
8631 goto done;
8633 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8634 if (err)
8635 goto done;
8637 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8638 if (refs) {
8639 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8640 if (err)
8641 goto done;
8644 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8645 if (err)
8646 goto done;
8648 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8649 if (err)
8650 goto done;
8652 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8653 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
8654 if (err)
8655 goto done;
8657 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8658 refs_str ? " (" : "", refs_str ? refs_str : "",
8659 refs_str ? ")" : "", new_commit_brief_str);
8660 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8661 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8662 free(refs_str);
8663 refs_str = NULL;
8665 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8666 if (err)
8667 goto done;
8669 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8670 if (err)
8671 goto done;
8673 err = got_object_id_str(&yca_id_str, yca_id);
8674 if (err)
8675 goto done;
8677 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8678 if (refs) {
8679 err = build_refs_str(&refs_str, refs, yca_id, repo);
8680 if (err)
8681 goto done;
8683 printf("history forked at %s%s%s%s\n %s\n",
8684 yca_id_str,
8685 refs_str ? " (" : "", refs_str ? refs_str : "",
8686 refs_str ? ")" : "", yca_brief_str);
8688 done:
8689 free(custom_refs_str);
8690 free(new_commit_id);
8691 free(refs_str);
8692 free(yca_id);
8693 free(yca_id_str);
8694 free(yca_brief_str);
8695 if (new_commit)
8696 got_object_commit_close(new_commit);
8697 if (yca_commit)
8698 got_object_commit_close(yca_commit);
8700 return NULL;
8703 static const struct got_error *
8704 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8705 int delete, struct got_repository *repo)
8707 const struct got_error *err;
8708 struct got_reflist_head refs, backup_refs;
8709 struct got_reflist_entry *re;
8710 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8711 struct got_object_id *old_commit_id = NULL;
8712 char *branch_name = NULL;
8713 struct got_commit_object *old_commit = NULL;
8714 struct got_reflist_object_id_map *refs_idmap = NULL;
8715 int wanted_branch_found = 0;
8717 TAILQ_INIT(&refs);
8718 TAILQ_INIT(&backup_refs);
8720 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8721 if (err)
8722 return err;
8724 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8725 if (err)
8726 goto done;
8728 if (wanted_branch_name) {
8729 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8730 wanted_branch_name += 11;
8733 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8734 got_ref_cmp_by_commit_timestamp_descending, repo);
8735 if (err)
8736 goto done;
8738 TAILQ_FOREACH(re, &backup_refs, entry) {
8739 const char *refname = got_ref_get_name(re->ref);
8740 char *slash;
8742 err = check_cancelled(NULL);
8743 if (err)
8744 break;
8746 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8747 if (err)
8748 break;
8750 err = got_object_open_as_commit(&old_commit, repo,
8751 old_commit_id);
8752 if (err)
8753 break;
8755 if (strncmp(backup_ref_prefix, refname,
8756 backup_ref_prefix_len) == 0)
8757 refname += backup_ref_prefix_len;
8759 while (refname[0] == '/')
8760 refname++;
8762 branch_name = strdup(refname);
8763 if (branch_name == NULL) {
8764 err = got_error_from_errno("strdup");
8765 break;
8767 slash = strrchr(branch_name, '/');
8768 if (slash) {
8769 *slash = '\0';
8770 refname += strlen(branch_name) + 1;
8773 if (wanted_branch_name == NULL ||
8774 strcmp(wanted_branch_name, branch_name) == 0) {
8775 wanted_branch_found = 1;
8776 if (delete) {
8777 err = delete_backup_ref(re->ref,
8778 old_commit_id, repo);
8779 } else {
8780 err = print_backup_ref(branch_name, refname,
8781 old_commit_id, old_commit, refs_idmap,
8782 repo);
8784 if (err)
8785 break;
8788 free(old_commit_id);
8789 old_commit_id = NULL;
8790 free(branch_name);
8791 branch_name = NULL;
8792 got_object_commit_close(old_commit);
8793 old_commit = NULL;
8796 if (wanted_branch_name && !wanted_branch_found) {
8797 err = got_error_fmt(GOT_ERR_NOT_REF,
8798 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8800 done:
8801 if (refs_idmap)
8802 got_reflist_object_id_map_free(refs_idmap);
8803 got_ref_list_free(&refs);
8804 got_ref_list_free(&backup_refs);
8805 free(old_commit_id);
8806 free(branch_name);
8807 if (old_commit)
8808 got_object_commit_close(old_commit);
8809 return err;
8812 static const struct got_error *
8813 abort_progress(void *arg, unsigned char status, const char *path)
8816 * Unversioned files should not clutter progress output when
8817 * an operation is aborted.
8819 if (status == GOT_STATUS_UNVERSIONED)
8820 return NULL;
8822 return update_progress(arg, status, path);
8825 static const struct got_error *
8826 cmd_rebase(int argc, char *argv[])
8828 const struct got_error *error = NULL;
8829 struct got_worktree *worktree = NULL;
8830 struct got_repository *repo = NULL;
8831 struct got_fileindex *fileindex = NULL;
8832 char *cwd = NULL;
8833 struct got_reference *branch = NULL;
8834 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8835 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8836 struct got_object_id *resume_commit_id = NULL;
8837 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8838 struct got_commit_object *commit = NULL;
8839 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8840 int histedit_in_progress = 0, merge_in_progress = 0;
8841 int create_backup = 1, list_backups = 0, delete_backups = 0;
8842 struct got_object_id_queue commits;
8843 struct got_pathlist_head merged_paths;
8844 const struct got_object_id_queue *parent_ids;
8845 struct got_object_qid *qid, *pid;
8846 struct got_update_progress_arg upa;
8848 STAILQ_INIT(&commits);
8849 TAILQ_INIT(&merged_paths);
8850 memset(&upa, 0, sizeof(upa));
8852 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8853 switch (ch) {
8854 case 'a':
8855 abort_rebase = 1;
8856 break;
8857 case 'c':
8858 continue_rebase = 1;
8859 break;
8860 case 'l':
8861 list_backups = 1;
8862 break;
8863 case 'X':
8864 delete_backups = 1;
8865 break;
8866 default:
8867 usage_rebase();
8868 /* NOTREACHED */
8872 argc -= optind;
8873 argv += optind;
8875 #ifndef PROFILE
8876 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8877 "unveil", NULL) == -1)
8878 err(1, "pledge");
8879 #endif
8880 if (list_backups) {
8881 if (abort_rebase)
8882 option_conflict('l', 'a');
8883 if (continue_rebase)
8884 option_conflict('l', 'c');
8885 if (delete_backups)
8886 option_conflict('l', 'X');
8887 if (argc != 0 && argc != 1)
8888 usage_rebase();
8889 } else if (delete_backups) {
8890 if (abort_rebase)
8891 option_conflict('X', 'a');
8892 if (continue_rebase)
8893 option_conflict('X', 'c');
8894 if (list_backups)
8895 option_conflict('l', 'X');
8896 if (argc != 0 && argc != 1)
8897 usage_rebase();
8898 } else {
8899 if (abort_rebase && continue_rebase)
8900 usage_rebase();
8901 else if (abort_rebase || continue_rebase) {
8902 if (argc != 0)
8903 usage_rebase();
8904 } else if (argc != 1)
8905 usage_rebase();
8908 cwd = getcwd(NULL, 0);
8909 if (cwd == NULL) {
8910 error = got_error_from_errno("getcwd");
8911 goto done;
8913 error = got_worktree_open(&worktree, cwd);
8914 if (error) {
8915 if (list_backups || delete_backups) {
8916 if (error->code != GOT_ERR_NOT_WORKTREE)
8917 goto done;
8918 } else {
8919 if (error->code == GOT_ERR_NOT_WORKTREE)
8920 error = wrap_not_worktree_error(error,
8921 "rebase", cwd);
8922 goto done;
8926 error = got_repo_open(&repo,
8927 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8928 if (error != NULL)
8929 goto done;
8931 error = apply_unveil(got_repo_get_path(repo), 0,
8932 worktree ? got_worktree_get_root_path(worktree) : NULL);
8933 if (error)
8934 goto done;
8936 if (list_backups || delete_backups) {
8937 error = process_backup_refs(
8938 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8939 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8940 goto done; /* nothing else to do */
8943 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8944 worktree);
8945 if (error)
8946 goto done;
8947 if (histedit_in_progress) {
8948 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8949 goto done;
8952 error = got_worktree_merge_in_progress(&merge_in_progress,
8953 worktree, repo);
8954 if (error)
8955 goto done;
8956 if (merge_in_progress) {
8957 error = got_error(GOT_ERR_MERGE_BUSY);
8958 goto done;
8961 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8962 if (error)
8963 goto done;
8965 if (abort_rebase) {
8966 if (!rebase_in_progress) {
8967 error = got_error(GOT_ERR_NOT_REBASING);
8968 goto done;
8970 error = got_worktree_rebase_continue(&resume_commit_id,
8971 &new_base_branch, &tmp_branch, &branch, &fileindex,
8972 worktree, repo);
8973 if (error)
8974 goto done;
8975 printf("Switching work tree to %s\n",
8976 got_ref_get_symref_target(new_base_branch));
8977 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8978 new_base_branch, abort_progress, &upa);
8979 if (error)
8980 goto done;
8981 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8982 print_merge_progress_stats(&upa);
8983 goto done; /* nothing else to do */
8986 if (continue_rebase) {
8987 if (!rebase_in_progress) {
8988 error = got_error(GOT_ERR_NOT_REBASING);
8989 goto done;
8991 error = got_worktree_rebase_continue(&resume_commit_id,
8992 &new_base_branch, &tmp_branch, &branch, &fileindex,
8993 worktree, repo);
8994 if (error)
8995 goto done;
8997 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8998 resume_commit_id, repo);
8999 if (error)
9000 goto done;
9002 yca_id = got_object_id_dup(resume_commit_id);
9003 if (yca_id == NULL) {
9004 error = got_error_from_errno("got_object_id_dup");
9005 goto done;
9007 } else {
9008 error = got_ref_open(&branch, repo, argv[0], 0);
9009 if (error != NULL)
9010 goto done;
9013 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9014 if (error)
9015 goto done;
9017 if (!continue_rebase) {
9018 struct got_object_id *base_commit_id;
9020 base_commit_id = got_worktree_get_base_commit_id(worktree);
9021 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9022 base_commit_id, branch_head_commit_id, 1, repo,
9023 check_cancelled, NULL);
9024 if (error)
9025 goto done;
9026 if (yca_id == NULL) {
9027 error = got_error_msg(GOT_ERR_ANCESTRY,
9028 "specified branch shares no common ancestry "
9029 "with work tree's branch");
9030 goto done;
9033 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9034 if (error) {
9035 if (error->code != GOT_ERR_ANCESTRY)
9036 goto done;
9037 error = NULL;
9038 } else {
9039 static char msg[128];
9040 snprintf(msg, sizeof(msg),
9041 "%s is already based on %s",
9042 got_ref_get_name(branch),
9043 got_worktree_get_head_ref_name(worktree));
9044 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
9045 goto done;
9047 error = got_worktree_rebase_prepare(&new_base_branch,
9048 &tmp_branch, &fileindex, worktree, branch, repo);
9049 if (error)
9050 goto done;
9053 commit_id = branch_head_commit_id;
9054 error = got_object_open_as_commit(&commit, repo, commit_id);
9055 if (error)
9056 goto done;
9058 parent_ids = got_object_commit_get_parent_ids(commit);
9059 pid = STAILQ_FIRST(parent_ids);
9060 if (pid == NULL) {
9061 if (!continue_rebase) {
9062 error = got_worktree_rebase_abort(worktree, fileindex,
9063 repo, new_base_branch, abort_progress, &upa);
9064 if (error)
9065 goto done;
9066 printf("Rebase of %s aborted\n",
9067 got_ref_get_name(branch));
9068 print_merge_progress_stats(&upa);
9071 error = got_error(GOT_ERR_EMPTY_REBASE);
9072 goto done;
9074 error = collect_commits(&commits, commit_id, pid->id,
9075 yca_id, got_worktree_get_path_prefix(worktree),
9076 GOT_ERR_REBASE_PATH, repo);
9077 got_object_commit_close(commit);
9078 commit = NULL;
9079 if (error)
9080 goto done;
9082 if (STAILQ_EMPTY(&commits)) {
9083 if (continue_rebase) {
9084 error = rebase_complete(worktree, fileindex,
9085 branch, new_base_branch, tmp_branch, repo,
9086 create_backup);
9087 goto done;
9088 } else {
9089 /* Fast-forward the reference of the branch. */
9090 struct got_object_id *new_head_commit_id;
9091 char *id_str;
9092 error = got_ref_resolve(&new_head_commit_id, repo,
9093 new_base_branch);
9094 if (error)
9095 goto done;
9096 error = got_object_id_str(&id_str, new_head_commit_id);
9097 printf("Forwarding %s to commit %s\n",
9098 got_ref_get_name(branch), id_str);
9099 free(id_str);
9100 error = got_ref_change_ref(branch,
9101 new_head_commit_id);
9102 if (error)
9103 goto done;
9104 /* No backup needed since objects did not change. */
9105 create_backup = 0;
9109 pid = NULL;
9110 STAILQ_FOREACH(qid, &commits, entry) {
9112 commit_id = qid->id;
9113 parent_id = pid ? pid->id : yca_id;
9114 pid = qid;
9116 memset(&upa, 0, sizeof(upa));
9117 error = got_worktree_rebase_merge_files(&merged_paths,
9118 worktree, fileindex, parent_id, commit_id, repo,
9119 update_progress, &upa, check_cancelled, NULL);
9120 if (error)
9121 goto done;
9123 print_merge_progress_stats(&upa);
9124 if (upa.conflicts > 0 || upa.missing > 0 ||
9125 upa.not_deleted > 0 || upa.unversioned > 0) {
9126 if (upa.conflicts > 0) {
9127 error = show_rebase_merge_conflict(qid->id,
9128 repo);
9129 if (error)
9130 goto done;
9132 got_worktree_rebase_pathlist_free(&merged_paths);
9133 break;
9136 error = rebase_commit(&merged_paths, worktree, fileindex,
9137 tmp_branch, commit_id, repo);
9138 got_worktree_rebase_pathlist_free(&merged_paths);
9139 if (error)
9140 goto done;
9143 if (upa.conflicts > 0 || upa.missing > 0 ||
9144 upa.not_deleted > 0 || upa.unversioned > 0) {
9145 error = got_worktree_rebase_postpone(worktree, fileindex);
9146 if (error)
9147 goto done;
9148 if (upa.conflicts > 0 && upa.missing == 0 &&
9149 upa.not_deleted == 0 && upa.unversioned == 0) {
9150 error = got_error_msg(GOT_ERR_CONFLICTS,
9151 "conflicts must be resolved before rebasing "
9152 "can continue");
9153 } else if (upa.conflicts > 0) {
9154 error = got_error_msg(GOT_ERR_CONFLICTS,
9155 "conflicts must be resolved before rebasing "
9156 "can continue; changes destined for some "
9157 "files were not yet merged and should be "
9158 "merged manually if required before the "
9159 "rebase operation is continued");
9160 } else {
9161 error = got_error_msg(GOT_ERR_CONFLICTS,
9162 "changes destined for some files were not "
9163 "yet merged and should be merged manually "
9164 "if required before the rebase operation "
9165 "is continued");
9167 } else
9168 error = rebase_complete(worktree, fileindex, branch,
9169 new_base_branch, tmp_branch, repo, create_backup);
9170 done:
9171 got_object_id_queue_free(&commits);
9172 free(branch_head_commit_id);
9173 free(resume_commit_id);
9174 free(yca_id);
9175 if (commit)
9176 got_object_commit_close(commit);
9177 if (branch)
9178 got_ref_close(branch);
9179 if (new_base_branch)
9180 got_ref_close(new_base_branch);
9181 if (tmp_branch)
9182 got_ref_close(tmp_branch);
9183 if (worktree)
9184 got_worktree_close(worktree);
9185 if (repo) {
9186 const struct got_error *close_err = got_repo_close(repo);
9187 if (error == NULL)
9188 error = close_err;
9190 return error;
9193 __dead static void
9194 usage_histedit(void)
9196 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9197 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9198 getprogname());
9199 exit(1);
9202 #define GOT_HISTEDIT_PICK 'p'
9203 #define GOT_HISTEDIT_EDIT 'e'
9204 #define GOT_HISTEDIT_FOLD 'f'
9205 #define GOT_HISTEDIT_DROP 'd'
9206 #define GOT_HISTEDIT_MESG 'm'
9208 static struct got_histedit_cmd {
9209 unsigned char code;
9210 const char *name;
9211 const char *desc;
9212 } got_histedit_cmds[] = {
9213 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9214 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9215 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9216 "be used" },
9217 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9218 { GOT_HISTEDIT_MESG, "mesg",
9219 "single-line log message for commit above (open editor if empty)" },
9222 struct got_histedit_list_entry {
9223 TAILQ_ENTRY(got_histedit_list_entry) entry;
9224 struct got_object_id *commit_id;
9225 const struct got_histedit_cmd *cmd;
9226 char *logmsg;
9228 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9230 static const struct got_error *
9231 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9232 FILE *f, struct got_repository *repo)
9234 const struct got_error *err = NULL;
9235 char *logmsg = NULL, *id_str = NULL;
9236 struct got_commit_object *commit = NULL;
9237 int n;
9239 err = got_object_open_as_commit(&commit, repo, commit_id);
9240 if (err)
9241 goto done;
9243 err = get_short_logmsg(&logmsg, 34, commit);
9244 if (err)
9245 goto done;
9247 err = got_object_id_str(&id_str, commit_id);
9248 if (err)
9249 goto done;
9251 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9252 if (n < 0)
9253 err = got_ferror(f, GOT_ERR_IO);
9254 done:
9255 if (commit)
9256 got_object_commit_close(commit);
9257 free(id_str);
9258 free(logmsg);
9259 return err;
9262 static const struct got_error *
9263 histedit_write_commit_list(struct got_object_id_queue *commits,
9264 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9265 struct got_repository *repo)
9267 const struct got_error *err = NULL;
9268 struct got_object_qid *qid;
9269 const char *histedit_cmd = NULL;
9271 if (STAILQ_EMPTY(commits))
9272 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9274 STAILQ_FOREACH(qid, commits, entry) {
9275 histedit_cmd = got_histedit_cmds[0].name;
9276 if (edit_only)
9277 histedit_cmd = "edit";
9278 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9279 histedit_cmd = "fold";
9280 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9281 if (err)
9282 break;
9283 if (edit_logmsg_only) {
9284 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9285 if (n < 0) {
9286 err = got_ferror(f, GOT_ERR_IO);
9287 break;
9292 return err;
9295 static const struct got_error *
9296 write_cmd_list(FILE *f, const char *branch_name,
9297 struct got_object_id_queue *commits)
9299 const struct got_error *err = NULL;
9300 size_t i;
9301 int n;
9302 char *id_str;
9303 struct got_object_qid *qid;
9305 qid = STAILQ_FIRST(commits);
9306 err = got_object_id_str(&id_str, qid->id);
9307 if (err)
9308 return err;
9310 n = fprintf(f,
9311 "# Editing the history of branch '%s' starting at\n"
9312 "# commit %s\n"
9313 "# Commits will be processed in order from top to "
9314 "bottom of this file.\n", branch_name, id_str);
9315 if (n < 0) {
9316 err = got_ferror(f, GOT_ERR_IO);
9317 goto done;
9320 n = fprintf(f, "# Available histedit commands:\n");
9321 if (n < 0) {
9322 err = got_ferror(f, GOT_ERR_IO);
9323 goto done;
9326 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9327 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9328 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9329 cmd->desc);
9330 if (n < 0) {
9331 err = got_ferror(f, GOT_ERR_IO);
9332 break;
9335 done:
9336 free(id_str);
9337 return err;
9340 static const struct got_error *
9341 histedit_syntax_error(int lineno)
9343 static char msg[42];
9344 int ret;
9346 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9347 lineno);
9348 if (ret == -1 || ret >= sizeof(msg))
9349 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9351 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9354 static const struct got_error *
9355 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9356 char *logmsg, struct got_repository *repo)
9358 const struct got_error *err;
9359 struct got_commit_object *folded_commit = NULL;
9360 char *id_str, *folded_logmsg = NULL;
9362 err = got_object_id_str(&id_str, hle->commit_id);
9363 if (err)
9364 return err;
9366 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9367 if (err)
9368 goto done;
9370 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9371 if (err)
9372 goto done;
9373 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9374 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9375 folded_logmsg) == -1) {
9376 err = got_error_from_errno("asprintf");
9378 done:
9379 if (folded_commit)
9380 got_object_commit_close(folded_commit);
9381 free(id_str);
9382 free(folded_logmsg);
9383 return err;
9386 static struct got_histedit_list_entry *
9387 get_folded_commits(struct got_histedit_list_entry *hle)
9389 struct got_histedit_list_entry *prev, *folded = NULL;
9391 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9392 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9393 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9394 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9395 folded = prev;
9396 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9399 return folded;
9402 static const struct got_error *
9403 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9404 struct got_repository *repo)
9406 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9407 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9408 const struct got_error *err = NULL;
9409 struct got_commit_object *commit = NULL;
9410 int logmsg_len;
9411 int fd;
9412 struct got_histedit_list_entry *folded = NULL;
9414 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9415 if (err)
9416 return err;
9418 folded = get_folded_commits(hle);
9419 if (folded) {
9420 while (folded != hle) {
9421 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9422 folded = TAILQ_NEXT(folded, entry);
9423 continue;
9425 err = append_folded_commit_msg(&new_msg, folded,
9426 logmsg, repo);
9427 if (err)
9428 goto done;
9429 free(logmsg);
9430 logmsg = new_msg;
9431 folded = TAILQ_NEXT(folded, entry);
9435 err = got_object_id_str(&id_str, hle->commit_id);
9436 if (err)
9437 goto done;
9438 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9439 if (err)
9440 goto done;
9441 logmsg_len = asprintf(&new_msg,
9442 "%s\n# original log message of commit %s: %s",
9443 logmsg ? logmsg : "", id_str, orig_logmsg);
9444 if (logmsg_len == -1) {
9445 err = got_error_from_errno("asprintf");
9446 goto done;
9448 free(logmsg);
9449 logmsg = new_msg;
9451 err = got_object_id_str(&id_str, hle->commit_id);
9452 if (err)
9453 goto done;
9455 err = got_opentemp_named_fd(&logmsg_path, &fd,
9456 GOT_TMPDIR_STR "/got-logmsg");
9457 if (err)
9458 goto done;
9460 write(fd, logmsg, logmsg_len);
9461 close(fd);
9463 err = get_editor(&editor);
9464 if (err)
9465 goto done;
9467 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9468 logmsg_len, 0);
9469 if (err) {
9470 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9471 goto done;
9472 err = NULL;
9473 hle->logmsg = strdup(new_msg);
9474 if (hle->logmsg == NULL)
9475 err = got_error_from_errno("strdup");
9477 done:
9478 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9479 err = got_error_from_errno2("unlink", logmsg_path);
9480 free(logmsg_path);
9481 free(logmsg);
9482 free(orig_logmsg);
9483 free(editor);
9484 if (commit)
9485 got_object_commit_close(commit);
9486 return err;
9489 static const struct got_error *
9490 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9491 FILE *f, struct got_repository *repo)
9493 const struct got_error *err = NULL;
9494 char *line = NULL, *p, *end;
9495 size_t i, size;
9496 ssize_t len;
9497 int lineno = 0;
9498 const struct got_histedit_cmd *cmd;
9499 struct got_object_id *commit_id = NULL;
9500 struct got_histedit_list_entry *hle = NULL;
9502 for (;;) {
9503 len = getline(&line, &size, f);
9504 if (len == -1) {
9505 const struct got_error *getline_err;
9506 if (feof(f))
9507 break;
9508 getline_err = got_error_from_errno("getline");
9509 err = got_ferror(f, getline_err->code);
9510 break;
9512 lineno++;
9513 p = line;
9514 while (isspace((unsigned char)p[0]))
9515 p++;
9516 if (p[0] == '#' || p[0] == '\0') {
9517 free(line);
9518 line = NULL;
9519 continue;
9521 cmd = NULL;
9522 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9523 cmd = &got_histedit_cmds[i];
9524 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9525 isspace((unsigned char)p[strlen(cmd->name)])) {
9526 p += strlen(cmd->name);
9527 break;
9529 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9530 p++;
9531 break;
9534 if (i == nitems(got_histedit_cmds)) {
9535 err = histedit_syntax_error(lineno);
9536 break;
9538 while (isspace((unsigned char)p[0]))
9539 p++;
9540 if (cmd->code == GOT_HISTEDIT_MESG) {
9541 if (hle == NULL || hle->logmsg != NULL) {
9542 err = got_error(GOT_ERR_HISTEDIT_CMD);
9543 break;
9545 if (p[0] == '\0') {
9546 err = histedit_edit_logmsg(hle, repo);
9547 if (err)
9548 break;
9549 } else {
9550 hle->logmsg = strdup(p);
9551 if (hle->logmsg == NULL) {
9552 err = got_error_from_errno("strdup");
9553 break;
9556 free(line);
9557 line = NULL;
9558 continue;
9559 } else {
9560 end = p;
9561 while (end[0] && !isspace((unsigned char)end[0]))
9562 end++;
9563 *end = '\0';
9565 err = got_object_resolve_id_str(&commit_id, repo, p);
9566 if (err) {
9567 /* override error code */
9568 err = histedit_syntax_error(lineno);
9569 break;
9572 hle = malloc(sizeof(*hle));
9573 if (hle == NULL) {
9574 err = got_error_from_errno("malloc");
9575 break;
9577 hle->cmd = cmd;
9578 hle->commit_id = commit_id;
9579 hle->logmsg = NULL;
9580 commit_id = NULL;
9581 free(line);
9582 line = NULL;
9583 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9586 free(line);
9587 free(commit_id);
9588 return err;
9591 static const struct got_error *
9592 histedit_check_script(struct got_histedit_list *histedit_cmds,
9593 struct got_object_id_queue *commits, struct got_repository *repo)
9595 const struct got_error *err = NULL;
9596 struct got_object_qid *qid;
9597 struct got_histedit_list_entry *hle;
9598 static char msg[92];
9599 char *id_str;
9601 if (TAILQ_EMPTY(histedit_cmds))
9602 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9603 "histedit script contains no commands");
9604 if (STAILQ_EMPTY(commits))
9605 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9607 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9608 struct got_histedit_list_entry *hle2;
9609 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9610 if (hle == hle2)
9611 continue;
9612 if (got_object_id_cmp(hle->commit_id,
9613 hle2->commit_id) != 0)
9614 continue;
9615 err = got_object_id_str(&id_str, hle->commit_id);
9616 if (err)
9617 return err;
9618 snprintf(msg, sizeof(msg), "commit %s is listed "
9619 "more than once in histedit script", id_str);
9620 free(id_str);
9621 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9625 STAILQ_FOREACH(qid, commits, entry) {
9626 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9627 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9628 break;
9630 if (hle == NULL) {
9631 err = got_object_id_str(&id_str, qid->id);
9632 if (err)
9633 return err;
9634 snprintf(msg, sizeof(msg),
9635 "commit %s missing from histedit script", id_str);
9636 free(id_str);
9637 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9641 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9642 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9643 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9644 "last commit in histedit script cannot be folded");
9646 return NULL;
9649 static const struct got_error *
9650 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9651 const char *path, struct got_object_id_queue *commits,
9652 struct got_repository *repo)
9654 const struct got_error *err = NULL;
9655 char *editor;
9656 FILE *f = NULL;
9658 err = get_editor(&editor);
9659 if (err)
9660 return err;
9662 if (spawn_editor(editor, path) == -1) {
9663 err = got_error_from_errno("failed spawning editor");
9664 goto done;
9667 f = fopen(path, "r");
9668 if (f == NULL) {
9669 err = got_error_from_errno("fopen");
9670 goto done;
9672 err = histedit_parse_list(histedit_cmds, f, repo);
9673 if (err)
9674 goto done;
9676 err = histedit_check_script(histedit_cmds, commits, repo);
9677 done:
9678 if (f && fclose(f) == EOF && err == NULL)
9679 err = got_error_from_errno("fclose");
9680 free(editor);
9681 return err;
9684 static const struct got_error *
9685 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9686 struct got_object_id_queue *, const char *, const char *,
9687 struct got_repository *);
9689 static const struct got_error *
9690 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9691 struct got_object_id_queue *commits, const char *branch_name,
9692 int edit_logmsg_only, int fold_only, int edit_only,
9693 struct got_repository *repo)
9695 const struct got_error *err;
9696 FILE *f = NULL;
9697 char *path = NULL;
9699 err = got_opentemp_named(&path, &f, "got-histedit");
9700 if (err)
9701 return err;
9703 err = write_cmd_list(f, branch_name, commits);
9704 if (err)
9705 goto done;
9707 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9708 fold_only, edit_only, repo);
9709 if (err)
9710 goto done;
9712 if (edit_logmsg_only || fold_only || edit_only) {
9713 rewind(f);
9714 err = histedit_parse_list(histedit_cmds, f, repo);
9715 } else {
9716 if (fclose(f) == EOF) {
9717 err = got_error_from_errno("fclose");
9718 goto done;
9720 f = NULL;
9721 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9722 if (err) {
9723 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9724 err->code != GOT_ERR_HISTEDIT_CMD)
9725 goto done;
9726 err = histedit_edit_list_retry(histedit_cmds, err,
9727 commits, path, branch_name, repo);
9730 done:
9731 if (f && fclose(f) == EOF && err == NULL)
9732 err = got_error_from_errno("fclose");
9733 if (path && unlink(path) != 0 && err == NULL)
9734 err = got_error_from_errno2("unlink", path);
9735 free(path);
9736 return err;
9739 static const struct got_error *
9740 histedit_save_list(struct got_histedit_list *histedit_cmds,
9741 struct got_worktree *worktree, struct got_repository *repo)
9743 const struct got_error *err = NULL;
9744 char *path = NULL;
9745 FILE *f = NULL;
9746 struct got_histedit_list_entry *hle;
9747 struct got_commit_object *commit = NULL;
9749 err = got_worktree_get_histedit_script_path(&path, worktree);
9750 if (err)
9751 return err;
9753 f = fopen(path, "w");
9754 if (f == NULL) {
9755 err = got_error_from_errno2("fopen", path);
9756 goto done;
9758 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9759 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9760 repo);
9761 if (err)
9762 break;
9764 if (hle->logmsg) {
9765 int n = fprintf(f, "%c %s\n",
9766 GOT_HISTEDIT_MESG, hle->logmsg);
9767 if (n < 0) {
9768 err = got_ferror(f, GOT_ERR_IO);
9769 break;
9773 done:
9774 if (f && fclose(f) == EOF && err == NULL)
9775 err = got_error_from_errno("fclose");
9776 free(path);
9777 if (commit)
9778 got_object_commit_close(commit);
9779 return err;
9782 void
9783 histedit_free_list(struct got_histedit_list *histedit_cmds)
9785 struct got_histedit_list_entry *hle;
9787 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9788 TAILQ_REMOVE(histedit_cmds, hle, entry);
9789 free(hle);
9793 static const struct got_error *
9794 histedit_load_list(struct got_histedit_list *histedit_cmds,
9795 const char *path, struct got_repository *repo)
9797 const struct got_error *err = NULL;
9798 FILE *f = NULL;
9800 f = fopen(path, "r");
9801 if (f == NULL) {
9802 err = got_error_from_errno2("fopen", path);
9803 goto done;
9806 err = histedit_parse_list(histedit_cmds, f, repo);
9807 done:
9808 if (f && fclose(f) == EOF && err == NULL)
9809 err = got_error_from_errno("fclose");
9810 return err;
9813 static const struct got_error *
9814 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9815 const struct got_error *edit_err, struct got_object_id_queue *commits,
9816 const char *path, const char *branch_name, struct got_repository *repo)
9818 const struct got_error *err = NULL, *prev_err = edit_err;
9819 int resp = ' ';
9821 while (resp != 'c' && resp != 'r' && resp != 'a') {
9822 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9823 "or (a)bort: ", getprogname(), prev_err->msg);
9824 resp = getchar();
9825 if (resp == '\n')
9826 resp = getchar();
9827 if (resp == 'c') {
9828 histedit_free_list(histedit_cmds);
9829 err = histedit_run_editor(histedit_cmds, path, commits,
9830 repo);
9831 if (err) {
9832 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9833 err->code != GOT_ERR_HISTEDIT_CMD)
9834 break;
9835 prev_err = err;
9836 resp = ' ';
9837 continue;
9839 break;
9840 } else if (resp == 'r') {
9841 histedit_free_list(histedit_cmds);
9842 err = histedit_edit_script(histedit_cmds,
9843 commits, branch_name, 0, 0, 0, repo);
9844 if (err) {
9845 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9846 err->code != GOT_ERR_HISTEDIT_CMD)
9847 break;
9848 prev_err = err;
9849 resp = ' ';
9850 continue;
9852 break;
9853 } else if (resp == 'a') {
9854 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9855 break;
9856 } else
9857 printf("invalid response '%c'\n", resp);
9860 return err;
9863 static const struct got_error *
9864 histedit_complete(struct got_worktree *worktree,
9865 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9866 struct got_reference *branch, struct got_repository *repo)
9868 printf("Switching work tree to %s\n",
9869 got_ref_get_symref_target(branch));
9870 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9871 branch, repo);
9874 static const struct got_error *
9875 show_histedit_progress(struct got_commit_object *commit,
9876 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9878 const struct got_error *err;
9879 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9881 err = got_object_id_str(&old_id_str, hle->commit_id);
9882 if (err)
9883 goto done;
9885 if (new_id) {
9886 err = got_object_id_str(&new_id_str, new_id);
9887 if (err)
9888 goto done;
9891 old_id_str[12] = '\0';
9892 if (new_id_str)
9893 new_id_str[12] = '\0';
9895 if (hle->logmsg) {
9896 logmsg = strdup(hle->logmsg);
9897 if (logmsg == NULL) {
9898 err = got_error_from_errno("strdup");
9899 goto done;
9901 trim_logmsg(logmsg, 42);
9902 } else {
9903 err = get_short_logmsg(&logmsg, 42, commit);
9904 if (err)
9905 goto done;
9908 switch (hle->cmd->code) {
9909 case GOT_HISTEDIT_PICK:
9910 case GOT_HISTEDIT_EDIT:
9911 printf("%s -> %s: %s\n", old_id_str,
9912 new_id_str ? new_id_str : "no-op change", logmsg);
9913 break;
9914 case GOT_HISTEDIT_DROP:
9915 case GOT_HISTEDIT_FOLD:
9916 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9917 logmsg);
9918 break;
9919 default:
9920 break;
9922 done:
9923 free(old_id_str);
9924 free(new_id_str);
9925 return err;
9928 static const struct got_error *
9929 histedit_commit(struct got_pathlist_head *merged_paths,
9930 struct got_worktree *worktree, struct got_fileindex *fileindex,
9931 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9932 struct got_repository *repo)
9934 const struct got_error *err;
9935 struct got_commit_object *commit;
9936 struct got_object_id *new_commit_id;
9938 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9939 && hle->logmsg == NULL) {
9940 err = histedit_edit_logmsg(hle, repo);
9941 if (err)
9942 return err;
9945 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9946 if (err)
9947 return err;
9949 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9950 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9951 hle->logmsg, repo);
9952 if (err) {
9953 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9954 goto done;
9955 err = show_histedit_progress(commit, hle, NULL);
9956 } else {
9957 err = show_histedit_progress(commit, hle, new_commit_id);
9958 free(new_commit_id);
9960 done:
9961 got_object_commit_close(commit);
9962 return err;
9965 static const struct got_error *
9966 histedit_skip_commit(struct got_histedit_list_entry *hle,
9967 struct got_worktree *worktree, struct got_repository *repo)
9969 const struct got_error *error;
9970 struct got_commit_object *commit;
9972 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9973 repo);
9974 if (error)
9975 return error;
9977 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9978 if (error)
9979 return error;
9981 error = show_histedit_progress(commit, hle, NULL);
9982 got_object_commit_close(commit);
9983 return error;
9986 static const struct got_error *
9987 check_local_changes(void *arg, unsigned char status,
9988 unsigned char staged_status, const char *path,
9989 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9990 struct got_object_id *commit_id, int dirfd, const char *de_name)
9992 int *have_local_changes = arg;
9994 switch (status) {
9995 case GOT_STATUS_ADD:
9996 case GOT_STATUS_DELETE:
9997 case GOT_STATUS_MODIFY:
9998 case GOT_STATUS_CONFLICT:
9999 *have_local_changes = 1;
10000 return got_error(GOT_ERR_CANCELLED);
10001 default:
10002 break;
10005 switch (staged_status) {
10006 case GOT_STATUS_ADD:
10007 case GOT_STATUS_DELETE:
10008 case GOT_STATUS_MODIFY:
10009 *have_local_changes = 1;
10010 return got_error(GOT_ERR_CANCELLED);
10011 default:
10012 break;
10015 return NULL;
10018 static const struct got_error *
10019 cmd_histedit(int argc, char *argv[])
10021 const struct got_error *error = NULL;
10022 struct got_worktree *worktree = NULL;
10023 struct got_fileindex *fileindex = NULL;
10024 struct got_repository *repo = NULL;
10025 char *cwd = NULL;
10026 struct got_reference *branch = NULL;
10027 struct got_reference *tmp_branch = NULL;
10028 struct got_object_id *resume_commit_id = NULL;
10029 struct got_object_id *base_commit_id = NULL;
10030 struct got_object_id *head_commit_id = NULL;
10031 struct got_commit_object *commit = NULL;
10032 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10033 struct got_update_progress_arg upa;
10034 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10035 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10036 int list_backups = 0, delete_backups = 0;
10037 const char *edit_script_path = NULL;
10038 struct got_object_id_queue commits;
10039 struct got_pathlist_head merged_paths;
10040 const struct got_object_id_queue *parent_ids;
10041 struct got_object_qid *pid;
10042 struct got_histedit_list histedit_cmds;
10043 struct got_histedit_list_entry *hle;
10045 STAILQ_INIT(&commits);
10046 TAILQ_INIT(&histedit_cmds);
10047 TAILQ_INIT(&merged_paths);
10048 memset(&upa, 0, sizeof(upa));
10050 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10051 switch (ch) {
10052 case 'a':
10053 abort_edit = 1;
10054 break;
10055 case 'c':
10056 continue_edit = 1;
10057 break;
10058 case 'e':
10059 edit_only = 1;
10060 break;
10061 case 'f':
10062 fold_only = 1;
10063 break;
10064 case 'F':
10065 edit_script_path = optarg;
10066 break;
10067 case 'm':
10068 edit_logmsg_only = 1;
10069 break;
10070 case 'l':
10071 list_backups = 1;
10072 break;
10073 case 'X':
10074 delete_backups = 1;
10075 break;
10076 default:
10077 usage_histedit();
10078 /* NOTREACHED */
10082 argc -= optind;
10083 argv += optind;
10085 #ifndef PROFILE
10086 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10087 "unveil", NULL) == -1)
10088 err(1, "pledge");
10089 #endif
10090 if (abort_edit && continue_edit)
10091 option_conflict('a', 'c');
10092 if (edit_script_path && edit_logmsg_only)
10093 option_conflict('F', 'm');
10094 if (abort_edit && edit_logmsg_only)
10095 option_conflict('a', 'm');
10096 if (continue_edit && edit_logmsg_only)
10097 option_conflict('c', 'm');
10098 if (abort_edit && fold_only)
10099 option_conflict('a', 'f');
10100 if (continue_edit && fold_only)
10101 option_conflict('c', 'f');
10102 if (fold_only && edit_logmsg_only)
10103 option_conflict('f', 'm');
10104 if (edit_script_path && fold_only)
10105 option_conflict('F', 'f');
10106 if (abort_edit && edit_only)
10107 option_conflict('a', 'e');
10108 if (continue_edit && edit_only)
10109 option_conflict('c', 'e');
10110 if (edit_only && edit_logmsg_only)
10111 option_conflict('e', 'm');
10112 if (edit_script_path && edit_only)
10113 option_conflict('F', 'e');
10114 if (list_backups) {
10115 if (abort_edit)
10116 option_conflict('l', 'a');
10117 if (continue_edit)
10118 option_conflict('l', 'c');
10119 if (edit_script_path)
10120 option_conflict('l', 'F');
10121 if (edit_logmsg_only)
10122 option_conflict('l', 'm');
10123 if (fold_only)
10124 option_conflict('l', 'f');
10125 if (edit_only)
10126 option_conflict('l', 'e');
10127 if (delete_backups)
10128 option_conflict('l', 'X');
10129 if (argc != 0 && argc != 1)
10130 usage_histedit();
10131 } else if (delete_backups) {
10132 if (abort_edit)
10133 option_conflict('X', 'a');
10134 if (continue_edit)
10135 option_conflict('X', 'c');
10136 if (edit_script_path)
10137 option_conflict('X', 'F');
10138 if (edit_logmsg_only)
10139 option_conflict('X', 'm');
10140 if (fold_only)
10141 option_conflict('X', 'f');
10142 if (edit_only)
10143 option_conflict('X', 'e');
10144 if (list_backups)
10145 option_conflict('X', 'l');
10146 if (argc != 0 && argc != 1)
10147 usage_histedit();
10148 } else if (argc != 0)
10149 usage_histedit();
10152 * This command cannot apply unveil(2) in all cases because the
10153 * user may choose to run an editor to edit the histedit script
10154 * and to edit individual commit log messages.
10155 * unveil(2) traverses exec(2); if an editor is used we have to
10156 * apply unveil after edit script and log messages have been written.
10157 * XXX TODO: Make use of unveil(2) where possible.
10160 cwd = getcwd(NULL, 0);
10161 if (cwd == NULL) {
10162 error = got_error_from_errno("getcwd");
10163 goto done;
10165 error = got_worktree_open(&worktree, cwd);
10166 if (error) {
10167 if (list_backups || delete_backups) {
10168 if (error->code != GOT_ERR_NOT_WORKTREE)
10169 goto done;
10170 } else {
10171 if (error->code == GOT_ERR_NOT_WORKTREE)
10172 error = wrap_not_worktree_error(error,
10173 "histedit", cwd);
10174 goto done;
10178 if (list_backups || delete_backups) {
10179 error = got_repo_open(&repo,
10180 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10181 NULL);
10182 if (error != NULL)
10183 goto done;
10184 error = apply_unveil(got_repo_get_path(repo), 0,
10185 worktree ? got_worktree_get_root_path(worktree) : NULL);
10186 if (error)
10187 goto done;
10188 error = process_backup_refs(
10189 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10190 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10191 goto done; /* nothing else to do */
10194 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10195 NULL);
10196 if (error != NULL)
10197 goto done;
10199 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10200 if (error)
10201 goto done;
10202 if (rebase_in_progress) {
10203 error = got_error(GOT_ERR_REBASING);
10204 goto done;
10207 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10208 repo);
10209 if (error)
10210 goto done;
10211 if (merge_in_progress) {
10212 error = got_error(GOT_ERR_MERGE_BUSY);
10213 goto done;
10216 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10217 if (error)
10218 goto done;
10220 if (edit_in_progress && edit_logmsg_only) {
10221 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10222 "histedit operation is in progress in this "
10223 "work tree and must be continued or aborted "
10224 "before the -m option can be used");
10225 goto done;
10227 if (edit_in_progress && fold_only) {
10228 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10229 "histedit operation is in progress in this "
10230 "work tree and must be continued or aborted "
10231 "before the -f option can be used");
10232 goto done;
10234 if (edit_in_progress && edit_only) {
10235 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10236 "histedit operation is in progress in this "
10237 "work tree and must be continued or aborted "
10238 "before the -e option can be used");
10239 goto done;
10242 if (edit_in_progress && abort_edit) {
10243 error = got_worktree_histedit_continue(&resume_commit_id,
10244 &tmp_branch, &branch, &base_commit_id, &fileindex,
10245 worktree, repo);
10246 if (error)
10247 goto done;
10248 printf("Switching work tree to %s\n",
10249 got_ref_get_symref_target(branch));
10250 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10251 branch, base_commit_id, abort_progress, &upa);
10252 if (error)
10253 goto done;
10254 printf("Histedit of %s aborted\n",
10255 got_ref_get_symref_target(branch));
10256 print_merge_progress_stats(&upa);
10257 goto done; /* nothing else to do */
10258 } else if (abort_edit) {
10259 error = got_error(GOT_ERR_NOT_HISTEDIT);
10260 goto done;
10263 if (continue_edit) {
10264 char *path;
10266 if (!edit_in_progress) {
10267 error = got_error(GOT_ERR_NOT_HISTEDIT);
10268 goto done;
10271 error = got_worktree_get_histedit_script_path(&path, worktree);
10272 if (error)
10273 goto done;
10275 error = histedit_load_list(&histedit_cmds, path, repo);
10276 free(path);
10277 if (error)
10278 goto done;
10280 error = got_worktree_histedit_continue(&resume_commit_id,
10281 &tmp_branch, &branch, &base_commit_id, &fileindex,
10282 worktree, repo);
10283 if (error)
10284 goto done;
10286 error = got_ref_resolve(&head_commit_id, repo, branch);
10287 if (error)
10288 goto done;
10290 error = got_object_open_as_commit(&commit, repo,
10291 head_commit_id);
10292 if (error)
10293 goto done;
10294 parent_ids = got_object_commit_get_parent_ids(commit);
10295 pid = STAILQ_FIRST(parent_ids);
10296 if (pid == NULL) {
10297 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10298 goto done;
10300 error = collect_commits(&commits, head_commit_id, pid->id,
10301 base_commit_id, got_worktree_get_path_prefix(worktree),
10302 GOT_ERR_HISTEDIT_PATH, repo);
10303 got_object_commit_close(commit);
10304 commit = NULL;
10305 if (error)
10306 goto done;
10307 } else {
10308 if (edit_in_progress) {
10309 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10310 goto done;
10313 error = got_ref_open(&branch, repo,
10314 got_worktree_get_head_ref_name(worktree), 0);
10315 if (error != NULL)
10316 goto done;
10318 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10319 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10320 "will not edit commit history of a branch outside "
10321 "the \"refs/heads/\" reference namespace");
10322 goto done;
10325 error = got_ref_resolve(&head_commit_id, repo, branch);
10326 got_ref_close(branch);
10327 branch = NULL;
10328 if (error)
10329 goto done;
10331 error = got_object_open_as_commit(&commit, repo,
10332 head_commit_id);
10333 if (error)
10334 goto done;
10335 parent_ids = got_object_commit_get_parent_ids(commit);
10336 pid = STAILQ_FIRST(parent_ids);
10337 if (pid == NULL) {
10338 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10339 goto done;
10341 error = collect_commits(&commits, head_commit_id, pid->id,
10342 got_worktree_get_base_commit_id(worktree),
10343 got_worktree_get_path_prefix(worktree),
10344 GOT_ERR_HISTEDIT_PATH, repo);
10345 got_object_commit_close(commit);
10346 commit = NULL;
10347 if (error)
10348 goto done;
10350 if (STAILQ_EMPTY(&commits)) {
10351 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10352 goto done;
10355 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10356 &base_commit_id, &fileindex, worktree, repo);
10357 if (error)
10358 goto done;
10360 if (edit_script_path) {
10361 error = histedit_load_list(&histedit_cmds,
10362 edit_script_path, repo);
10363 if (error) {
10364 got_worktree_histedit_abort(worktree, fileindex,
10365 repo, branch, base_commit_id,
10366 abort_progress, &upa);
10367 print_merge_progress_stats(&upa);
10368 goto done;
10370 } else {
10371 const char *branch_name;
10372 branch_name = got_ref_get_symref_target(branch);
10373 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10374 branch_name += 11;
10375 error = histedit_edit_script(&histedit_cmds, &commits,
10376 branch_name, edit_logmsg_only, fold_only,
10377 edit_only, repo);
10378 if (error) {
10379 got_worktree_histedit_abort(worktree, fileindex,
10380 repo, branch, base_commit_id,
10381 abort_progress, &upa);
10382 print_merge_progress_stats(&upa);
10383 goto done;
10388 error = histedit_save_list(&histedit_cmds, worktree,
10389 repo);
10390 if (error) {
10391 got_worktree_histedit_abort(worktree, fileindex,
10392 repo, branch, base_commit_id,
10393 abort_progress, &upa);
10394 print_merge_progress_stats(&upa);
10395 goto done;
10400 error = histedit_check_script(&histedit_cmds, &commits, repo);
10401 if (error)
10402 goto done;
10404 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10405 if (resume_commit_id) {
10406 if (got_object_id_cmp(hle->commit_id,
10407 resume_commit_id) != 0)
10408 continue;
10410 resume_commit_id = NULL;
10411 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10412 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10413 error = histedit_skip_commit(hle, worktree,
10414 repo);
10415 if (error)
10416 goto done;
10417 } else {
10418 struct got_pathlist_head paths;
10419 int have_changes = 0;
10421 TAILQ_INIT(&paths);
10422 error = got_pathlist_append(&paths, "", NULL);
10423 if (error)
10424 goto done;
10425 error = got_worktree_status(worktree, &paths,
10426 repo, 0, check_local_changes, &have_changes,
10427 check_cancelled, NULL);
10428 got_pathlist_free(&paths);
10429 if (error) {
10430 if (error->code != GOT_ERR_CANCELLED)
10431 goto done;
10432 if (sigint_received || sigpipe_received)
10433 goto done;
10435 if (have_changes) {
10436 error = histedit_commit(NULL, worktree,
10437 fileindex, tmp_branch, hle, repo);
10438 if (error)
10439 goto done;
10440 } else {
10441 error = got_object_open_as_commit(
10442 &commit, repo, hle->commit_id);
10443 if (error)
10444 goto done;
10445 error = show_histedit_progress(commit,
10446 hle, NULL);
10447 got_object_commit_close(commit);
10448 commit = NULL;
10449 if (error)
10450 goto done;
10453 continue;
10456 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10457 error = histedit_skip_commit(hle, worktree, repo);
10458 if (error)
10459 goto done;
10460 continue;
10463 error = got_object_open_as_commit(&commit, repo,
10464 hle->commit_id);
10465 if (error)
10466 goto done;
10467 parent_ids = got_object_commit_get_parent_ids(commit);
10468 pid = STAILQ_FIRST(parent_ids);
10470 error = got_worktree_histedit_merge_files(&merged_paths,
10471 worktree, fileindex, pid->id, hle->commit_id, repo,
10472 update_progress, &upa, check_cancelled, NULL);
10473 if (error)
10474 goto done;
10475 got_object_commit_close(commit);
10476 commit = NULL;
10478 print_merge_progress_stats(&upa);
10479 if (upa.conflicts > 0 || upa.missing > 0 ||
10480 upa.not_deleted > 0 || upa.unversioned > 0) {
10481 if (upa.conflicts > 0) {
10482 error = show_rebase_merge_conflict(
10483 hle->commit_id, repo);
10484 if (error)
10485 goto done;
10487 got_worktree_rebase_pathlist_free(&merged_paths);
10488 break;
10491 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10492 char *id_str;
10493 error = got_object_id_str(&id_str, hle->commit_id);
10494 if (error)
10495 goto done;
10496 printf("Stopping histedit for amending commit %s\n",
10497 id_str);
10498 free(id_str);
10499 got_worktree_rebase_pathlist_free(&merged_paths);
10500 error = got_worktree_histedit_postpone(worktree,
10501 fileindex);
10502 goto done;
10505 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10506 error = histedit_skip_commit(hle, worktree, repo);
10507 if (error)
10508 goto done;
10509 continue;
10512 error = histedit_commit(&merged_paths, worktree, fileindex,
10513 tmp_branch, hle, repo);
10514 got_worktree_rebase_pathlist_free(&merged_paths);
10515 if (error)
10516 goto done;
10519 if (upa.conflicts > 0 || upa.missing > 0 ||
10520 upa.not_deleted > 0 || upa.unversioned > 0) {
10521 error = got_worktree_histedit_postpone(worktree, fileindex);
10522 if (error)
10523 goto done;
10524 if (upa.conflicts > 0 && upa.missing == 0 &&
10525 upa.not_deleted == 0 && upa.unversioned == 0) {
10526 error = got_error_msg(GOT_ERR_CONFLICTS,
10527 "conflicts must be resolved before histedit "
10528 "can continue");
10529 } else if (upa.conflicts > 0) {
10530 error = got_error_msg(GOT_ERR_CONFLICTS,
10531 "conflicts must be resolved before histedit "
10532 "can continue; changes destined for some "
10533 "files were not yet merged and should be "
10534 "merged manually if required before the "
10535 "histedit operation is continued");
10536 } else {
10537 error = got_error_msg(GOT_ERR_CONFLICTS,
10538 "changes destined for some files were not "
10539 "yet merged and should be merged manually "
10540 "if required before the histedit operation "
10541 "is continued");
10543 } else
10544 error = histedit_complete(worktree, fileindex, tmp_branch,
10545 branch, repo);
10546 done:
10547 got_object_id_queue_free(&commits);
10548 histedit_free_list(&histedit_cmds);
10549 free(head_commit_id);
10550 free(base_commit_id);
10551 free(resume_commit_id);
10552 if (commit)
10553 got_object_commit_close(commit);
10554 if (branch)
10555 got_ref_close(branch);
10556 if (tmp_branch)
10557 got_ref_close(tmp_branch);
10558 if (worktree)
10559 got_worktree_close(worktree);
10560 if (repo) {
10561 const struct got_error *close_err = got_repo_close(repo);
10562 if (error == NULL)
10563 error = close_err;
10565 return error;
10568 __dead static void
10569 usage_integrate(void)
10571 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10572 exit(1);
10575 static const struct got_error *
10576 cmd_integrate(int argc, char *argv[])
10578 const struct got_error *error = NULL;
10579 struct got_repository *repo = NULL;
10580 struct got_worktree *worktree = NULL;
10581 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10582 const char *branch_arg = NULL;
10583 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10584 struct got_fileindex *fileindex = NULL;
10585 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10586 int ch;
10587 struct got_update_progress_arg upa;
10589 while ((ch = getopt(argc, argv, "")) != -1) {
10590 switch (ch) {
10591 default:
10592 usage_integrate();
10593 /* NOTREACHED */
10597 argc -= optind;
10598 argv += optind;
10600 if (argc != 1)
10601 usage_integrate();
10602 branch_arg = argv[0];
10603 #ifndef PROFILE
10604 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10605 "unveil", NULL) == -1)
10606 err(1, "pledge");
10607 #endif
10608 cwd = getcwd(NULL, 0);
10609 if (cwd == NULL) {
10610 error = got_error_from_errno("getcwd");
10611 goto done;
10614 error = got_worktree_open(&worktree, cwd);
10615 if (error) {
10616 if (error->code == GOT_ERR_NOT_WORKTREE)
10617 error = wrap_not_worktree_error(error, "integrate",
10618 cwd);
10619 goto done;
10622 error = check_rebase_or_histedit_in_progress(worktree);
10623 if (error)
10624 goto done;
10626 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10627 NULL);
10628 if (error != NULL)
10629 goto done;
10631 error = apply_unveil(got_repo_get_path(repo), 0,
10632 got_worktree_get_root_path(worktree));
10633 if (error)
10634 goto done;
10636 error = check_merge_in_progress(worktree, repo);
10637 if (error)
10638 goto done;
10640 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10641 error = got_error_from_errno("asprintf");
10642 goto done;
10645 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10646 &base_branch_ref, worktree, refname, repo);
10647 if (error)
10648 goto done;
10650 refname = strdup(got_ref_get_name(branch_ref));
10651 if (refname == NULL) {
10652 error = got_error_from_errno("strdup");
10653 got_worktree_integrate_abort(worktree, fileindex, repo,
10654 branch_ref, base_branch_ref);
10655 goto done;
10657 base_refname = strdup(got_ref_get_name(base_branch_ref));
10658 if (base_refname == NULL) {
10659 error = got_error_from_errno("strdup");
10660 got_worktree_integrate_abort(worktree, fileindex, repo,
10661 branch_ref, base_branch_ref);
10662 goto done;
10665 error = got_ref_resolve(&commit_id, repo, branch_ref);
10666 if (error)
10667 goto done;
10669 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10670 if (error)
10671 goto done;
10673 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10674 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10675 "specified branch has already been integrated");
10676 got_worktree_integrate_abort(worktree, fileindex, repo,
10677 branch_ref, base_branch_ref);
10678 goto done;
10681 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10682 if (error) {
10683 if (error->code == GOT_ERR_ANCESTRY)
10684 error = got_error(GOT_ERR_REBASE_REQUIRED);
10685 got_worktree_integrate_abort(worktree, fileindex, repo,
10686 branch_ref, base_branch_ref);
10687 goto done;
10690 memset(&upa, 0, sizeof(upa));
10691 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10692 branch_ref, base_branch_ref, update_progress, &upa,
10693 check_cancelled, NULL);
10694 if (error)
10695 goto done;
10697 printf("Integrated %s into %s\n", refname, base_refname);
10698 print_update_progress_stats(&upa);
10699 done:
10700 if (repo) {
10701 const struct got_error *close_err = got_repo_close(repo);
10702 if (error == NULL)
10703 error = close_err;
10705 if (worktree)
10706 got_worktree_close(worktree);
10707 free(cwd);
10708 free(base_commit_id);
10709 free(commit_id);
10710 free(refname);
10711 free(base_refname);
10712 return error;
10715 __dead static void
10716 usage_merge(void)
10718 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
10719 getprogname());
10720 exit(1);
10723 static const struct got_error *
10724 cmd_merge(int argc, char *argv[])
10726 const struct got_error *error = NULL;
10727 struct got_worktree *worktree = NULL;
10728 struct got_repository *repo = NULL;
10729 struct got_fileindex *fileindex = NULL;
10730 char *cwd = NULL, *id_str = NULL, *author = NULL;
10731 struct got_reference *branch = NULL, *wt_branch = NULL;
10732 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
10733 struct got_object_id *wt_branch_tip = NULL;
10734 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
10735 int interrupt_merge = 0;
10736 struct got_update_progress_arg upa;
10737 struct got_object_id *merge_commit_id = NULL;
10738 char *branch_name = NULL;
10740 memset(&upa, 0, sizeof(upa));
10742 while ((ch = getopt(argc, argv, "acn")) != -1) {
10743 switch (ch) {
10744 case 'a':
10745 abort_merge = 1;
10746 break;
10747 case 'c':
10748 continue_merge = 1;
10749 break;
10750 case 'n':
10751 interrupt_merge = 1;
10752 break;
10753 default:
10754 usage_rebase();
10755 /* NOTREACHED */
10759 argc -= optind;
10760 argv += optind;
10762 #ifndef PROFILE
10763 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10764 "unveil", NULL) == -1)
10765 err(1, "pledge");
10766 #endif
10768 if (abort_merge && continue_merge)
10769 option_conflict('a', 'c');
10770 if (abort_merge || continue_merge) {
10771 if (argc != 0)
10772 usage_merge();
10773 } else if (argc != 1)
10774 usage_merge();
10776 cwd = getcwd(NULL, 0);
10777 if (cwd == NULL) {
10778 error = got_error_from_errno("getcwd");
10779 goto done;
10782 error = got_worktree_open(&worktree, cwd);
10783 if (error) {
10784 if (error->code == GOT_ERR_NOT_WORKTREE)
10785 error = wrap_not_worktree_error(error,
10786 "merge", cwd);
10787 goto done;
10790 error = got_repo_open(&repo,
10791 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
10792 if (error != NULL)
10793 goto done;
10795 error = apply_unveil(got_repo_get_path(repo), 0,
10796 worktree ? got_worktree_get_root_path(worktree) : NULL);
10797 if (error)
10798 goto done;
10800 error = check_rebase_or_histedit_in_progress(worktree);
10801 if (error)
10802 goto done;
10804 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10805 repo);
10806 if (error)
10807 goto done;
10809 if (abort_merge) {
10810 if (!merge_in_progress) {
10811 error = got_error(GOT_ERR_NOT_MERGING);
10812 goto done;
10814 error = got_worktree_merge_continue(&branch_name,
10815 &branch_tip, &fileindex, worktree, repo);
10816 if (error)
10817 goto done;
10818 error = got_worktree_merge_abort(worktree, fileindex, repo,
10819 abort_progress, &upa);
10820 if (error)
10821 goto done;
10822 printf("Merge of %s aborted\n", branch_name);
10823 goto done; /* nothing else to do */
10826 error = get_author(&author, repo, worktree);
10827 if (error)
10828 goto done;
10830 if (continue_merge) {
10831 if (!merge_in_progress) {
10832 error = got_error(GOT_ERR_NOT_MERGING);
10833 goto done;
10835 error = got_worktree_merge_continue(&branch_name,
10836 &branch_tip, &fileindex, worktree, repo);
10837 if (error)
10838 goto done;
10839 } else {
10840 error = got_ref_open(&branch, repo, argv[0], 0);
10841 if (error != NULL)
10842 goto done;
10843 branch_name = strdup(got_ref_get_name(branch));
10844 if (branch_name == NULL) {
10845 error = got_error_from_errno("strdup");
10846 goto done;
10848 error = got_ref_resolve(&branch_tip, repo, branch);
10849 if (error)
10850 goto done;
10853 error = got_ref_open(&wt_branch, repo,
10854 got_worktree_get_head_ref_name(worktree), 0);
10855 if (error)
10856 goto done;
10857 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
10858 if (error)
10859 goto done;
10860 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10861 wt_branch_tip, branch_tip, 0, repo,
10862 check_cancelled, NULL);
10863 if (error && error->code != GOT_ERR_ANCESTRY)
10864 goto done;
10866 if (!continue_merge) {
10867 error = check_path_prefix(wt_branch_tip, branch_tip,
10868 got_worktree_get_path_prefix(worktree),
10869 GOT_ERR_MERGE_PATH, repo);
10870 if (error)
10871 goto done;
10872 if (yca_id) {
10873 error = check_same_branch(wt_branch_tip, branch,
10874 yca_id, repo);
10875 if (error) {
10876 if (error->code != GOT_ERR_ANCESTRY)
10877 goto done;
10878 error = NULL;
10879 } else {
10880 static char msg[512];
10881 snprintf(msg, sizeof(msg),
10882 "cannot create a merge commit because "
10883 "%s is based on %s; %s can be integrated "
10884 "with 'got integrate' instead", branch_name,
10885 got_worktree_get_head_ref_name(worktree),
10886 branch_name);
10887 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
10888 goto done;
10891 error = got_worktree_merge_prepare(&fileindex, worktree,
10892 branch, repo);
10893 if (error)
10894 goto done;
10896 error = got_worktree_merge_branch(worktree, fileindex,
10897 yca_id, branch_tip, repo, update_progress, &upa,
10898 check_cancelled, NULL);
10899 if (error)
10900 goto done;
10901 print_merge_progress_stats(&upa);
10902 if (!upa.did_something) {
10903 error = got_worktree_merge_abort(worktree, fileindex,
10904 repo, abort_progress, &upa);
10905 if (error)
10906 goto done;
10907 printf("Already up-to-date\n");
10908 goto done;
10912 if (interrupt_merge) {
10913 error = got_worktree_merge_postpone(worktree, fileindex);
10914 if (error)
10915 goto done;
10916 printf("Merge of %s interrupted on request\n", branch_name);
10917 } else if (upa.conflicts > 0 || upa.missing > 0 ||
10918 upa.not_deleted > 0 || upa.unversioned > 0) {
10919 error = got_worktree_merge_postpone(worktree, fileindex);
10920 if (error)
10921 goto done;
10922 if (upa.conflicts > 0 && upa.missing == 0 &&
10923 upa.not_deleted == 0 && upa.unversioned == 0) {
10924 error = got_error_msg(GOT_ERR_CONFLICTS,
10925 "conflicts must be resolved before merging "
10926 "can continue");
10927 } else if (upa.conflicts > 0) {
10928 error = got_error_msg(GOT_ERR_CONFLICTS,
10929 "conflicts must be resolved before merging "
10930 "can continue; changes destined for some "
10931 "files were not yet merged and "
10932 "should be merged manually if required before the "
10933 "merge operation is continued");
10934 } else {
10935 error = got_error_msg(GOT_ERR_CONFLICTS,
10936 "changes destined for some "
10937 "files were not yet merged and should be "
10938 "merged manually if required before the "
10939 "merge operation is continued");
10941 goto done;
10942 } else {
10943 error = got_worktree_merge_commit(&merge_commit_id, worktree,
10944 fileindex, author, NULL, 1, branch_tip, branch_name,
10945 repo, continue_merge ? print_status : NULL, NULL);
10946 if (error)
10947 goto done;
10948 error = got_worktree_merge_complete(worktree, fileindex, repo);
10949 if (error)
10950 goto done;
10951 error = got_object_id_str(&id_str, merge_commit_id);
10952 if (error)
10953 goto done;
10954 printf("Merged %s into %s: %s\n", branch_name,
10955 got_worktree_get_head_ref_name(worktree),
10956 id_str);
10959 done:
10960 free(id_str);
10961 free(merge_commit_id);
10962 free(author);
10963 free(branch_tip);
10964 free(branch_name);
10965 free(yca_id);
10966 if (branch)
10967 got_ref_close(branch);
10968 if (wt_branch)
10969 got_ref_close(wt_branch);
10970 if (worktree)
10971 got_worktree_close(worktree);
10972 if (repo) {
10973 const struct got_error *close_err = got_repo_close(repo);
10974 if (error == NULL)
10975 error = close_err;
10977 return error;
10980 __dead static void
10981 usage_stage(void)
10983 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10984 "[-S] [file-path ...]\n",
10985 getprogname());
10986 exit(1);
10989 static const struct got_error *
10990 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10991 const char *path, struct got_object_id *blob_id,
10992 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10993 int dirfd, const char *de_name)
10995 const struct got_error *err = NULL;
10996 char *id_str = NULL;
10998 if (staged_status != GOT_STATUS_ADD &&
10999 staged_status != GOT_STATUS_MODIFY &&
11000 staged_status != GOT_STATUS_DELETE)
11001 return NULL;
11003 if (staged_status == GOT_STATUS_ADD ||
11004 staged_status == GOT_STATUS_MODIFY)
11005 err = got_object_id_str(&id_str, staged_blob_id);
11006 else
11007 err = got_object_id_str(&id_str, blob_id);
11008 if (err)
11009 return err;
11011 printf("%s %c %s\n", id_str, staged_status, path);
11012 free(id_str);
11013 return NULL;
11016 static const struct got_error *
11017 cmd_stage(int argc, char *argv[])
11019 const struct got_error *error = NULL;
11020 struct got_repository *repo = NULL;
11021 struct got_worktree *worktree = NULL;
11022 char *cwd = NULL;
11023 struct got_pathlist_head paths;
11024 struct got_pathlist_entry *pe;
11025 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11026 FILE *patch_script_file = NULL;
11027 const char *patch_script_path = NULL;
11028 struct choose_patch_arg cpa;
11030 TAILQ_INIT(&paths);
11032 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11033 switch (ch) {
11034 case 'l':
11035 list_stage = 1;
11036 break;
11037 case 'p':
11038 pflag = 1;
11039 break;
11040 case 'F':
11041 patch_script_path = optarg;
11042 break;
11043 case 'S':
11044 allow_bad_symlinks = 1;
11045 break;
11046 default:
11047 usage_stage();
11048 /* NOTREACHED */
11052 argc -= optind;
11053 argv += optind;
11055 #ifndef PROFILE
11056 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11057 "unveil", NULL) == -1)
11058 err(1, "pledge");
11059 #endif
11060 if (list_stage && (pflag || patch_script_path))
11061 errx(1, "-l option cannot be used with other options");
11062 if (patch_script_path && !pflag)
11063 errx(1, "-F option can only be used together with -p option");
11065 cwd = getcwd(NULL, 0);
11066 if (cwd == NULL) {
11067 error = got_error_from_errno("getcwd");
11068 goto done;
11071 error = got_worktree_open(&worktree, cwd);
11072 if (error) {
11073 if (error->code == GOT_ERR_NOT_WORKTREE)
11074 error = wrap_not_worktree_error(error, "stage", cwd);
11075 goto done;
11078 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11079 NULL);
11080 if (error != NULL)
11081 goto done;
11083 if (patch_script_path) {
11084 patch_script_file = fopen(patch_script_path, "r");
11085 if (patch_script_file == NULL) {
11086 error = got_error_from_errno2("fopen",
11087 patch_script_path);
11088 goto done;
11091 error = apply_unveil(got_repo_get_path(repo), 0,
11092 got_worktree_get_root_path(worktree));
11093 if (error)
11094 goto done;
11096 error = check_merge_in_progress(worktree, repo);
11097 if (error)
11098 goto done;
11100 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11101 if (error)
11102 goto done;
11104 if (list_stage)
11105 error = got_worktree_status(worktree, &paths, repo, 0,
11106 print_stage, NULL, check_cancelled, NULL);
11107 else {
11108 cpa.patch_script_file = patch_script_file;
11109 cpa.action = "stage";
11110 error = got_worktree_stage(worktree, &paths,
11111 pflag ? NULL : print_status, NULL,
11112 pflag ? choose_patch : NULL, &cpa,
11113 allow_bad_symlinks, repo);
11115 done:
11116 if (patch_script_file && fclose(patch_script_file) == EOF &&
11117 error == NULL)
11118 error = got_error_from_errno2("fclose", patch_script_path);
11119 if (repo) {
11120 const struct got_error *close_err = got_repo_close(repo);
11121 if (error == NULL)
11122 error = close_err;
11124 if (worktree)
11125 got_worktree_close(worktree);
11126 TAILQ_FOREACH(pe, &paths, entry)
11127 free((char *)pe->path);
11128 got_pathlist_free(&paths);
11129 free(cwd);
11130 return error;
11133 __dead static void
11134 usage_unstage(void)
11136 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11137 "[file-path ...]\n",
11138 getprogname());
11139 exit(1);
11143 static const struct got_error *
11144 cmd_unstage(int argc, char *argv[])
11146 const struct got_error *error = NULL;
11147 struct got_repository *repo = NULL;
11148 struct got_worktree *worktree = NULL;
11149 char *cwd = NULL;
11150 struct got_pathlist_head paths;
11151 struct got_pathlist_entry *pe;
11152 int ch, pflag = 0;
11153 struct got_update_progress_arg upa;
11154 FILE *patch_script_file = NULL;
11155 const char *patch_script_path = NULL;
11156 struct choose_patch_arg cpa;
11158 TAILQ_INIT(&paths);
11160 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11161 switch (ch) {
11162 case 'p':
11163 pflag = 1;
11164 break;
11165 case 'F':
11166 patch_script_path = optarg;
11167 break;
11168 default:
11169 usage_unstage();
11170 /* NOTREACHED */
11174 argc -= optind;
11175 argv += optind;
11177 #ifndef PROFILE
11178 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11179 "unveil", NULL) == -1)
11180 err(1, "pledge");
11181 #endif
11182 if (patch_script_path && !pflag)
11183 errx(1, "-F option can only be used together with -p option");
11185 cwd = getcwd(NULL, 0);
11186 if (cwd == NULL) {
11187 error = got_error_from_errno("getcwd");
11188 goto done;
11191 error = got_worktree_open(&worktree, cwd);
11192 if (error) {
11193 if (error->code == GOT_ERR_NOT_WORKTREE)
11194 error = wrap_not_worktree_error(error, "unstage", cwd);
11195 goto done;
11198 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11199 NULL);
11200 if (error != NULL)
11201 goto done;
11203 if (patch_script_path) {
11204 patch_script_file = fopen(patch_script_path, "r");
11205 if (patch_script_file == NULL) {
11206 error = got_error_from_errno2("fopen",
11207 patch_script_path);
11208 goto done;
11212 error = apply_unveil(got_repo_get_path(repo), 0,
11213 got_worktree_get_root_path(worktree));
11214 if (error)
11215 goto done;
11217 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11218 if (error)
11219 goto done;
11221 cpa.patch_script_file = patch_script_file;
11222 cpa.action = "unstage";
11223 memset(&upa, 0, sizeof(upa));
11224 error = got_worktree_unstage(worktree, &paths, update_progress,
11225 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11226 if (!error)
11227 print_merge_progress_stats(&upa);
11228 done:
11229 if (patch_script_file && fclose(patch_script_file) == EOF &&
11230 error == NULL)
11231 error = got_error_from_errno2("fclose", patch_script_path);
11232 if (repo) {
11233 const struct got_error *close_err = got_repo_close(repo);
11234 if (error == NULL)
11235 error = close_err;
11237 if (worktree)
11238 got_worktree_close(worktree);
11239 TAILQ_FOREACH(pe, &paths, entry)
11240 free((char *)pe->path);
11241 got_pathlist_free(&paths);
11242 free(cwd);
11243 return error;
11246 __dead static void
11247 usage_cat(void)
11249 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11250 "arg1 [arg2 ...]\n", getprogname());
11251 exit(1);
11254 static const struct got_error *
11255 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11257 const struct got_error *err;
11258 struct got_blob_object *blob;
11260 err = got_object_open_as_blob(&blob, repo, id, 8192);
11261 if (err)
11262 return err;
11264 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11265 got_object_blob_close(blob);
11266 return err;
11269 static const struct got_error *
11270 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11272 const struct got_error *err;
11273 struct got_tree_object *tree;
11274 int nentries, i;
11276 err = got_object_open_as_tree(&tree, repo, id);
11277 if (err)
11278 return err;
11280 nentries = got_object_tree_get_nentries(tree);
11281 for (i = 0; i < nentries; i++) {
11282 struct got_tree_entry *te;
11283 char *id_str;
11284 if (sigint_received || sigpipe_received)
11285 break;
11286 te = got_object_tree_get_entry(tree, i);
11287 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11288 if (err)
11289 break;
11290 fprintf(outfile, "%s %.7o %s\n", id_str,
11291 got_tree_entry_get_mode(te),
11292 got_tree_entry_get_name(te));
11293 free(id_str);
11296 got_object_tree_close(tree);
11297 return err;
11300 static const struct got_error *
11301 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11303 const struct got_error *err;
11304 struct got_commit_object *commit;
11305 const struct got_object_id_queue *parent_ids;
11306 struct got_object_qid *pid;
11307 char *id_str = NULL;
11308 const char *logmsg = NULL;
11310 err = got_object_open_as_commit(&commit, repo, id);
11311 if (err)
11312 return err;
11314 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11315 if (err)
11316 goto done;
11318 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11319 parent_ids = got_object_commit_get_parent_ids(commit);
11320 fprintf(outfile, "numparents %d\n",
11321 got_object_commit_get_nparents(commit));
11322 STAILQ_FOREACH(pid, parent_ids, entry) {
11323 char *pid_str;
11324 err = got_object_id_str(&pid_str, pid->id);
11325 if (err)
11326 goto done;
11327 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11328 free(pid_str);
11330 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
11331 got_object_commit_get_author(commit),
11332 (long long)got_object_commit_get_author_time(commit));
11334 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
11335 got_object_commit_get_author(commit),
11336 (long long)got_object_commit_get_committer_time(commit));
11338 logmsg = got_object_commit_get_logmsg_raw(commit);
11339 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11340 fprintf(outfile, "%s", logmsg);
11341 done:
11342 free(id_str);
11343 got_object_commit_close(commit);
11344 return err;
11347 static const struct got_error *
11348 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11350 const struct got_error *err;
11351 struct got_tag_object *tag;
11352 char *id_str = NULL;
11353 const char *tagmsg = NULL;
11355 err = got_object_open_as_tag(&tag, repo, id);
11356 if (err)
11357 return err;
11359 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11360 if (err)
11361 goto done;
11363 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11365 switch (got_object_tag_get_object_type(tag)) {
11366 case GOT_OBJ_TYPE_BLOB:
11367 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11368 GOT_OBJ_LABEL_BLOB);
11369 break;
11370 case GOT_OBJ_TYPE_TREE:
11371 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11372 GOT_OBJ_LABEL_TREE);
11373 break;
11374 case GOT_OBJ_TYPE_COMMIT:
11375 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11376 GOT_OBJ_LABEL_COMMIT);
11377 break;
11378 case GOT_OBJ_TYPE_TAG:
11379 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11380 GOT_OBJ_LABEL_TAG);
11381 break;
11382 default:
11383 break;
11386 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11387 got_object_tag_get_name(tag));
11389 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
11390 got_object_tag_get_tagger(tag),
11391 (long long)got_object_tag_get_tagger_time(tag));
11393 tagmsg = got_object_tag_get_message(tag);
11394 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11395 fprintf(outfile, "%s", tagmsg);
11396 done:
11397 free(id_str);
11398 got_object_tag_close(tag);
11399 return err;
11402 static const struct got_error *
11403 cmd_cat(int argc, char *argv[])
11405 const struct got_error *error;
11406 struct got_repository *repo = NULL;
11407 struct got_worktree *worktree = NULL;
11408 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11409 const char *commit_id_str = NULL;
11410 struct got_object_id *id = NULL, *commit_id = NULL;
11411 int ch, obj_type, i, force_path = 0;
11412 struct got_reflist_head refs;
11414 TAILQ_INIT(&refs);
11416 #ifndef PROFILE
11417 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11418 NULL) == -1)
11419 err(1, "pledge");
11420 #endif
11422 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11423 switch (ch) {
11424 case 'c':
11425 commit_id_str = optarg;
11426 break;
11427 case 'r':
11428 repo_path = realpath(optarg, NULL);
11429 if (repo_path == NULL)
11430 return got_error_from_errno2("realpath",
11431 optarg);
11432 got_path_strip_trailing_slashes(repo_path);
11433 break;
11434 case 'P':
11435 force_path = 1;
11436 break;
11437 default:
11438 usage_cat();
11439 /* NOTREACHED */
11443 argc -= optind;
11444 argv += optind;
11446 cwd = getcwd(NULL, 0);
11447 if (cwd == NULL) {
11448 error = got_error_from_errno("getcwd");
11449 goto done;
11451 error = got_worktree_open(&worktree, cwd);
11452 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11453 goto done;
11454 if (worktree) {
11455 if (repo_path == NULL) {
11456 repo_path = strdup(
11457 got_worktree_get_repo_path(worktree));
11458 if (repo_path == NULL) {
11459 error = got_error_from_errno("strdup");
11460 goto done;
11465 if (repo_path == NULL) {
11466 repo_path = getcwd(NULL, 0);
11467 if (repo_path == NULL)
11468 return got_error_from_errno("getcwd");
11471 error = got_repo_open(&repo, repo_path, NULL);
11472 free(repo_path);
11473 if (error != NULL)
11474 goto done;
11476 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11477 if (error)
11478 goto done;
11480 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11481 if (error)
11482 goto done;
11484 if (commit_id_str == NULL)
11485 commit_id_str = GOT_REF_HEAD;
11486 error = got_repo_match_object_id(&commit_id, NULL,
11487 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11488 if (error)
11489 goto done;
11491 for (i = 0; i < argc; i++) {
11492 if (force_path) {
11493 error = got_object_id_by_path(&id, repo, commit_id,
11494 argv[i]);
11495 if (error)
11496 break;
11497 } else {
11498 error = got_repo_match_object_id(&id, &label, argv[i],
11499 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11500 repo);
11501 if (error) {
11502 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11503 error->code != GOT_ERR_NOT_REF)
11504 break;
11505 error = got_object_id_by_path(&id, repo,
11506 commit_id, argv[i]);
11507 if (error)
11508 break;
11512 error = got_object_get_type(&obj_type, repo, id);
11513 if (error)
11514 break;
11516 switch (obj_type) {
11517 case GOT_OBJ_TYPE_BLOB:
11518 error = cat_blob(id, repo, stdout);
11519 break;
11520 case GOT_OBJ_TYPE_TREE:
11521 error = cat_tree(id, repo, stdout);
11522 break;
11523 case GOT_OBJ_TYPE_COMMIT:
11524 error = cat_commit(id, repo, stdout);
11525 break;
11526 case GOT_OBJ_TYPE_TAG:
11527 error = cat_tag(id, repo, stdout);
11528 break;
11529 default:
11530 error = got_error(GOT_ERR_OBJ_TYPE);
11531 break;
11533 if (error)
11534 break;
11535 free(label);
11536 label = NULL;
11537 free(id);
11538 id = NULL;
11540 done:
11541 free(label);
11542 free(id);
11543 free(commit_id);
11544 if (worktree)
11545 got_worktree_close(worktree);
11546 if (repo) {
11547 const struct got_error *close_err = got_repo_close(repo);
11548 if (error == NULL)
11549 error = close_err;
11551 got_ref_list_free(&refs);
11552 return error;
11555 __dead static void
11556 usage_info(void)
11558 fprintf(stderr, "usage: %s info [path ...]\n",
11559 getprogname());
11560 exit(1);
11563 static const struct got_error *
11564 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11565 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11566 struct got_object_id *commit_id)
11568 const struct got_error *err = NULL;
11569 char *id_str = NULL;
11570 char datebuf[128];
11571 struct tm mytm, *tm;
11572 struct got_pathlist_head *paths = arg;
11573 struct got_pathlist_entry *pe;
11576 * Clear error indication from any of the path arguments which
11577 * would cause this file index entry to be displayed.
11579 TAILQ_FOREACH(pe, paths, entry) {
11580 if (got_path_cmp(path, pe->path, strlen(path),
11581 pe->path_len) == 0 ||
11582 got_path_is_child(path, pe->path, pe->path_len))
11583 pe->data = NULL; /* no error */
11586 printf(GOT_COMMIT_SEP_STR);
11587 if (S_ISLNK(mode))
11588 printf("symlink: %s\n", path);
11589 else if (S_ISREG(mode)) {
11590 printf("file: %s\n", path);
11591 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11592 } else if (S_ISDIR(mode))
11593 printf("directory: %s\n", path);
11594 else
11595 printf("something: %s\n", path);
11597 tm = localtime_r(&mtime, &mytm);
11598 if (tm == NULL)
11599 return NULL;
11600 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11601 return got_error(GOT_ERR_NO_SPACE);
11602 printf("timestamp: %s\n", datebuf);
11604 if (blob_id) {
11605 err = got_object_id_str(&id_str, blob_id);
11606 if (err)
11607 return err;
11608 printf("based on blob: %s\n", id_str);
11609 free(id_str);
11612 if (staged_blob_id) {
11613 err = got_object_id_str(&id_str, staged_blob_id);
11614 if (err)
11615 return err;
11616 printf("based on staged blob: %s\n", id_str);
11617 free(id_str);
11620 if (commit_id) {
11621 err = got_object_id_str(&id_str, commit_id);
11622 if (err)
11623 return err;
11624 printf("based on commit: %s\n", id_str);
11625 free(id_str);
11628 return NULL;
11631 static const struct got_error *
11632 cmd_info(int argc, char *argv[])
11634 const struct got_error *error = NULL;
11635 struct got_worktree *worktree = NULL;
11636 char *cwd = NULL, *id_str = NULL;
11637 struct got_pathlist_head paths;
11638 struct got_pathlist_entry *pe;
11639 char *uuidstr = NULL;
11640 int ch, show_files = 0;
11642 TAILQ_INIT(&paths);
11644 while ((ch = getopt(argc, argv, "")) != -1) {
11645 switch (ch) {
11646 default:
11647 usage_info();
11648 /* NOTREACHED */
11652 argc -= optind;
11653 argv += optind;
11655 #ifndef PROFILE
11656 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11657 NULL) == -1)
11658 err(1, "pledge");
11659 #endif
11660 cwd = getcwd(NULL, 0);
11661 if (cwd == NULL) {
11662 error = got_error_from_errno("getcwd");
11663 goto done;
11666 error = got_worktree_open(&worktree, cwd);
11667 if (error) {
11668 if (error->code == GOT_ERR_NOT_WORKTREE)
11669 error = wrap_not_worktree_error(error, "info", cwd);
11670 goto done;
11673 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11674 if (error)
11675 goto done;
11677 if (argc >= 1) {
11678 error = get_worktree_paths_from_argv(&paths, argc, argv,
11679 worktree);
11680 if (error)
11681 goto done;
11682 show_files = 1;
11685 error = got_object_id_str(&id_str,
11686 got_worktree_get_base_commit_id(worktree));
11687 if (error)
11688 goto done;
11690 error = got_worktree_get_uuid(&uuidstr, worktree);
11691 if (error)
11692 goto done;
11694 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11695 printf("work tree base commit: %s\n", id_str);
11696 printf("work tree path prefix: %s\n",
11697 got_worktree_get_path_prefix(worktree));
11698 printf("work tree branch reference: %s\n",
11699 got_worktree_get_head_ref_name(worktree));
11700 printf("work tree UUID: %s\n", uuidstr);
11701 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11703 if (show_files) {
11704 struct got_pathlist_entry *pe;
11705 TAILQ_FOREACH(pe, &paths, entry) {
11706 if (pe->path_len == 0)
11707 continue;
11709 * Assume this path will fail. This will be corrected
11710 * in print_path_info() in case the path does suceeed.
11712 pe->data = (void *)got_error_path(pe->path,
11713 GOT_ERR_BAD_PATH);
11715 error = got_worktree_path_info(worktree, &paths,
11716 print_path_info, &paths, check_cancelled, NULL);
11717 if (error)
11718 goto done;
11719 TAILQ_FOREACH(pe, &paths, entry) {
11720 if (pe->data != NULL) {
11721 error = pe->data; /* bad path */
11722 break;
11726 done:
11727 TAILQ_FOREACH(pe, &paths, entry)
11728 free((char *)pe->path);
11729 got_pathlist_free(&paths);
11730 free(cwd);
11731 free(id_str);
11732 free(uuidstr);
11733 return error;