Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 #ifndef GOT_DEFAULT_EDITOR
72 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
73 #endif
75 static volatile sig_atomic_t sigint_received;
76 static volatile sig_atomic_t sigpipe_received;
78 static void
79 catch_sigint(int signo)
80 {
81 sigint_received = 1;
82 }
84 static void
85 catch_sigpipe(int signo)
86 {
87 sigpipe_received = 1;
88 }
91 struct got_cmd {
92 const char *cmd_name;
93 const struct got_error *(*cmd_main)(int, char *[]);
94 void (*cmd_usage)(void);
95 const char *cmd_alias;
96 };
98 __dead static void usage(int, int);
99 __dead static void usage_import(void);
100 __dead static void usage_clone(void);
101 __dead static void usage_fetch(void);
102 __dead static void usage_checkout(void);
103 __dead static void usage_update(void);
104 __dead static void usage_log(void);
105 __dead static void usage_diff(void);
106 __dead static void usage_blame(void);
107 __dead static void usage_tree(void);
108 __dead static void usage_status(void);
109 __dead static void usage_ref(void);
110 __dead static void usage_branch(void);
111 __dead static void usage_tag(void);
112 __dead static void usage_add(void);
113 __dead static void usage_remove(void);
114 __dead static void usage_patch(void);
115 __dead static void usage_revert(void);
116 __dead static void usage_commit(void);
117 __dead static void usage_send(void);
118 __dead static void usage_cherrypick(void);
119 __dead static void usage_backout(void);
120 __dead static void usage_rebase(void);
121 __dead static void usage_histedit(void);
122 __dead static void usage_integrate(void);
123 __dead static void usage_merge(void);
124 __dead static void usage_stage(void);
125 __dead static void usage_unstage(void);
126 __dead static void usage_cat(void);
127 __dead static void usage_info(void);
129 static const struct got_error* cmd_import(int, char *[]);
130 static const struct got_error* cmd_clone(int, char *[]);
131 static const struct got_error* cmd_fetch(int, char *[]);
132 static const struct got_error* cmd_checkout(int, char *[]);
133 static const struct got_error* cmd_update(int, char *[]);
134 static const struct got_error* cmd_log(int, char *[]);
135 static const struct got_error* cmd_diff(int, char *[]);
136 static const struct got_error* cmd_blame(int, char *[]);
137 static const struct got_error* cmd_tree(int, char *[]);
138 static const struct got_error* cmd_status(int, char *[]);
139 static const struct got_error* cmd_ref(int, char *[]);
140 static const struct got_error* cmd_branch(int, char *[]);
141 static const struct got_error* cmd_tag(int, char *[]);
142 static const struct got_error* cmd_add(int, char *[]);
143 static const struct got_error* cmd_remove(int, char *[]);
144 static const struct got_error* cmd_patch(int, char *[]);
145 static const struct got_error* cmd_revert(int, char *[]);
146 static const struct got_error* cmd_commit(int, char *[]);
147 static const struct got_error* cmd_send(int, char *[]);
148 static const struct got_error* cmd_cherrypick(int, char *[]);
149 static const struct got_error* cmd_backout(int, char *[]);
150 static const struct got_error* cmd_rebase(int, char *[]);
151 static const struct got_error* cmd_histedit(int, char *[]);
152 static const struct got_error* cmd_integrate(int, char *[]);
153 static const struct got_error* cmd_merge(int, char *[]);
154 static const struct got_error* cmd_stage(int, char *[]);
155 static const struct got_error* cmd_unstage(int, char *[]);
156 static const struct got_error* cmd_cat(int, char *[]);
157 static const struct got_error* cmd_info(int, char *[]);
159 static const struct got_cmd got_commands[] = {
160 { "import", cmd_import, usage_import, "im" },
161 { "clone", cmd_clone, usage_clone, "cl" },
162 { "fetch", cmd_fetch, usage_fetch, "fe" },
163 { "checkout", cmd_checkout, usage_checkout, "co" },
164 { "update", cmd_update, usage_update, "up" },
165 { "log", cmd_log, usage_log, "" },
166 { "diff", cmd_diff, usage_diff, "di" },
167 { "blame", cmd_blame, usage_blame, "bl" },
168 { "tree", cmd_tree, usage_tree, "tr" },
169 { "status", cmd_status, usage_status, "st" },
170 { "ref", cmd_ref, usage_ref, "" },
171 { "branch", cmd_branch, usage_branch, "br" },
172 { "tag", cmd_tag, usage_tag, "" },
173 { "add", cmd_add, usage_add, "" },
174 { "remove", cmd_remove, usage_remove, "rm" },
175 { "patch", cmd_patch, usage_patch, "pa" },
176 { "revert", cmd_revert, usage_revert, "rv" },
177 { "commit", cmd_commit, usage_commit, "ci" },
178 { "send", cmd_send, usage_send, "se" },
179 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
180 { "backout", cmd_backout, usage_backout, "bo" },
181 { "rebase", cmd_rebase, usage_rebase, "rb" },
182 { "histedit", cmd_histedit, usage_histedit, "he" },
183 { "integrate", cmd_integrate, usage_integrate,"ig" },
184 { "merge", cmd_merge, usage_merge, "mg" },
185 { "stage", cmd_stage, usage_stage, "sg" },
186 { "unstage", cmd_unstage, usage_unstage, "ug" },
187 { "cat", cmd_cat, usage_cat, "" },
188 { "info", cmd_info, usage_info, "" },
189 };
191 static void
192 list_commands(FILE *fp)
194 size_t i;
196 fprintf(fp, "commands:");
197 for (i = 0; i < nitems(got_commands); i++) {
198 const struct got_cmd *cmd = &got_commands[i];
199 fprintf(fp, " %s", cmd->cmd_name);
201 fputc('\n', fp);
204 __dead static void
205 option_conflict(char a, char b)
207 errx(1, "-%c and -%c options are mutually exclusive", a, b);
210 int
211 main(int argc, char *argv[])
213 const struct got_cmd *cmd;
214 size_t i;
215 int ch;
216 int hflag = 0, Vflag = 0;
217 static const struct option longopts[] = {
218 { "version", no_argument, NULL, 'V' },
219 { NULL, 0, NULL, 0 }
220 };
222 setlocale(LC_CTYPE, "");
224 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
225 switch (ch) {
226 case 'h':
227 hflag = 1;
228 break;
229 case 'V':
230 Vflag = 1;
231 break;
232 default:
233 usage(hflag, 1);
234 /* NOTREACHED */
238 argc -= optind;
239 argv += optind;
240 optind = 1;
241 optreset = 1;
243 if (Vflag) {
244 got_version_print_str();
245 return 0;
248 if (argc <= 0)
249 usage(hflag, hflag ? 0 : 1);
251 signal(SIGINT, catch_sigint);
252 signal(SIGPIPE, catch_sigpipe);
254 for (i = 0; i < nitems(got_commands); i++) {
255 const struct got_error *error;
257 cmd = &got_commands[i];
259 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
260 strcmp(cmd->cmd_alias, argv[0]) != 0)
261 continue;
263 if (hflag)
264 cmd->cmd_usage();
266 error = cmd->cmd_main(argc, argv);
267 if (error && error->code != GOT_ERR_CANCELLED &&
268 error->code != GOT_ERR_PRIVSEP_EXIT &&
269 !(sigpipe_received &&
270 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
271 !(sigint_received &&
272 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
273 fflush(stdout);
274 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
275 return 1;
278 return 0;
281 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
282 list_commands(stderr);
283 return 1;
286 __dead static void
287 usage(int hflag, int status)
289 FILE *fp = (status == 0) ? stdout : stderr;
291 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
292 getprogname());
293 if (hflag)
294 list_commands(fp);
295 exit(status);
298 static const struct got_error *
299 get_editor(char **abspath)
301 const struct got_error *err = NULL;
302 const char *editor;
304 *abspath = NULL;
306 editor = getenv("VISUAL");
307 if (editor == NULL)
308 editor = getenv("EDITOR");
310 if (editor) {
311 err = got_path_find_prog(abspath, editor);
312 if (err)
313 return err;
316 if (*abspath == NULL) {
317 *abspath = strdup(GOT_DEFAULT_EDITOR);
318 if (*abspath == NULL)
319 return got_error_from_errno("strdup");
322 return NULL;
325 static const struct got_error *
326 apply_unveil(const char *repo_path, int repo_read_only,
327 const char *worktree_path)
329 const struct got_error *err;
331 #ifdef PROFILE
332 if (unveil("gmon.out", "rwc") != 0)
333 return got_error_from_errno2("unveil", "gmon.out");
334 #endif
335 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
336 return got_error_from_errno2("unveil", repo_path);
338 if (worktree_path && unveil(worktree_path, "rwc") != 0)
339 return got_error_from_errno2("unveil", worktree_path);
341 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
342 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
344 err = got_privsep_unveil_exec_helpers();
345 if (err != NULL)
346 return err;
348 if (unveil(NULL, NULL) != 0)
349 return got_error_from_errno("unveil");
351 return NULL;
354 __dead static void
355 usage_import(void)
357 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
358 "[-r repository-path] directory\n", getprogname());
359 exit(1);
362 static int
363 spawn_editor(const char *editor, const char *file)
365 pid_t pid;
366 sig_t sighup, sigint, sigquit;
367 int st = -1;
369 sighup = signal(SIGHUP, SIG_IGN);
370 sigint = signal(SIGINT, SIG_IGN);
371 sigquit = signal(SIGQUIT, SIG_IGN);
373 switch (pid = fork()) {
374 case -1:
375 goto doneediting;
376 case 0:
377 execl(editor, editor, file, (char *)NULL);
378 _exit(127);
381 while (waitpid(pid, &st, 0) == -1)
382 if (errno != EINTR)
383 break;
385 doneediting:
386 (void)signal(SIGHUP, sighup);
387 (void)signal(SIGINT, sigint);
388 (void)signal(SIGQUIT, sigquit);
390 if (!WIFEXITED(st)) {
391 errno = EINTR;
392 return -1;
395 return WEXITSTATUS(st);
398 static const struct got_error *
399 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
401 const struct got_error *err = NULL;
402 char *line = NULL;
403 size_t linesize = 0;
405 *logmsg = NULL;
406 *len = 0;
408 if (fseeko(fp, 0L, SEEK_SET) == -1)
409 return got_error_from_errno("fseeko");
411 *logmsg = malloc(filesize + 1);
412 if (*logmsg == NULL)
413 return got_error_from_errno("malloc");
414 (*logmsg)[0] = '\0';
416 while (getline(&line, &linesize, fp) != -1) {
417 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
418 continue; /* remove comments and leading empty lines */
419 *len = strlcat(*logmsg, line, filesize + 1);
420 if (*len >= filesize + 1) {
421 err = got_error(GOT_ERR_NO_SPACE);
422 goto done;
425 if (ferror(fp)) {
426 err = got_ferror(fp, GOT_ERR_IO);
427 goto done;
430 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
431 (*logmsg)[*len - 1] = '\0';
432 (*len)--;
434 done:
435 free(line);
436 if (err) {
437 free(*logmsg);
438 *logmsg = NULL;
439 *len = 0;
441 return err;
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 struct stat st, st2;
451 FILE *fp = NULL;
452 size_t logmsg_len;
454 *logmsg = NULL;
456 if (stat(logmsg_path, &st) == -1)
457 return got_error_from_errno2("stat", logmsg_path);
459 if (spawn_editor(editor, logmsg_path) == -1)
460 return got_error_from_errno("failed spawning editor");
462 if (require_modification) {
463 struct timespec timeout;
465 timeout.tv_sec = 0;
466 timeout.tv_nsec = 1;
467 nanosleep(&timeout, NULL);
470 if (stat(logmsg_path, &st2) == -1)
471 return got_error_from_errno2("stat", logmsg_path);
473 if (require_modification && st.st_size == st2.st_size &&
474 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
475 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "no changes made to commit message, aborting");
478 fp = fopen(logmsg_path, "re");
479 if (fp == NULL) {
480 err = got_error_from_errno("fopen");
481 goto done;
484 /* strip comments and leading/trailing newlines */
485 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
486 if (err)
487 goto done;
488 if (logmsg_len == 0) {
489 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
490 "commit message cannot be empty, aborting");
491 goto done;
493 done:
494 if (fp && fclose(fp) == EOF && err == NULL)
495 err = got_error_from_errno("fclose");
496 if (err) {
497 free(*logmsg);
498 *logmsg = NULL;
500 return err;
503 static const struct got_error *
504 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
505 const char *path_dir, const char *branch_name)
507 char *initial_content = NULL;
508 const struct got_error *err = NULL;
509 int initial_content_len;
510 int fd = -1;
512 initial_content_len = asprintf(&initial_content,
513 "\n# %s to be imported to branch %s\n", path_dir,
514 branch_name);
515 if (initial_content_len == -1)
516 return got_error_from_errno("asprintf");
518 err = got_opentemp_named_fd(logmsg_path, &fd,
519 GOT_TMPDIR_STR "/got-importmsg", "");
520 if (err)
521 goto done;
523 if (write(fd, initial_content, initial_content_len) == -1) {
524 err = got_error_from_errno2("write", *logmsg_path);
525 goto done;
527 if (close(fd) == -1) {
528 err = got_error_from_errno2("close", *logmsg_path);
529 goto done;
531 fd = -1;
533 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
534 initial_content_len, 1);
535 done:
536 if (fd != -1 && close(fd) == -1 && err == NULL)
537 err = got_error_from_errno2("close", *logmsg_path);
538 free(initial_content);
539 if (err) {
540 free(*logmsg_path);
541 *logmsg_path = NULL;
543 return err;
546 static const struct got_error *
547 import_progress(void *arg, const char *path)
549 printf("A %s\n", path);
550 return NULL;
553 static const struct got_error *
554 valid_author(const char *author)
556 const char *email = author;
558 /*
559 * Git' expects the author (or committer) to be in the form
560 * "name <email>", which are mostly free form (see the
561 * "committer" description in git-fast-import(1)). We're only
562 * doing this to avoid git's object parser breaking on commits
563 * we create.
564 */
566 while (*author && *author != '\n' && *author != '<' && *author != '>')
567 author++;
568 if (author != email && *author == '<' && *(author - 1) != ' ')
569 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
570 "between author name and email required", email);
571 if (*author++ != '<')
572 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
573 while (*author && *author != '\n' && *author != '<' && *author != '>')
574 author++;
575 if (strcmp(author, ">") != 0)
576 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
577 return NULL;
580 static const struct got_error *
581 get_author(char **author, struct got_repository *repo,
582 struct got_worktree *worktree)
584 const struct got_error *err = NULL;
585 const char *got_author = NULL, *name, *email;
586 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
588 *author = NULL;
590 if (worktree)
591 worktree_conf = got_worktree_get_gotconfig(worktree);
592 repo_conf = got_repo_get_gotconfig(repo);
594 /*
595 * Priority of potential author information sources, from most
596 * significant to least significant:
597 * 1) work tree's .got/got.conf file
598 * 2) repository's got.conf file
599 * 3) repository's git config file
600 * 4) environment variables
601 * 5) global git config files (in user's home directory or /etc)
602 */
604 if (worktree_conf)
605 got_author = got_gotconfig_get_author(worktree_conf);
606 if (got_author == NULL)
607 got_author = got_gotconfig_get_author(repo_conf);
608 if (got_author == NULL) {
609 name = got_repo_get_gitconfig_author_name(repo);
610 email = got_repo_get_gitconfig_author_email(repo);
611 if (name && email) {
612 if (asprintf(author, "%s <%s>", name, email) == -1)
613 return got_error_from_errno("asprintf");
614 return NULL;
617 got_author = getenv("GOT_AUTHOR");
618 if (got_author == NULL) {
619 name = got_repo_get_global_gitconfig_author_name(repo);
620 email = got_repo_get_global_gitconfig_author_email(
621 repo);
622 if (name && email) {
623 if (asprintf(author, "%s <%s>", name, email)
624 == -1)
625 return got_error_from_errno("asprintf");
626 return NULL;
628 /* TODO: Look up user in password database? */
629 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
633 *author = strdup(got_author);
634 if (*author == NULL)
635 return got_error_from_errno("strdup");
637 err = valid_author(*author);
638 if (err) {
639 free(*author);
640 *author = NULL;
642 return err;
645 static const struct got_error *
646 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
647 struct got_worktree *worktree)
649 const char *got_allowed_signers = NULL;
650 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
652 *allowed_signers = NULL;
654 if (worktree)
655 worktree_conf = got_worktree_get_gotconfig(worktree);
656 repo_conf = got_repo_get_gotconfig(repo);
658 /*
659 * Priority of potential author information sources, from most
660 * significant to least significant:
661 * 1) work tree's .got/got.conf file
662 * 2) repository's got.conf file
663 */
665 if (worktree_conf)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 worktree_conf);
668 if (got_allowed_signers == NULL)
669 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
670 repo_conf);
672 if (got_allowed_signers) {
673 *allowed_signers = strdup(got_allowed_signers);
674 if (*allowed_signers == NULL)
675 return got_error_from_errno("strdup");
677 return NULL;
680 static const struct got_error *
681 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
682 struct got_worktree *worktree)
684 const char *got_revoked_signers = NULL;
685 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
687 *revoked_signers = NULL;
689 if (worktree)
690 worktree_conf = got_worktree_get_gotconfig(worktree);
691 repo_conf = got_repo_get_gotconfig(repo);
693 /*
694 * Priority of potential author information sources, from most
695 * significant to least significant:
696 * 1) work tree's .got/got.conf file
697 * 2) repository's got.conf file
698 */
700 if (worktree_conf)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 worktree_conf);
703 if (got_revoked_signers == NULL)
704 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
705 repo_conf);
707 if (got_revoked_signers) {
708 *revoked_signers = strdup(got_revoked_signers);
709 if (*revoked_signers == NULL)
710 return got_error_from_errno("strdup");
712 return NULL;
715 static const char *
716 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
718 const char *got_signer_id = NULL;
719 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 return got_signer_id;
740 static const struct got_error *
741 get_gitconfig_path(char **gitconfig_path)
743 const char *homedir = getenv("HOME");
745 *gitconfig_path = NULL;
746 if (homedir) {
747 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
748 return got_error_from_errno("asprintf");
751 return NULL;
754 static const struct got_error *
755 cmd_import(int argc, char *argv[])
757 const struct got_error *error = NULL;
758 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
759 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
760 const char *branch_name = NULL;
761 char *id_str = NULL, *logmsg_path = NULL;
762 char refname[PATH_MAX] = "refs/heads/";
763 struct got_repository *repo = NULL;
764 struct got_reference *branch_ref = NULL, *head_ref = NULL;
765 struct got_object_id *new_commit_id = NULL;
766 int ch, n = 0;
767 struct got_pathlist_head ignores;
768 struct got_pathlist_entry *pe;
769 int preserve_logmsg = 0;
770 int *pack_fds = NULL;
772 TAILQ_INIT(&ignores);
774 #ifndef PROFILE
775 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
776 "unveil",
777 NULL) == -1)
778 err(1, "pledge");
779 #endif
781 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
782 switch (ch) {
783 case 'b':
784 branch_name = optarg;
785 break;
786 case 'I':
787 if (optarg[0] == '\0')
788 break;
789 error = got_pathlist_insert(&pe, &ignores, optarg,
790 NULL);
791 if (error)
792 goto done;
793 break;
794 case 'm':
795 logmsg = strdup(optarg);
796 if (logmsg == NULL) {
797 error = got_error_from_errno("strdup");
798 goto done;
800 break;
801 case 'r':
802 repo_path = realpath(optarg, NULL);
803 if (repo_path == NULL) {
804 error = got_error_from_errno2("realpath",
805 optarg);
806 goto done;
808 break;
809 default:
810 usage_import();
811 /* NOTREACHED */
815 argc -= optind;
816 argv += optind;
818 if (argc != 1)
819 usage_import();
821 if (repo_path == NULL) {
822 repo_path = getcwd(NULL, 0);
823 if (repo_path == NULL)
824 return got_error_from_errno("getcwd");
826 got_path_strip_trailing_slashes(repo_path);
827 error = get_gitconfig_path(&gitconfig_path);
828 if (error)
829 goto done;
830 error = got_repo_pack_fds_open(&pack_fds);
831 if (error != NULL)
832 goto done;
833 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
834 if (error)
835 goto done;
837 error = get_author(&author, repo, NULL);
838 if (error)
839 return error;
841 /*
842 * Don't let the user create a branch name with a leading '-'.
843 * While technically a valid reference name, this case is usually
844 * an unintended typo.
845 */
846 if (branch_name && branch_name[0] == '-')
847 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
849 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
850 if (error && error->code != GOT_ERR_NOT_REF)
851 goto done;
853 if (branch_name)
854 n = strlcat(refname, branch_name, sizeof(refname));
855 else if (head_ref && got_ref_is_symbolic(head_ref))
856 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
857 sizeof(refname));
858 else
859 n = strlcat(refname, "main", sizeof(refname));
860 if (n >= sizeof(refname)) {
861 error = got_error(GOT_ERR_NO_SPACE);
862 goto done;
865 error = got_ref_open(&branch_ref, repo, refname, 0);
866 if (error) {
867 if (error->code != GOT_ERR_NOT_REF)
868 goto done;
869 } else {
870 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
871 "import target branch already exists");
872 goto done;
875 path_dir = realpath(argv[0], NULL);
876 if (path_dir == NULL) {
877 error = got_error_from_errno2("realpath", argv[0]);
878 goto done;
880 got_path_strip_trailing_slashes(path_dir);
882 /*
883 * unveil(2) traverses exec(2); if an editor is used we have
884 * to apply unveil after the log message has been written.
885 */
886 if (logmsg == NULL || *logmsg == '\0') {
887 error = get_editor(&editor);
888 if (error)
889 goto done;
890 free(logmsg);
891 error = collect_import_msg(&logmsg, &logmsg_path, editor,
892 path_dir, refname);
893 if (error) {
894 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
895 logmsg_path != NULL)
896 preserve_logmsg = 1;
897 goto done;
901 if (unveil(path_dir, "r") != 0) {
902 error = got_error_from_errno2("unveil", path_dir);
903 if (logmsg_path)
904 preserve_logmsg = 1;
905 goto done;
908 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
909 if (error) {
910 if (logmsg_path)
911 preserve_logmsg = 1;
912 goto done;
915 error = got_repo_import(&new_commit_id, path_dir, logmsg,
916 author, &ignores, repo, import_progress, NULL);
917 if (error) {
918 if (logmsg_path)
919 preserve_logmsg = 1;
920 goto done;
923 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
924 if (error) {
925 if (logmsg_path)
926 preserve_logmsg = 1;
927 goto done;
930 error = got_ref_write(branch_ref, repo);
931 if (error) {
932 if (logmsg_path)
933 preserve_logmsg = 1;
934 goto done;
937 error = got_object_id_str(&id_str, new_commit_id);
938 if (error) {
939 if (logmsg_path)
940 preserve_logmsg = 1;
941 goto done;
944 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
945 if (error) {
946 if (error->code != GOT_ERR_NOT_REF) {
947 if (logmsg_path)
948 preserve_logmsg = 1;
949 goto done;
952 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
953 branch_ref);
954 if (error) {
955 if (logmsg_path)
956 preserve_logmsg = 1;
957 goto done;
960 error = got_ref_write(head_ref, repo);
961 if (error) {
962 if (logmsg_path)
963 preserve_logmsg = 1;
964 goto done;
968 printf("Created branch %s with commit %s\n",
969 got_ref_get_name(branch_ref), id_str);
970 done:
971 if (pack_fds) {
972 const struct got_error *pack_err =
973 got_repo_pack_fds_close(pack_fds);
974 if (error == NULL)
975 error = pack_err;
977 if (repo) {
978 const struct got_error *close_err = got_repo_close(repo);
979 if (error == NULL)
980 error = close_err;
982 if (preserve_logmsg) {
983 fprintf(stderr, "%s: log message preserved in %s\n",
984 getprogname(), logmsg_path);
985 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
986 error = got_error_from_errno2("unlink", logmsg_path);
987 free(logmsg);
988 free(logmsg_path);
989 free(repo_path);
990 free(editor);
991 free(new_commit_id);
992 free(id_str);
993 free(author);
994 free(gitconfig_path);
995 if (branch_ref)
996 got_ref_close(branch_ref);
997 if (head_ref)
998 got_ref_close(head_ref);
999 return error;
1002 __dead static void
1003 usage_clone(void)
1005 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1006 "repository-URL [directory]\n", getprogname());
1007 exit(1);
1010 struct got_fetch_progress_arg {
1011 char last_scaled_size[FMT_SCALED_STRSIZE];
1012 int last_p_indexed;
1013 int last_p_resolved;
1014 int verbosity;
1016 struct got_repository *repo;
1018 int create_configs;
1019 int configs_created;
1020 struct {
1021 struct got_pathlist_head *symrefs;
1022 struct got_pathlist_head *wanted_branches;
1023 struct got_pathlist_head *wanted_refs;
1024 const char *proto;
1025 const char *host;
1026 const char *port;
1027 const char *remote_repo_path;
1028 const char *git_url;
1029 int fetch_all_branches;
1030 int mirror_references;
1031 } config_info;
1034 /* XXX forward declaration */
1035 static const struct got_error *
1036 create_config_files(const char *proto, const char *host, const char *port,
1037 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1038 int mirror_references, struct got_pathlist_head *symrefs,
1039 struct got_pathlist_head *wanted_branches,
1040 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1042 static const struct got_error *
1043 fetch_progress(void *arg, const char *message, off_t packfile_size,
1044 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1046 const struct got_error *err = NULL;
1047 struct got_fetch_progress_arg *a = arg;
1048 char scaled_size[FMT_SCALED_STRSIZE];
1049 int p_indexed, p_resolved;
1050 int print_size = 0, print_indexed = 0, print_resolved = 0;
1053 * In order to allow a failed clone to be resumed with 'got fetch'
1054 * we try to create configuration files as soon as possible.
1055 * Once the server has sent information about its default branch
1056 * we have all required information.
1058 if (a->create_configs && !a->configs_created &&
1059 !TAILQ_EMPTY(a->config_info.symrefs)) {
1060 err = create_config_files(a->config_info.proto,
1061 a->config_info.host, a->config_info.port,
1062 a->config_info.remote_repo_path,
1063 a->config_info.git_url,
1064 a->config_info.fetch_all_branches,
1065 a->config_info.mirror_references,
1066 a->config_info.symrefs,
1067 a->config_info.wanted_branches,
1068 a->config_info.wanted_refs, a->repo);
1069 if (err)
1070 return err;
1071 a->configs_created = 1;
1074 if (a->verbosity < 0)
1075 return NULL;
1077 if (message && message[0] != '\0') {
1078 printf("\rserver: %s", message);
1079 fflush(stdout);
1080 return NULL;
1083 if (packfile_size > 0 || nobj_indexed > 0) {
1084 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1085 (a->last_scaled_size[0] == '\0' ||
1086 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1087 print_size = 1;
1088 if (strlcpy(a->last_scaled_size, scaled_size,
1089 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1090 return got_error(GOT_ERR_NO_SPACE);
1092 if (nobj_indexed > 0) {
1093 p_indexed = (nobj_indexed * 100) / nobj_total;
1094 if (p_indexed != a->last_p_indexed) {
1095 a->last_p_indexed = p_indexed;
1096 print_indexed = 1;
1097 print_size = 1;
1100 if (nobj_resolved > 0) {
1101 p_resolved = (nobj_resolved * 100) /
1102 (nobj_total - nobj_loose);
1103 if (p_resolved != a->last_p_resolved) {
1104 a->last_p_resolved = p_resolved;
1105 print_resolved = 1;
1106 print_indexed = 1;
1107 print_size = 1;
1112 if (print_size || print_indexed || print_resolved)
1113 printf("\r");
1114 if (print_size)
1115 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1116 if (print_indexed)
1117 printf("; indexing %d%%", p_indexed);
1118 if (print_resolved)
1119 printf("; resolving deltas %d%%", p_resolved);
1120 if (print_size || print_indexed || print_resolved)
1121 fflush(stdout);
1123 return NULL;
1126 static const struct got_error *
1127 create_symref(const char *refname, struct got_reference *target_ref,
1128 int verbosity, struct got_repository *repo)
1130 const struct got_error *err;
1131 struct got_reference *head_symref;
1133 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1134 if (err)
1135 return err;
1137 err = got_ref_write(head_symref, repo);
1138 if (err == NULL && verbosity > 0) {
1139 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1140 got_ref_get_name(target_ref));
1142 got_ref_close(head_symref);
1143 return err;
1146 static const struct got_error *
1147 list_remote_refs(struct got_pathlist_head *symrefs,
1148 struct got_pathlist_head *refs)
1150 const struct got_error *err;
1151 struct got_pathlist_entry *pe;
1153 TAILQ_FOREACH(pe, symrefs, entry) {
1154 const char *refname = pe->path;
1155 const char *targetref = pe->data;
1157 printf("%s: %s\n", refname, targetref);
1160 TAILQ_FOREACH(pe, refs, entry) {
1161 const char *refname = pe->path;
1162 struct got_object_id *id = pe->data;
1163 char *id_str;
1165 err = got_object_id_str(&id_str, id);
1166 if (err)
1167 return err;
1168 printf("%s: %s\n", refname, id_str);
1169 free(id_str);
1172 return NULL;
1175 static const struct got_error *
1176 create_ref(const char *refname, struct got_object_id *id,
1177 int verbosity, struct got_repository *repo)
1179 const struct got_error *err = NULL;
1180 struct got_reference *ref;
1181 char *id_str;
1183 err = got_object_id_str(&id_str, id);
1184 if (err)
1185 return err;
1187 err = got_ref_alloc(&ref, refname, id);
1188 if (err)
1189 goto done;
1191 err = got_ref_write(ref, repo);
1192 got_ref_close(ref);
1194 if (err == NULL && verbosity >= 0)
1195 printf("Created reference %s: %s\n", refname, id_str);
1196 done:
1197 free(id_str);
1198 return err;
1201 static int
1202 match_wanted_ref(const char *refname, const char *wanted_ref)
1204 if (strncmp(refname, "refs/", 5) != 0)
1205 return 0;
1206 refname += 5;
1209 * Prevent fetching of references that won't make any
1210 * sense outside of the remote repository's context.
1212 if (strncmp(refname, "got/", 4) == 0)
1213 return 0;
1214 if (strncmp(refname, "remotes/", 8) == 0)
1215 return 0;
1217 if (strncmp(wanted_ref, "refs/", 5) == 0)
1218 wanted_ref += 5;
1220 /* Allow prefix match. */
1221 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1222 return 1;
1224 /* Allow exact match. */
1225 return (strcmp(refname, wanted_ref) == 0);
1228 static int
1229 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1231 struct got_pathlist_entry *pe;
1233 TAILQ_FOREACH(pe, wanted_refs, entry) {
1234 if (match_wanted_ref(refname, pe->path))
1235 return 1;
1238 return 0;
1241 static const struct got_error *
1242 create_wanted_ref(const char *refname, struct got_object_id *id,
1243 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1245 const struct got_error *err;
1246 char *remote_refname;
1248 if (strncmp("refs/", refname, 5) == 0)
1249 refname += 5;
1251 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1252 remote_repo_name, refname) == -1)
1253 return got_error_from_errno("asprintf");
1255 err = create_ref(remote_refname, id, verbosity, repo);
1256 free(remote_refname);
1257 return err;
1260 static const struct got_error *
1261 create_gotconfig(const char *proto, const char *host, const char *port,
1262 const char *remote_repo_path, const char *default_branch,
1263 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1264 struct got_pathlist_head *wanted_refs, int mirror_references,
1265 struct got_repository *repo)
1267 const struct got_error *err = NULL;
1268 char *gotconfig_path = NULL;
1269 char *gotconfig = NULL;
1270 FILE *gotconfig_file = NULL;
1271 const char *branchname = NULL;
1272 char *branches = NULL, *refs = NULL;
1273 ssize_t n;
1275 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1276 struct got_pathlist_entry *pe;
1277 TAILQ_FOREACH(pe, wanted_branches, entry) {
1278 char *s;
1279 branchname = pe->path;
1280 if (strncmp(branchname, "refs/heads/", 11) == 0)
1281 branchname += 11;
1282 if (asprintf(&s, "%s\"%s\" ",
1283 branches ? branches : "", branchname) == -1) {
1284 err = got_error_from_errno("asprintf");
1285 goto done;
1287 free(branches);
1288 branches = s;
1290 } else if (!fetch_all_branches && default_branch) {
1291 branchname = default_branch;
1292 if (strncmp(branchname, "refs/heads/", 11) == 0)
1293 branchname += 11;
1294 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1295 err = got_error_from_errno("asprintf");
1296 goto done;
1299 if (!TAILQ_EMPTY(wanted_refs)) {
1300 struct got_pathlist_entry *pe;
1301 TAILQ_FOREACH(pe, wanted_refs, entry) {
1302 char *s;
1303 const char *refname = pe->path;
1304 if (strncmp(refname, "refs/", 5) == 0)
1305 branchname += 5;
1306 if (asprintf(&s, "%s\"%s\" ",
1307 refs ? refs : "", refname) == -1) {
1308 err = got_error_from_errno("asprintf");
1309 goto done;
1311 free(refs);
1312 refs = s;
1316 /* Create got.conf(5). */
1317 gotconfig_path = got_repo_get_path_gotconfig(repo);
1318 if (gotconfig_path == NULL) {
1319 err = got_error_from_errno("got_repo_get_path_gotconfig");
1320 goto done;
1322 gotconfig_file = fopen(gotconfig_path, "ae");
1323 if (gotconfig_file == NULL) {
1324 err = got_error_from_errno2("fopen", gotconfig_path);
1325 goto done;
1327 if (asprintf(&gotconfig,
1328 "remote \"%s\" {\n"
1329 "\tserver %s\n"
1330 "\tprotocol %s\n"
1331 "%s%s%s"
1332 "\trepository \"%s\"\n"
1333 "%s%s%s"
1334 "%s%s%s"
1335 "%s"
1336 "%s"
1337 "}\n",
1338 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1339 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1340 remote_repo_path, branches ? "\tbranch { " : "",
1341 branches ? branches : "", branches ? "}\n" : "",
1342 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1343 mirror_references ? "\tmirror_references yes\n" : "",
1344 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1345 err = got_error_from_errno("asprintf");
1346 goto done;
1348 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1349 if (n != strlen(gotconfig)) {
1350 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1351 goto done;
1354 done:
1355 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1356 err = got_error_from_errno2("fclose", gotconfig_path);
1357 free(gotconfig_path);
1358 free(branches);
1359 return err;
1362 static const struct got_error *
1363 create_gitconfig(const char *git_url, const char *default_branch,
1364 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1365 struct got_pathlist_head *wanted_refs, int mirror_references,
1366 struct got_repository *repo)
1368 const struct got_error *err = NULL;
1369 char *gitconfig_path = NULL;
1370 char *gitconfig = NULL;
1371 FILE *gitconfig_file = NULL;
1372 char *branches = NULL, *refs = NULL;
1373 const char *branchname;
1374 ssize_t n;
1376 /* Create a config file Git can understand. */
1377 gitconfig_path = got_repo_get_path_gitconfig(repo);
1378 if (gitconfig_path == NULL) {
1379 err = got_error_from_errno("got_repo_get_path_gitconfig");
1380 goto done;
1382 gitconfig_file = fopen(gitconfig_path, "ae");
1383 if (gitconfig_file == NULL) {
1384 err = got_error_from_errno2("fopen", gitconfig_path);
1385 goto done;
1387 if (fetch_all_branches) {
1388 if (mirror_references) {
1389 if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1391 err = got_error_from_errno("asprintf");
1392 goto done;
1394 } else if (asprintf(&branches,
1395 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1396 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1400 } else if (!TAILQ_EMPTY(wanted_branches)) {
1401 struct got_pathlist_entry *pe;
1402 TAILQ_FOREACH(pe, wanted_branches, entry) {
1403 char *s;
1404 branchname = pe->path;
1405 if (strncmp(branchname, "refs/heads/", 11) == 0)
1406 branchname += 11;
1407 if (mirror_references) {
1408 if (asprintf(&s,
1409 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1410 branches ? branches : "",
1411 branchname, branchname) == -1) {
1412 err = got_error_from_errno("asprintf");
1413 goto done;
1415 } else if (asprintf(&s,
1416 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1417 branches ? branches : "",
1418 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1419 branchname) == -1) {
1420 err = got_error_from_errno("asprintf");
1421 goto done;
1423 free(branches);
1424 branches = s;
1426 } else {
1428 * If the server specified a default branch, use just that one.
1429 * Otherwise fall back to fetching all branches on next fetch.
1431 if (default_branch) {
1432 branchname = default_branch;
1433 if (strncmp(branchname, "refs/heads/", 11) == 0)
1434 branchname += 11;
1435 } else
1436 branchname = "*"; /* fall back to all branches */
1437 if (mirror_references) {
1438 if (asprintf(&branches,
1439 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1440 branchname, branchname) == -1) {
1441 err = got_error_from_errno("asprintf");
1442 goto done;
1444 } else if (asprintf(&branches,
1445 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1446 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1447 branchname) == -1) {
1448 err = got_error_from_errno("asprintf");
1449 goto done;
1452 if (!TAILQ_EMPTY(wanted_refs)) {
1453 struct got_pathlist_entry *pe;
1454 TAILQ_FOREACH(pe, wanted_refs, entry) {
1455 char *s;
1456 const char *refname = pe->path;
1457 if (strncmp(refname, "refs/", 5) == 0)
1458 refname += 5;
1459 if (mirror_references) {
1460 if (asprintf(&s,
1461 "%s\tfetch = refs/%s:refs/%s\n",
1462 refs ? refs : "", refname, refname) == -1) {
1463 err = got_error_from_errno("asprintf");
1464 goto done;
1466 } else if (asprintf(&s,
1467 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1468 refs ? refs : "",
1469 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1470 refname) == -1) {
1471 err = got_error_from_errno("asprintf");
1472 goto done;
1474 free(refs);
1475 refs = s;
1479 if (asprintf(&gitconfig,
1480 "[remote \"%s\"]\n"
1481 "\turl = %s\n"
1482 "%s"
1483 "%s"
1484 "\tfetch = refs/tags/*:refs/tags/*\n",
1485 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1486 refs ? refs : "") == -1) {
1487 err = got_error_from_errno("asprintf");
1488 goto done;
1490 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1491 if (n != strlen(gitconfig)) {
1492 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1493 goto done;
1495 done:
1496 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1497 err = got_error_from_errno2("fclose", gitconfig_path);
1498 free(gitconfig_path);
1499 free(branches);
1500 return err;
1503 static const struct got_error *
1504 create_config_files(const char *proto, const char *host, const char *port,
1505 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1506 int mirror_references, struct got_pathlist_head *symrefs,
1507 struct got_pathlist_head *wanted_branches,
1508 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1510 const struct got_error *err = NULL;
1511 const char *default_branch = NULL;
1512 struct got_pathlist_entry *pe;
1515 * If we asked for a set of wanted branches then use the first
1516 * one of those.
1518 if (!TAILQ_EMPTY(wanted_branches)) {
1519 pe = TAILQ_FIRST(wanted_branches);
1520 default_branch = pe->path;
1521 } else {
1522 /* First HEAD ref listed by server is the default branch. */
1523 TAILQ_FOREACH(pe, symrefs, entry) {
1524 const char *refname = pe->path;
1525 const char *target = pe->data;
1527 if (strcmp(refname, GOT_REF_HEAD) != 0)
1528 continue;
1530 default_branch = target;
1531 break;
1535 /* Create got.conf(5). */
1536 err = create_gotconfig(proto, host, port, remote_repo_path,
1537 default_branch, fetch_all_branches, wanted_branches,
1538 wanted_refs, mirror_references, repo);
1539 if (err)
1540 return err;
1542 /* Create a config file Git can understand. */
1543 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1544 wanted_branches, wanted_refs, mirror_references, repo);
1547 static const struct got_error *
1548 cmd_clone(int argc, char *argv[])
1550 const struct got_error *error = NULL;
1551 const char *uri, *dirname;
1552 char *proto, *host, *port, *repo_name, *server_path;
1553 char *default_destdir = NULL, *id_str = NULL;
1554 const char *repo_path;
1555 struct got_repository *repo = NULL;
1556 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1557 struct got_pathlist_entry *pe;
1558 struct got_object_id *pack_hash = NULL;
1559 int ch, fetchfd = -1, fetchstatus;
1560 pid_t fetchpid = -1;
1561 struct got_fetch_progress_arg fpa;
1562 char *git_url = NULL;
1563 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1564 int bflag = 0, list_refs_only = 0;
1565 int *pack_fds = NULL;
1567 TAILQ_INIT(&refs);
1568 TAILQ_INIT(&symrefs);
1569 TAILQ_INIT(&wanted_branches);
1570 TAILQ_INIT(&wanted_refs);
1572 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1573 switch (ch) {
1574 case 'a':
1575 fetch_all_branches = 1;
1576 break;
1577 case 'b':
1578 error = got_pathlist_append(&wanted_branches,
1579 optarg, NULL);
1580 if (error)
1581 return error;
1582 bflag = 1;
1583 break;
1584 case 'l':
1585 list_refs_only = 1;
1586 break;
1587 case 'm':
1588 mirror_references = 1;
1589 break;
1590 case 'q':
1591 verbosity = -1;
1592 break;
1593 case 'R':
1594 error = got_pathlist_append(&wanted_refs,
1595 optarg, NULL);
1596 if (error)
1597 return error;
1598 break;
1599 case 'v':
1600 if (verbosity < 0)
1601 verbosity = 0;
1602 else if (verbosity < 3)
1603 verbosity++;
1604 break;
1605 default:
1606 usage_clone();
1607 break;
1610 argc -= optind;
1611 argv += optind;
1613 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1614 option_conflict('a', 'b');
1615 if (list_refs_only) {
1616 if (!TAILQ_EMPTY(&wanted_branches))
1617 option_conflict('l', 'b');
1618 if (fetch_all_branches)
1619 option_conflict('l', 'a');
1620 if (mirror_references)
1621 option_conflict('l', 'm');
1622 if (!TAILQ_EMPTY(&wanted_refs))
1623 option_conflict('l', 'R');
1626 uri = argv[0];
1628 if (argc == 1)
1629 dirname = NULL;
1630 else if (argc == 2)
1631 dirname = argv[1];
1632 else
1633 usage_clone();
1635 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1636 &repo_name, uri);
1637 if (error)
1638 goto done;
1640 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1641 host, port ? ":" : "", port ? port : "",
1642 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1643 error = got_error_from_errno("asprintf");
1644 goto done;
1647 if (strcmp(proto, "git") == 0) {
1648 #ifndef PROFILE
1649 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1650 "sendfd dns inet unveil", NULL) == -1)
1651 err(1, "pledge");
1652 #endif
1653 } else if (strcmp(proto, "git+ssh") == 0 ||
1654 strcmp(proto, "ssh") == 0) {
1655 #ifndef PROFILE
1656 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1657 "sendfd unveil", NULL) == -1)
1658 err(1, "pledge");
1659 #endif
1660 } else if (strcmp(proto, "http") == 0 ||
1661 strcmp(proto, "git+http") == 0) {
1662 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1663 goto done;
1664 } else {
1665 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1666 goto done;
1668 if (dirname == NULL) {
1669 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1670 error = got_error_from_errno("asprintf");
1671 goto done;
1673 repo_path = default_destdir;
1674 } else
1675 repo_path = dirname;
1677 if (!list_refs_only) {
1678 error = got_path_mkdir(repo_path);
1679 if (error &&
1680 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1681 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1682 goto done;
1683 if (!got_path_dir_is_empty(repo_path)) {
1684 error = got_error_path(repo_path,
1685 GOT_ERR_DIR_NOT_EMPTY);
1686 goto done;
1690 error = got_dial_apply_unveil(proto);
1691 if (error)
1692 goto done;
1694 error = apply_unveil(repo_path, 0, NULL);
1695 if (error)
1696 goto done;
1698 if (verbosity >= 0)
1699 printf("Connecting to %s\n", git_url);
1701 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1702 server_path, verbosity);
1703 if (error)
1704 goto done;
1706 if (!list_refs_only) {
1707 error = got_repo_init(repo_path, NULL);
1708 if (error)
1709 goto done;
1710 error = got_repo_pack_fds_open(&pack_fds);
1711 if (error != NULL)
1712 goto done;
1713 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1714 if (error)
1715 goto done;
1718 fpa.last_scaled_size[0] = '\0';
1719 fpa.last_p_indexed = -1;
1720 fpa.last_p_resolved = -1;
1721 fpa.verbosity = verbosity;
1722 fpa.create_configs = 1;
1723 fpa.configs_created = 0;
1724 fpa.repo = repo;
1725 fpa.config_info.symrefs = &symrefs;
1726 fpa.config_info.wanted_branches = &wanted_branches;
1727 fpa.config_info.wanted_refs = &wanted_refs;
1728 fpa.config_info.proto = proto;
1729 fpa.config_info.host = host;
1730 fpa.config_info.port = port;
1731 fpa.config_info.remote_repo_path = server_path;
1732 fpa.config_info.git_url = git_url;
1733 fpa.config_info.fetch_all_branches = fetch_all_branches;
1734 fpa.config_info.mirror_references = mirror_references;
1735 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1736 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1737 fetch_all_branches, &wanted_branches, &wanted_refs,
1738 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1739 fetch_progress, &fpa);
1740 if (error)
1741 goto done;
1743 if (list_refs_only) {
1744 error = list_remote_refs(&symrefs, &refs);
1745 goto done;
1748 if (pack_hash == NULL) {
1749 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1750 "server sent an empty pack file");
1751 goto done;
1753 error = got_object_id_str(&id_str, pack_hash);
1754 if (error)
1755 goto done;
1756 if (verbosity >= 0)
1757 printf("\nFetched %s.pack\n", id_str);
1758 free(id_str);
1760 /* Set up references provided with the pack file. */
1761 TAILQ_FOREACH(pe, &refs, entry) {
1762 const char *refname = pe->path;
1763 struct got_object_id *id = pe->data;
1764 char *remote_refname;
1766 if (is_wanted_ref(&wanted_refs, refname) &&
1767 !mirror_references) {
1768 error = create_wanted_ref(refname, id,
1769 GOT_FETCH_DEFAULT_REMOTE_NAME,
1770 verbosity - 1, repo);
1771 if (error)
1772 goto done;
1773 continue;
1776 error = create_ref(refname, id, verbosity - 1, repo);
1777 if (error)
1778 goto done;
1780 if (mirror_references)
1781 continue;
1783 if (strncmp("refs/heads/", refname, 11) != 0)
1784 continue;
1786 if (asprintf(&remote_refname,
1787 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1788 refname + 11) == -1) {
1789 error = got_error_from_errno("asprintf");
1790 goto done;
1792 error = create_ref(remote_refname, id, verbosity - 1, repo);
1793 free(remote_refname);
1794 if (error)
1795 goto done;
1798 /* Set the HEAD reference if the server provided one. */
1799 TAILQ_FOREACH(pe, &symrefs, entry) {
1800 struct got_reference *target_ref;
1801 const char *refname = pe->path;
1802 const char *target = pe->data;
1803 char *remote_refname = NULL, *remote_target = NULL;
1805 if (strcmp(refname, GOT_REF_HEAD) != 0)
1806 continue;
1808 error = got_ref_open(&target_ref, repo, target, 0);
1809 if (error) {
1810 if (error->code == GOT_ERR_NOT_REF) {
1811 error = NULL;
1812 continue;
1814 goto done;
1817 error = create_symref(refname, target_ref, verbosity, repo);
1818 got_ref_close(target_ref);
1819 if (error)
1820 goto done;
1822 if (mirror_references)
1823 continue;
1825 if (strncmp("refs/heads/", target, 11) != 0)
1826 continue;
1828 if (asprintf(&remote_refname,
1829 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1830 refname) == -1) {
1831 error = got_error_from_errno("asprintf");
1832 goto done;
1834 if (asprintf(&remote_target,
1835 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1836 target + 11) == -1) {
1837 error = got_error_from_errno("asprintf");
1838 free(remote_refname);
1839 goto done;
1841 error = got_ref_open(&target_ref, repo, remote_target, 0);
1842 if (error) {
1843 free(remote_refname);
1844 free(remote_target);
1845 if (error->code == GOT_ERR_NOT_REF) {
1846 error = NULL;
1847 continue;
1849 goto done;
1851 error = create_symref(remote_refname, target_ref,
1852 verbosity - 1, repo);
1853 free(remote_refname);
1854 free(remote_target);
1855 got_ref_close(target_ref);
1856 if (error)
1857 goto done;
1859 if (pe == NULL) {
1861 * We failed to set the HEAD reference. If we asked for
1862 * a set of wanted branches use the first of one of those
1863 * which could be fetched instead.
1865 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1866 const char *target = pe->path;
1867 struct got_reference *target_ref;
1869 error = got_ref_open(&target_ref, repo, target, 0);
1870 if (error) {
1871 if (error->code == GOT_ERR_NOT_REF) {
1872 error = NULL;
1873 continue;
1875 goto done;
1878 error = create_symref(GOT_REF_HEAD, target_ref,
1879 verbosity, repo);
1880 got_ref_close(target_ref);
1881 if (error)
1882 goto done;
1883 break;
1886 if (!fpa.configs_created && pe != NULL) {
1887 error = create_config_files(fpa.config_info.proto,
1888 fpa.config_info.host, fpa.config_info.port,
1889 fpa.config_info.remote_repo_path,
1890 fpa.config_info.git_url,
1891 fpa.config_info.fetch_all_branches,
1892 fpa.config_info.mirror_references,
1893 fpa.config_info.symrefs,
1894 fpa.config_info.wanted_branches,
1895 fpa.config_info.wanted_refs, fpa.repo);
1896 if (error)
1897 goto done;
1901 if (verbosity >= 0)
1902 printf("Created %s repository '%s'\n",
1903 mirror_references ? "mirrored" : "cloned", repo_path);
1904 done:
1905 if (pack_fds) {
1906 const struct got_error *pack_err =
1907 got_repo_pack_fds_close(pack_fds);
1908 if (error == NULL)
1909 error = pack_err;
1911 if (fetchpid > 0) {
1912 if (kill(fetchpid, SIGTERM) == -1)
1913 error = got_error_from_errno("kill");
1914 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1915 error = got_error_from_errno("waitpid");
1917 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1918 error = got_error_from_errno("close");
1919 if (repo) {
1920 const struct got_error *close_err = got_repo_close(repo);
1921 if (error == NULL)
1922 error = close_err;
1924 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1925 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1926 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1927 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1928 free(pack_hash);
1929 free(proto);
1930 free(host);
1931 free(port);
1932 free(server_path);
1933 free(repo_name);
1934 free(default_destdir);
1935 free(git_url);
1936 return error;
1939 static const struct got_error *
1940 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1941 int replace_tags, int verbosity, struct got_repository *repo)
1943 const struct got_error *err = NULL;
1944 char *new_id_str = NULL;
1945 struct got_object_id *old_id = NULL;
1947 err = got_object_id_str(&new_id_str, new_id);
1948 if (err)
1949 goto done;
1951 if (!replace_tags &&
1952 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1953 err = got_ref_resolve(&old_id, repo, ref);
1954 if (err)
1955 goto done;
1956 if (got_object_id_cmp(old_id, new_id) == 0)
1957 goto done;
1958 if (verbosity >= 0) {
1959 printf("Rejecting update of existing tag %s: %s\n",
1960 got_ref_get_name(ref), new_id_str);
1962 goto done;
1965 if (got_ref_is_symbolic(ref)) {
1966 if (verbosity >= 0) {
1967 printf("Replacing reference %s: %s\n",
1968 got_ref_get_name(ref),
1969 got_ref_get_symref_target(ref));
1971 err = got_ref_change_symref_to_ref(ref, new_id);
1972 if (err)
1973 goto done;
1974 err = got_ref_write(ref, repo);
1975 if (err)
1976 goto done;
1977 } else {
1978 err = got_ref_resolve(&old_id, repo, ref);
1979 if (err)
1980 goto done;
1981 if (got_object_id_cmp(old_id, new_id) == 0)
1982 goto done;
1984 err = got_ref_change_ref(ref, new_id);
1985 if (err)
1986 goto done;
1987 err = got_ref_write(ref, repo);
1988 if (err)
1989 goto done;
1992 if (verbosity >= 0)
1993 printf("Updated %s: %s\n", got_ref_get_name(ref),
1994 new_id_str);
1995 done:
1996 free(old_id);
1997 free(new_id_str);
1998 return err;
2001 static const struct got_error *
2002 update_symref(const char *refname, struct got_reference *target_ref,
2003 int verbosity, struct got_repository *repo)
2005 const struct got_error *err = NULL, *unlock_err;
2006 struct got_reference *symref;
2007 int symref_is_locked = 0;
2009 err = got_ref_open(&symref, repo, refname, 1);
2010 if (err) {
2011 if (err->code != GOT_ERR_NOT_REF)
2012 return err;
2013 err = got_ref_alloc_symref(&symref, refname, target_ref);
2014 if (err)
2015 goto done;
2017 err = got_ref_write(symref, repo);
2018 if (err)
2019 goto done;
2021 if (verbosity >= 0)
2022 printf("Created reference %s: %s\n",
2023 got_ref_get_name(symref),
2024 got_ref_get_symref_target(symref));
2025 } else {
2026 symref_is_locked = 1;
2028 if (strcmp(got_ref_get_symref_target(symref),
2029 got_ref_get_name(target_ref)) == 0)
2030 goto done;
2032 err = got_ref_change_symref(symref,
2033 got_ref_get_name(target_ref));
2034 if (err)
2035 goto done;
2037 err = got_ref_write(symref, repo);
2038 if (err)
2039 goto done;
2041 if (verbosity >= 0)
2042 printf("Updated %s: %s\n", got_ref_get_name(symref),
2043 got_ref_get_symref_target(symref));
2046 done:
2047 if (symref_is_locked) {
2048 unlock_err = got_ref_unlock(symref);
2049 if (unlock_err && err == NULL)
2050 err = unlock_err;
2052 got_ref_close(symref);
2053 return err;
2056 __dead static void
2057 usage_fetch(void)
2059 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2060 "[-R reference] [-r repository-path] [remote-repository]\n",
2061 getprogname());
2062 exit(1);
2065 static const struct got_error *
2066 delete_missing_ref(struct got_reference *ref,
2067 int verbosity, struct got_repository *repo)
2069 const struct got_error *err = NULL;
2070 struct got_object_id *id = NULL;
2071 char *id_str = NULL;
2073 if (got_ref_is_symbolic(ref)) {
2074 err = got_ref_delete(ref, repo);
2075 if (err)
2076 return err;
2077 if (verbosity >= 0) {
2078 printf("Deleted %s: %s\n",
2079 got_ref_get_name(ref),
2080 got_ref_get_symref_target(ref));
2082 } else {
2083 err = got_ref_resolve(&id, repo, ref);
2084 if (err)
2085 return err;
2086 err = got_object_id_str(&id_str, id);
2087 if (err)
2088 goto done;
2090 err = got_ref_delete(ref, repo);
2091 if (err)
2092 goto done;
2093 if (verbosity >= 0) {
2094 printf("Deleted %s: %s\n",
2095 got_ref_get_name(ref), id_str);
2098 done:
2099 free(id);
2100 free(id_str);
2101 return err;
2104 static const struct got_error *
2105 delete_missing_refs(struct got_pathlist_head *their_refs,
2106 struct got_pathlist_head *their_symrefs,
2107 const struct got_remote_repo *remote,
2108 int verbosity, struct got_repository *repo)
2110 const struct got_error *err = NULL, *unlock_err;
2111 struct got_reflist_head my_refs;
2112 struct got_reflist_entry *re;
2113 struct got_pathlist_entry *pe;
2114 char *remote_namespace = NULL;
2115 char *local_refname = NULL;
2117 TAILQ_INIT(&my_refs);
2119 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2120 == -1)
2121 return got_error_from_errno("asprintf");
2123 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2124 if (err)
2125 goto done;
2127 TAILQ_FOREACH(re, &my_refs, entry) {
2128 const char *refname = got_ref_get_name(re->ref);
2129 const char *their_refname;
2131 if (remote->mirror_references) {
2132 their_refname = refname;
2133 } else {
2134 if (strncmp(refname, remote_namespace,
2135 strlen(remote_namespace)) == 0) {
2136 if (strcmp(refname + strlen(remote_namespace),
2137 GOT_REF_HEAD) == 0)
2138 continue;
2139 if (asprintf(&local_refname, "refs/heads/%s",
2140 refname + strlen(remote_namespace)) == -1) {
2141 err = got_error_from_errno("asprintf");
2142 goto done;
2144 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2145 continue;
2147 their_refname = local_refname;
2150 TAILQ_FOREACH(pe, their_refs, entry) {
2151 if (strcmp(their_refname, pe->path) == 0)
2152 break;
2154 if (pe != NULL)
2155 continue;
2157 TAILQ_FOREACH(pe, their_symrefs, entry) {
2158 if (strcmp(their_refname, pe->path) == 0)
2159 break;
2161 if (pe != NULL)
2162 continue;
2164 err = delete_missing_ref(re->ref, verbosity, repo);
2165 if (err)
2166 break;
2168 if (local_refname) {
2169 struct got_reference *ref;
2170 err = got_ref_open(&ref, repo, local_refname, 1);
2171 if (err) {
2172 if (err->code != GOT_ERR_NOT_REF)
2173 break;
2174 free(local_refname);
2175 local_refname = NULL;
2176 continue;
2178 err = delete_missing_ref(ref, verbosity, repo);
2179 if (err)
2180 break;
2181 unlock_err = got_ref_unlock(ref);
2182 got_ref_close(ref);
2183 if (unlock_err && err == NULL) {
2184 err = unlock_err;
2185 break;
2188 free(local_refname);
2189 local_refname = NULL;
2192 done:
2193 got_ref_list_free(&my_refs);
2194 free(remote_namespace);
2195 free(local_refname);
2196 return err;
2199 static const struct got_error *
2200 update_wanted_ref(const char *refname, struct got_object_id *id,
2201 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2203 const struct got_error *err, *unlock_err;
2204 char *remote_refname;
2205 struct got_reference *ref;
2207 if (strncmp("refs/", refname, 5) == 0)
2208 refname += 5;
2210 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2211 remote_repo_name, refname) == -1)
2212 return got_error_from_errno("asprintf");
2214 err = got_ref_open(&ref, repo, remote_refname, 1);
2215 if (err) {
2216 if (err->code != GOT_ERR_NOT_REF)
2217 goto done;
2218 err = create_ref(remote_refname, id, verbosity, repo);
2219 } else {
2220 err = update_ref(ref, id, 0, verbosity, repo);
2221 unlock_err = got_ref_unlock(ref);
2222 if (unlock_err && err == NULL)
2223 err = unlock_err;
2224 got_ref_close(ref);
2226 done:
2227 free(remote_refname);
2228 return err;
2231 static const struct got_error *
2232 delete_ref(struct got_repository *repo, struct got_reference *ref)
2234 const struct got_error *err = NULL;
2235 struct got_object_id *id = NULL;
2236 char *id_str = NULL;
2237 const char *target;
2239 if (got_ref_is_symbolic(ref)) {
2240 target = got_ref_get_symref_target(ref);
2241 } else {
2242 err = got_ref_resolve(&id, repo, ref);
2243 if (err)
2244 goto done;
2245 err = got_object_id_str(&id_str, id);
2246 if (err)
2247 goto done;
2248 target = id_str;
2251 err = got_ref_delete(ref, repo);
2252 if (err)
2253 goto done;
2255 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2256 done:
2257 free(id);
2258 free(id_str);
2259 return err;
2262 static const struct got_error *
2263 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2265 const struct got_error *err = NULL;
2266 struct got_reflist_head refs;
2267 struct got_reflist_entry *re;
2268 char *prefix;
2270 TAILQ_INIT(&refs);
2272 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2273 err = got_error_from_errno("asprintf");
2274 goto done;
2276 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2277 if (err)
2278 goto done;
2280 TAILQ_FOREACH(re, &refs, entry)
2281 delete_ref(repo, re->ref);
2282 done:
2283 got_ref_list_free(&refs);
2284 return err;
2287 static const struct got_error *
2288 cmd_fetch(int argc, char *argv[])
2290 const struct got_error *error = NULL, *unlock_err;
2291 char *cwd = NULL, *repo_path = NULL;
2292 const char *remote_name;
2293 char *proto = NULL, *host = NULL, *port = NULL;
2294 char *repo_name = NULL, *server_path = NULL;
2295 const struct got_remote_repo *remotes;
2296 struct got_remote_repo *remote = NULL;
2297 int nremotes;
2298 char *id_str = NULL;
2299 struct got_repository *repo = NULL;
2300 struct got_worktree *worktree = NULL;
2301 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2302 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2303 char *head_refname = NULL;
2304 struct got_pathlist_entry *pe;
2305 struct got_reflist_head remote_refs;
2306 struct got_reflist_entry *re;
2307 struct got_object_id *pack_hash = NULL;
2308 int i, ch, fetchfd = -1, fetchstatus;
2309 pid_t fetchpid = -1;
2310 struct got_fetch_progress_arg fpa;
2311 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2312 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2313 int *pack_fds = NULL, have_bflag = 0;
2314 const char *remote_head = NULL, *worktree_branch = NULL;
2316 TAILQ_INIT(&refs);
2317 TAILQ_INIT(&symrefs);
2318 TAILQ_INIT(&remote_refs);
2319 TAILQ_INIT(&wanted_branches);
2320 TAILQ_INIT(&wanted_refs);
2322 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2323 switch (ch) {
2324 case 'a':
2325 fetch_all_branches = 1;
2326 break;
2327 case 'b':
2328 error = got_pathlist_append(&wanted_branches,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 have_bflag = 1;
2333 break;
2334 case 'd':
2335 delete_refs = 1;
2336 break;
2337 case 'l':
2338 list_refs_only = 1;
2339 break;
2340 case 'q':
2341 verbosity = -1;
2342 break;
2343 case 'R':
2344 error = got_pathlist_append(&wanted_refs,
2345 optarg, NULL);
2346 if (error)
2347 return error;
2348 break;
2349 case 'r':
2350 repo_path = realpath(optarg, NULL);
2351 if (repo_path == NULL)
2352 return got_error_from_errno2("realpath",
2353 optarg);
2354 got_path_strip_trailing_slashes(repo_path);
2355 break;
2356 case 't':
2357 replace_tags = 1;
2358 break;
2359 case 'v':
2360 if (verbosity < 0)
2361 verbosity = 0;
2362 else if (verbosity < 3)
2363 verbosity++;
2364 break;
2365 case 'X':
2366 delete_remote = 1;
2367 break;
2368 default:
2369 usage_fetch();
2370 break;
2373 argc -= optind;
2374 argv += optind;
2376 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2377 option_conflict('a', 'b');
2378 if (list_refs_only) {
2379 if (!TAILQ_EMPTY(&wanted_branches))
2380 option_conflict('l', 'b');
2381 if (fetch_all_branches)
2382 option_conflict('l', 'a');
2383 if (delete_refs)
2384 option_conflict('l', 'd');
2385 if (delete_remote)
2386 option_conflict('l', 'X');
2388 if (delete_remote) {
2389 if (fetch_all_branches)
2390 option_conflict('X', 'a');
2391 if (!TAILQ_EMPTY(&wanted_branches))
2392 option_conflict('X', 'b');
2393 if (delete_refs)
2394 option_conflict('X', 'd');
2395 if (replace_tags)
2396 option_conflict('X', 't');
2397 if (!TAILQ_EMPTY(&wanted_refs))
2398 option_conflict('X', 'R');
2401 if (argc == 0) {
2402 if (delete_remote)
2403 errx(1, "-X option requires a remote name");
2404 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2405 } else if (argc == 1)
2406 remote_name = argv[0];
2407 else
2408 usage_fetch();
2410 cwd = getcwd(NULL, 0);
2411 if (cwd == NULL) {
2412 error = got_error_from_errno("getcwd");
2413 goto done;
2416 error = got_repo_pack_fds_open(&pack_fds);
2417 if (error != NULL)
2418 goto done;
2420 if (repo_path == NULL) {
2421 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2422 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2423 goto done;
2424 else
2425 error = NULL;
2426 if (worktree) {
2427 repo_path =
2428 strdup(got_worktree_get_repo_path(worktree));
2429 if (repo_path == NULL)
2430 error = got_error_from_errno("strdup");
2431 if (error)
2432 goto done;
2433 } else {
2434 repo_path = strdup(cwd);
2435 if (repo_path == NULL) {
2436 error = got_error_from_errno("strdup");
2437 goto done;
2442 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2443 if (error)
2444 goto done;
2446 if (delete_remote) {
2447 error = delete_refs_for_remote(repo, remote_name);
2448 goto done; /* nothing else to do */
2451 if (worktree) {
2452 worktree_conf = got_worktree_get_gotconfig(worktree);
2453 if (worktree_conf) {
2454 got_gotconfig_get_remotes(&nremotes, &remotes,
2455 worktree_conf);
2456 for (i = 0; i < nremotes; i++) {
2457 if (strcmp(remotes[i].name, remote_name) == 0) {
2458 error = got_repo_remote_repo_dup(&remote,
2459 &remotes[i]);
2460 if (error)
2461 goto done;
2462 break;
2467 if (remote == NULL) {
2468 repo_conf = got_repo_get_gotconfig(repo);
2469 if (repo_conf) {
2470 got_gotconfig_get_remotes(&nremotes, &remotes,
2471 repo_conf);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 error = got_repo_remote_repo_dup(&remote,
2475 &remotes[i]);
2476 if (error)
2477 goto done;
2478 break;
2483 if (remote == NULL) {
2484 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2485 for (i = 0; i < nremotes; i++) {
2486 if (strcmp(remotes[i].name, remote_name) == 0) {
2487 error = got_repo_remote_repo_dup(&remote,
2488 &remotes[i]);
2489 if (error)
2490 goto done;
2491 break;
2495 if (remote == NULL) {
2496 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2497 goto done;
2500 if (TAILQ_EMPTY(&wanted_branches)) {
2501 if (!fetch_all_branches)
2502 fetch_all_branches = remote->fetch_all_branches;
2503 for (i = 0; i < remote->nfetch_branches; i++) {
2504 error = got_pathlist_append(&wanted_branches,
2505 remote->fetch_branches[i], NULL);
2506 if (error)
2507 goto done;
2510 if (TAILQ_EMPTY(&wanted_refs)) {
2511 for (i = 0; i < remote->nfetch_refs; i++) {
2512 error = got_pathlist_append(&wanted_refs,
2513 remote->fetch_refs[i], NULL);
2514 if (error)
2515 goto done;
2519 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2520 &repo_name, remote->fetch_url);
2521 if (error)
2522 goto done;
2524 if (strcmp(proto, "git") == 0) {
2525 #ifndef PROFILE
2526 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2527 "sendfd dns inet unveil", NULL) == -1)
2528 err(1, "pledge");
2529 #endif
2530 } else if (strcmp(proto, "git+ssh") == 0 ||
2531 strcmp(proto, "ssh") == 0) {
2532 #ifndef PROFILE
2533 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2534 "sendfd unveil", NULL) == -1)
2535 err(1, "pledge");
2536 #endif
2537 } else if (strcmp(proto, "http") == 0 ||
2538 strcmp(proto, "git+http") == 0) {
2539 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2540 goto done;
2541 } else {
2542 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2543 goto done;
2546 error = got_dial_apply_unveil(proto);
2547 if (error)
2548 goto done;
2550 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2551 if (error)
2552 goto done;
2554 if (worktree) {
2555 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2556 if (head_refname == NULL) {
2557 error = got_error_from_errno("strdup");
2558 goto done;
2561 /* Release work tree lock. */
2562 got_worktree_close(worktree);
2563 worktree = NULL;
2566 if (verbosity >= 0) {
2567 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2568 remote->name, proto, host,
2569 port ? ":" : "", port ? port : "",
2570 *server_path == '/' ? "" : "/", server_path);
2573 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2574 server_path, verbosity);
2575 if (error)
2576 goto done;
2578 if (!have_bflag) {
2580 * If set, get this remote's HEAD ref target so
2581 * if it has changed on the server we can fetch it.
2583 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2584 got_ref_cmp_by_name, repo);
2585 if (error)
2586 goto done;
2588 TAILQ_FOREACH(re, &remote_refs, entry) {
2589 const char *remote_refname, *remote_target;
2590 size_t remote_name_len;
2592 if (!got_ref_is_symbolic(re->ref))
2593 continue;
2595 remote_name_len = strlen(remote->name);
2596 remote_refname = got_ref_get_name(re->ref);
2598 /* we only want refs/remotes/$remote->name/HEAD */
2599 if (strncmp(remote_refname + 13, remote->name,
2600 remote_name_len) != 0)
2601 continue;
2603 if (strcmp(remote_refname + remote_name_len + 14,
2604 GOT_REF_HEAD) != 0)
2605 continue;
2608 * Take the name itself because we already
2609 * only match with refs/heads/ in fetch_pack().
2611 remote_target = got_ref_get_symref_target(re->ref);
2612 remote_head = remote_target + remote_name_len + 14;
2613 break;
2616 if (head_refname &&
2617 strncmp(head_refname, "refs/heads/", 11) == 0)
2618 worktree_branch = head_refname;
2621 fpa.last_scaled_size[0] = '\0';
2622 fpa.last_p_indexed = -1;
2623 fpa.last_p_resolved = -1;
2624 fpa.verbosity = verbosity;
2625 fpa.repo = repo;
2626 fpa.create_configs = 0;
2627 fpa.configs_created = 0;
2628 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2630 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2631 remote->mirror_references, fetch_all_branches, &wanted_branches,
2632 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2633 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2634 if (error)
2635 goto done;
2637 if (list_refs_only) {
2638 error = list_remote_refs(&symrefs, &refs);
2639 goto done;
2642 if (pack_hash == NULL) {
2643 if (verbosity >= 0)
2644 printf("Already up-to-date\n");
2645 } else if (verbosity >= 0) {
2646 error = got_object_id_str(&id_str, pack_hash);
2647 if (error)
2648 goto done;
2649 printf("\nFetched %s.pack\n", id_str);
2650 free(id_str);
2651 id_str = NULL;
2654 /* Update references provided with the pack file. */
2655 TAILQ_FOREACH(pe, &refs, entry) {
2656 const char *refname = pe->path;
2657 struct got_object_id *id = pe->data;
2658 struct got_reference *ref;
2659 char *remote_refname;
2661 if (is_wanted_ref(&wanted_refs, refname) &&
2662 !remote->mirror_references) {
2663 error = update_wanted_ref(refname, id,
2664 remote->name, verbosity, repo);
2665 if (error)
2666 goto done;
2667 continue;
2670 if (remote->mirror_references ||
2671 strncmp("refs/tags/", refname, 10) == 0) {
2672 error = got_ref_open(&ref, repo, refname, 1);
2673 if (error) {
2674 if (error->code != GOT_ERR_NOT_REF)
2675 goto done;
2676 error = create_ref(refname, id, verbosity,
2677 repo);
2678 if (error)
2679 goto done;
2680 } else {
2681 error = update_ref(ref, id, replace_tags,
2682 verbosity, repo);
2683 unlock_err = got_ref_unlock(ref);
2684 if (unlock_err && error == NULL)
2685 error = unlock_err;
2686 got_ref_close(ref);
2687 if (error)
2688 goto done;
2690 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2691 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2692 remote_name, refname + 11) == -1) {
2693 error = got_error_from_errno("asprintf");
2694 goto done;
2697 error = got_ref_open(&ref, repo, remote_refname, 1);
2698 if (error) {
2699 if (error->code != GOT_ERR_NOT_REF)
2700 goto done;
2701 error = create_ref(remote_refname, id,
2702 verbosity, repo);
2703 if (error)
2704 goto done;
2705 } else {
2706 error = update_ref(ref, id, replace_tags,
2707 verbosity, repo);
2708 unlock_err = got_ref_unlock(ref);
2709 if (unlock_err && error == NULL)
2710 error = unlock_err;
2711 got_ref_close(ref);
2712 if (error)
2713 goto done;
2716 /* Also create a local branch if none exists yet. */
2717 error = got_ref_open(&ref, repo, refname, 1);
2718 if (error) {
2719 if (error->code != GOT_ERR_NOT_REF)
2720 goto done;
2721 error = create_ref(refname, id, verbosity,
2722 repo);
2723 if (error)
2724 goto done;
2725 } else {
2726 unlock_err = got_ref_unlock(ref);
2727 if (unlock_err && error == NULL)
2728 error = unlock_err;
2729 got_ref_close(ref);
2733 if (delete_refs) {
2734 error = delete_missing_refs(&refs, &symrefs, remote,
2735 verbosity, repo);
2736 if (error)
2737 goto done;
2740 if (!remote->mirror_references) {
2741 /* Update remote HEAD reference if the server provided one. */
2742 TAILQ_FOREACH(pe, &symrefs, entry) {
2743 struct got_reference *target_ref;
2744 const char *refname = pe->path;
2745 const char *target = pe->data;
2746 char *remote_refname = NULL, *remote_target = NULL;
2748 if (strcmp(refname, GOT_REF_HEAD) != 0)
2749 continue;
2751 if (strncmp("refs/heads/", target, 11) != 0)
2752 continue;
2754 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2755 remote->name, refname) == -1) {
2756 error = got_error_from_errno("asprintf");
2757 goto done;
2759 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2760 remote->name, target + 11) == -1) {
2761 error = got_error_from_errno("asprintf");
2762 free(remote_refname);
2763 goto done;
2766 error = got_ref_open(&target_ref, repo, remote_target,
2767 0);
2768 if (error) {
2769 free(remote_refname);
2770 free(remote_target);
2771 if (error->code == GOT_ERR_NOT_REF) {
2772 error = NULL;
2773 continue;
2775 goto done;
2777 error = update_symref(remote_refname, target_ref,
2778 verbosity, repo);
2779 free(remote_refname);
2780 free(remote_target);
2781 got_ref_close(target_ref);
2782 if (error)
2783 goto done;
2786 done:
2787 if (fetchpid > 0) {
2788 if (kill(fetchpid, SIGTERM) == -1)
2789 error = got_error_from_errno("kill");
2790 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2791 error = got_error_from_errno("waitpid");
2793 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2794 error = got_error_from_errno("close");
2795 if (repo) {
2796 const struct got_error *close_err = got_repo_close(repo);
2797 if (error == NULL)
2798 error = close_err;
2800 if (worktree)
2801 got_worktree_close(worktree);
2802 if (pack_fds) {
2803 const struct got_error *pack_err =
2804 got_repo_pack_fds_close(pack_fds);
2805 if (error == NULL)
2806 error = pack_err;
2808 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2809 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2810 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2811 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2812 got_ref_list_free(&remote_refs);
2813 got_repo_free_remote_repo_data(remote);
2814 free(remote);
2815 free(head_refname);
2816 free(id_str);
2817 free(cwd);
2818 free(repo_path);
2819 free(pack_hash);
2820 free(proto);
2821 free(host);
2822 free(port);
2823 free(server_path);
2824 free(repo_name);
2825 return error;
2829 __dead static void
2830 usage_checkout(void)
2832 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2833 "[-p path-prefix] repository-path [work-tree-path]\n",
2834 getprogname());
2835 exit(1);
2838 static void
2839 show_worktree_base_ref_warning(void)
2841 fprintf(stderr, "%s: warning: could not create a reference "
2842 "to the work tree's base commit; the commit could be "
2843 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2844 "repository writable and running 'got update' will prevent this\n",
2845 getprogname());
2848 struct got_checkout_progress_arg {
2849 const char *worktree_path;
2850 int had_base_commit_ref_error;
2851 int verbosity;
2854 static const struct got_error *
2855 checkout_progress(void *arg, unsigned char status, const char *path)
2857 struct got_checkout_progress_arg *a = arg;
2859 /* Base commit bump happens silently. */
2860 if (status == GOT_STATUS_BUMP_BASE)
2861 return NULL;
2863 if (status == GOT_STATUS_BASE_REF_ERR) {
2864 a->had_base_commit_ref_error = 1;
2865 return NULL;
2868 while (path[0] == '/')
2869 path++;
2871 if (a->verbosity >= 0)
2872 printf("%c %s/%s\n", status, a->worktree_path, path);
2874 return NULL;
2877 static const struct got_error *
2878 check_cancelled(void *arg)
2880 if (sigint_received || sigpipe_received)
2881 return got_error(GOT_ERR_CANCELLED);
2882 return NULL;
2885 static const struct got_error *
2886 check_linear_ancestry(struct got_object_id *commit_id,
2887 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2888 struct got_repository *repo)
2890 const struct got_error *err = NULL;
2891 struct got_object_id *yca_id;
2893 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2894 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2895 if (err)
2896 return err;
2898 if (yca_id == NULL)
2899 return got_error(GOT_ERR_ANCESTRY);
2902 * Require a straight line of history between the target commit
2903 * and the work tree's base commit.
2905 * Non-linear situations such as this require a rebase:
2907 * (commit) D F (base_commit)
2908 * \ /
2909 * C E
2910 * \ /
2911 * B (yca)
2912 * |
2913 * A
2915 * 'got update' only handles linear cases:
2916 * Update forwards in time: A (base/yca) - B - C - D (commit)
2917 * Update backwards in time: D (base) - C - B - A (commit/yca)
2919 if (allow_forwards_in_time_only) {
2920 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2921 return got_error(GOT_ERR_ANCESTRY);
2922 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2923 got_object_id_cmp(base_commit_id, yca_id) != 0)
2924 return got_error(GOT_ERR_ANCESTRY);
2926 free(yca_id);
2927 return NULL;
2930 static const struct got_error *
2931 check_same_branch(struct got_object_id *commit_id,
2932 struct got_reference *head_ref, struct got_repository *repo)
2934 const struct got_error *err = NULL;
2935 struct got_commit_graph *graph = NULL;
2936 struct got_object_id *head_commit_id = NULL;
2938 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2939 if (err)
2940 goto done;
2942 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2943 goto done;
2945 err = got_commit_graph_open(&graph, "/", 1);
2946 if (err)
2947 goto done;
2949 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2950 check_cancelled, NULL);
2951 if (err)
2952 goto done;
2954 for (;;) {
2955 struct got_object_id id;
2957 err = got_commit_graph_iter_next(&id, graph, repo,
2958 check_cancelled, NULL);
2959 if (err) {
2960 if (err->code == GOT_ERR_ITER_COMPLETED)
2961 err = got_error(GOT_ERR_ANCESTRY);
2962 break;
2965 if (got_object_id_cmp(&id, commit_id) == 0)
2966 break;
2968 done:
2969 if (graph)
2970 got_commit_graph_close(graph);
2971 free(head_commit_id);
2972 return err;
2975 static const struct got_error *
2976 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2978 static char msg[512];
2979 const char *branch_name;
2981 if (got_ref_is_symbolic(ref))
2982 branch_name = got_ref_get_symref_target(ref);
2983 else
2984 branch_name = got_ref_get_name(ref);
2986 if (strncmp("refs/heads/", branch_name, 11) == 0)
2987 branch_name += 11;
2989 snprintf(msg, sizeof(msg),
2990 "target commit is not contained in branch '%s'; "
2991 "the branch to use must be specified with -b; "
2992 "if necessary a new branch can be created for "
2993 "this commit with 'got branch -c %s BRANCH_NAME'",
2994 branch_name, commit_id_str);
2996 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2999 static const struct got_error *
3000 cmd_checkout(int argc, char *argv[])
3002 const struct got_error *close_err, *error = NULL;
3003 struct got_repository *repo = NULL;
3004 struct got_reference *head_ref = NULL, *ref = NULL;
3005 struct got_worktree *worktree = NULL;
3006 char *repo_path = NULL;
3007 char *worktree_path = NULL;
3008 const char *path_prefix = "";
3009 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3010 char *commit_id_str = NULL, *keyword_idstr = NULL;
3011 struct got_object_id *commit_id = NULL;
3012 char *cwd = NULL;
3013 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3014 struct got_pathlist_head paths;
3015 struct got_checkout_progress_arg cpa;
3016 int *pack_fds = NULL;
3018 TAILQ_INIT(&paths);
3020 #ifndef PROFILE
3021 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3022 "unveil", NULL) == -1)
3023 err(1, "pledge");
3024 #endif
3026 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3027 switch (ch) {
3028 case 'b':
3029 branch_name = optarg;
3030 break;
3031 case 'c':
3032 commit_id_str = strdup(optarg);
3033 if (commit_id_str == NULL)
3034 return got_error_from_errno("strdup");
3035 break;
3036 case 'E':
3037 allow_nonempty = 1;
3038 break;
3039 case 'p':
3040 path_prefix = optarg;
3041 break;
3042 case 'q':
3043 verbosity = -1;
3044 break;
3045 default:
3046 usage_checkout();
3047 /* NOTREACHED */
3051 argc -= optind;
3052 argv += optind;
3054 if (argc == 1) {
3055 char *base, *dotgit;
3056 const char *path;
3057 repo_path = realpath(argv[0], NULL);
3058 if (repo_path == NULL)
3059 return got_error_from_errno2("realpath", argv[0]);
3060 cwd = getcwd(NULL, 0);
3061 if (cwd == NULL) {
3062 error = got_error_from_errno("getcwd");
3063 goto done;
3065 if (path_prefix[0])
3066 path = path_prefix;
3067 else
3068 path = repo_path;
3069 error = got_path_basename(&base, path);
3070 if (error)
3071 goto done;
3072 dotgit = strstr(base, ".git");
3073 if (dotgit)
3074 *dotgit = '\0';
3075 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3076 error = got_error_from_errno("asprintf");
3077 free(base);
3078 goto done;
3080 free(base);
3081 } else if (argc == 2) {
3082 repo_path = realpath(argv[0], NULL);
3083 if (repo_path == NULL) {
3084 error = got_error_from_errno2("realpath", argv[0]);
3085 goto done;
3087 worktree_path = realpath(argv[1], NULL);
3088 if (worktree_path == NULL) {
3089 if (errno != ENOENT) {
3090 error = got_error_from_errno2("realpath",
3091 argv[1]);
3092 goto done;
3094 worktree_path = strdup(argv[1]);
3095 if (worktree_path == NULL) {
3096 error = got_error_from_errno("strdup");
3097 goto done;
3100 } else
3101 usage_checkout();
3103 got_path_strip_trailing_slashes(repo_path);
3104 got_path_strip_trailing_slashes(worktree_path);
3106 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3107 got_path_is_child(repo_path, worktree_path,
3108 strlen(worktree_path))) {
3109 error = got_error_fmt(GOT_ERR_BAD_PATH,
3110 "work tree and repository paths may not overlap: %s",
3111 worktree_path);
3112 goto done;
3115 error = got_repo_pack_fds_open(&pack_fds);
3116 if (error != NULL)
3117 goto done;
3119 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3120 if (error != NULL)
3121 goto done;
3123 /* Pre-create work tree path for unveil(2) */
3124 error = got_path_mkdir(worktree_path);
3125 if (error) {
3126 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3127 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3128 goto done;
3129 if (!allow_nonempty &&
3130 !got_path_dir_is_empty(worktree_path)) {
3131 error = got_error_path(worktree_path,
3132 GOT_ERR_DIR_NOT_EMPTY);
3133 goto done;
3137 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3138 if (error)
3139 goto done;
3141 error = got_ref_open(&head_ref, repo, branch_name, 0);
3142 if (error != NULL)
3143 goto done;
3145 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3146 GOT_WORKTREE_GOT_DIR, repo);
3147 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3148 goto done;
3150 error = got_worktree_open(&worktree, worktree_path,
3151 GOT_WORKTREE_GOT_DIR);
3152 if (error != NULL)
3153 goto done;
3155 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3156 path_prefix);
3157 if (error != NULL)
3158 goto done;
3159 if (!same_path_prefix) {
3160 error = got_error(GOT_ERR_PATH_PREFIX);
3161 goto done;
3164 if (commit_id_str) {
3165 struct got_reflist_head refs;
3166 TAILQ_INIT(&refs);
3167 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3168 NULL);
3169 if (error)
3170 goto done;
3172 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3173 repo, worktree);
3174 if (error != NULL)
3175 goto done;
3176 if (keyword_idstr != NULL) {
3177 free(commit_id_str);
3178 commit_id_str = keyword_idstr;
3181 error = got_repo_match_object_id(&commit_id, NULL,
3182 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3183 got_ref_list_free(&refs);
3184 if (error)
3185 goto done;
3186 error = check_linear_ancestry(commit_id,
3187 got_worktree_get_base_commit_id(worktree), 0, repo);
3188 if (error != NULL) {
3189 if (error->code == GOT_ERR_ANCESTRY) {
3190 error = checkout_ancestry_error(
3191 head_ref, commit_id_str);
3193 goto done;
3195 error = check_same_branch(commit_id, head_ref, repo);
3196 if (error) {
3197 if (error->code == GOT_ERR_ANCESTRY) {
3198 error = checkout_ancestry_error(
3199 head_ref, commit_id_str);
3201 goto done;
3203 error = got_worktree_set_base_commit_id(worktree, repo,
3204 commit_id);
3205 if (error)
3206 goto done;
3207 /* Expand potentially abbreviated commit ID string. */
3208 free(commit_id_str);
3209 error = got_object_id_str(&commit_id_str, commit_id);
3210 if (error)
3211 goto done;
3212 } else {
3213 commit_id = got_object_id_dup(
3214 got_worktree_get_base_commit_id(worktree));
3215 if (commit_id == NULL) {
3216 error = got_error_from_errno("got_object_id_dup");
3217 goto done;
3219 error = got_object_id_str(&commit_id_str, commit_id);
3220 if (error)
3221 goto done;
3224 error = got_pathlist_append(&paths, "", NULL);
3225 if (error)
3226 goto done;
3227 cpa.worktree_path = worktree_path;
3228 cpa.had_base_commit_ref_error = 0;
3229 cpa.verbosity = verbosity;
3230 error = got_worktree_checkout_files(worktree, &paths, repo,
3231 checkout_progress, &cpa, check_cancelled, NULL);
3232 if (error != NULL)
3233 goto done;
3235 if (got_ref_is_symbolic(head_ref)) {
3236 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3237 if (error)
3238 goto done;
3239 refname = got_ref_get_name(ref);
3240 } else
3241 refname = got_ref_get_name(head_ref);
3242 printf("Checked out %s: %s\n", refname, commit_id_str);
3243 printf("Now shut up and hack\n");
3244 if (cpa.had_base_commit_ref_error)
3245 show_worktree_base_ref_warning();
3246 done:
3247 if (pack_fds) {
3248 const struct got_error *pack_err =
3249 got_repo_pack_fds_close(pack_fds);
3250 if (error == NULL)
3251 error = pack_err;
3253 if (head_ref)
3254 got_ref_close(head_ref);
3255 if (ref)
3256 got_ref_close(ref);
3257 if (repo) {
3258 close_err = got_repo_close(repo);
3259 if (error == NULL)
3260 error = close_err;
3262 if (worktree != NULL) {
3263 close_err = got_worktree_close(worktree);
3264 if (error == NULL)
3265 error = close_err;
3267 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3268 free(commit_id_str);
3269 free(commit_id);
3270 free(repo_path);
3271 free(worktree_path);
3272 free(cwd);
3273 return error;
3276 struct got_update_progress_arg {
3277 int did_something;
3278 int conflicts;
3279 int obstructed;
3280 int not_updated;
3281 int missing;
3282 int not_deleted;
3283 int unversioned;
3284 int verbosity;
3287 static void
3288 print_update_progress_stats(struct got_update_progress_arg *upa)
3290 if (!upa->did_something)
3291 return;
3293 if (upa->conflicts > 0)
3294 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3295 if (upa->obstructed > 0)
3296 printf("File paths obstructed by a non-regular file: %d\n",
3297 upa->obstructed);
3298 if (upa->not_updated > 0)
3299 printf("Files not updated because of existing merge "
3300 "conflicts: %d\n", upa->not_updated);
3304 * The meaning of some status codes differs between merge-style operations and
3305 * update operations. For example, the ! status code means "file was missing"
3306 * if changes were merged into the work tree, and "missing file was restored"
3307 * if the work tree was updated. This function should be used by any operation
3308 * which merges changes into the work tree without updating the work tree.
3310 static void
3311 print_merge_progress_stats(struct got_update_progress_arg *upa)
3313 if (!upa->did_something)
3314 return;
3316 if (upa->conflicts > 0)
3317 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3318 if (upa->obstructed > 0)
3319 printf("File paths obstructed by a non-regular file: %d\n",
3320 upa->obstructed);
3321 if (upa->missing > 0)
3322 printf("Files which had incoming changes but could not be "
3323 "found in the work tree: %d\n", upa->missing);
3324 if (upa->not_deleted > 0)
3325 printf("Files not deleted due to differences in deleted "
3326 "content: %d\n", upa->not_deleted);
3327 if (upa->unversioned > 0)
3328 printf("Files not merged because an unversioned file was "
3329 "found in the work tree: %d\n", upa->unversioned);
3332 __dead static void
3333 usage_update(void)
3335 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3336 "[path ...]\n", getprogname());
3337 exit(1);
3340 static const struct got_error *
3341 update_progress(void *arg, unsigned char status, const char *path)
3343 struct got_update_progress_arg *upa = arg;
3345 if (status == GOT_STATUS_EXISTS ||
3346 status == GOT_STATUS_BASE_REF_ERR)
3347 return NULL;
3349 upa->did_something = 1;
3351 /* Base commit bump happens silently. */
3352 if (status == GOT_STATUS_BUMP_BASE)
3353 return NULL;
3355 if (status == GOT_STATUS_CONFLICT)
3356 upa->conflicts++;
3357 if (status == GOT_STATUS_OBSTRUCTED)
3358 upa->obstructed++;
3359 if (status == GOT_STATUS_CANNOT_UPDATE)
3360 upa->not_updated++;
3361 if (status == GOT_STATUS_MISSING)
3362 upa->missing++;
3363 if (status == GOT_STATUS_CANNOT_DELETE)
3364 upa->not_deleted++;
3365 if (status == GOT_STATUS_UNVERSIONED)
3366 upa->unversioned++;
3368 while (path[0] == '/')
3369 path++;
3370 if (upa->verbosity >= 0)
3371 printf("%c %s\n", status, path);
3373 return NULL;
3376 static const struct got_error *
3377 switch_head_ref(struct got_reference *head_ref,
3378 struct got_object_id *commit_id, struct got_worktree *worktree,
3379 struct got_repository *repo)
3381 const struct got_error *err = NULL;
3382 char *base_id_str;
3383 int ref_has_moved = 0;
3385 /* Trivial case: switching between two different references. */
3386 if (strcmp(got_ref_get_name(head_ref),
3387 got_worktree_get_head_ref_name(worktree)) != 0) {
3388 printf("Switching work tree from %s to %s\n",
3389 got_worktree_get_head_ref_name(worktree),
3390 got_ref_get_name(head_ref));
3391 return got_worktree_set_head_ref(worktree, head_ref);
3394 err = check_linear_ancestry(commit_id,
3395 got_worktree_get_base_commit_id(worktree), 0, repo);
3396 if (err) {
3397 if (err->code != GOT_ERR_ANCESTRY)
3398 return err;
3399 ref_has_moved = 1;
3401 if (!ref_has_moved)
3402 return NULL;
3404 /* Switching to a rebased branch with the same reference name. */
3405 err = got_object_id_str(&base_id_str,
3406 got_worktree_get_base_commit_id(worktree));
3407 if (err)
3408 return err;
3409 printf("Reference %s now points at a different branch\n",
3410 got_worktree_get_head_ref_name(worktree));
3411 printf("Switching work tree from %s to %s\n", base_id_str,
3412 got_worktree_get_head_ref_name(worktree));
3413 return NULL;
3416 static const struct got_error *
3417 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3419 const struct got_error *err;
3420 int in_progress;
3422 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3423 if (err)
3424 return err;
3425 if (in_progress)
3426 return got_error(GOT_ERR_REBASING);
3428 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3429 if (err)
3430 return err;
3431 if (in_progress)
3432 return got_error(GOT_ERR_HISTEDIT_BUSY);
3434 return NULL;
3437 static const struct got_error *
3438 check_merge_in_progress(struct got_worktree *worktree,
3439 struct got_repository *repo)
3441 const struct got_error *err;
3442 int in_progress;
3444 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3445 if (err)
3446 return err;
3447 if (in_progress)
3448 return got_error(GOT_ERR_MERGE_BUSY);
3450 return NULL;
3453 static const struct got_error *
3454 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3455 char *argv[], struct got_worktree *worktree)
3457 const struct got_error *err = NULL;
3458 char *path;
3459 struct got_pathlist_entry *new;
3460 int i;
3462 if (argc == 0) {
3463 path = strdup("");
3464 if (path == NULL)
3465 return got_error_from_errno("strdup");
3466 return got_pathlist_append(paths, path, NULL);
3469 for (i = 0; i < argc; i++) {
3470 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3471 if (err)
3472 break;
3473 err = got_pathlist_insert(&new, paths, path, NULL);
3474 if (err || new == NULL /* duplicate */) {
3475 free(path);
3476 if (err)
3477 break;
3481 return err;
3484 static const struct got_error *
3485 wrap_not_worktree_error(const struct got_error *orig_err,
3486 const char *cmdname, const char *path)
3488 const struct got_error *err;
3489 struct got_repository *repo;
3490 static char msg[512];
3491 int *pack_fds = NULL;
3493 err = got_repo_pack_fds_open(&pack_fds);
3494 if (err)
3495 return err;
3497 err = got_repo_open(&repo, path, NULL, pack_fds);
3498 if (err)
3499 return orig_err;
3501 snprintf(msg, sizeof(msg),
3502 "'got %s' needs a work tree in addition to a git repository\n"
3503 "Work trees can be checked out from this Git repository with "
3504 "'got checkout'.\n"
3505 "The got(1) manual page contains more information.", cmdname);
3506 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3507 if (repo) {
3508 const struct got_error *close_err = got_repo_close(repo);
3509 if (err == NULL)
3510 err = close_err;
3512 if (pack_fds) {
3513 const struct got_error *pack_err =
3514 got_repo_pack_fds_close(pack_fds);
3515 if (err == NULL)
3516 err = pack_err;
3518 return err;
3521 static const struct got_error *
3522 cmd_update(int argc, char *argv[])
3524 const struct got_error *close_err, *error = NULL;
3525 struct got_repository *repo = NULL;
3526 struct got_worktree *worktree = NULL;
3527 char *worktree_path = NULL;
3528 struct got_object_id *commit_id = NULL;
3529 char *commit_id_str = NULL;
3530 const char *branch_name = NULL;
3531 struct got_reference *head_ref = NULL;
3532 struct got_pathlist_head paths;
3533 struct got_pathlist_entry *pe;
3534 int ch, verbosity = 0;
3535 struct got_update_progress_arg upa;
3536 int *pack_fds = NULL;
3538 TAILQ_INIT(&paths);
3540 #ifndef PROFILE
3541 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3542 "unveil", NULL) == -1)
3543 err(1, "pledge");
3544 #endif
3546 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3547 switch (ch) {
3548 case 'b':
3549 branch_name = optarg;
3550 break;
3551 case 'c':
3552 commit_id_str = strdup(optarg);
3553 if (commit_id_str == NULL)
3554 return got_error_from_errno("strdup");
3555 break;
3556 case 'q':
3557 verbosity = -1;
3558 break;
3559 default:
3560 usage_update();
3561 /* NOTREACHED */
3565 argc -= optind;
3566 argv += optind;
3568 worktree_path = getcwd(NULL, 0);
3569 if (worktree_path == NULL) {
3570 error = got_error_from_errno("getcwd");
3571 goto done;
3574 error = got_repo_pack_fds_open(&pack_fds);
3575 if (error != NULL)
3576 goto done;
3578 error = got_worktree_open(&worktree, worktree_path,
3579 GOT_WORKTREE_GOT_DIR);
3580 if (error) {
3581 if (error->code == GOT_ERR_NOT_WORKTREE)
3582 error = wrap_not_worktree_error(error, "update",
3583 worktree_path);
3584 goto done;
3587 error = check_rebase_or_histedit_in_progress(worktree);
3588 if (error)
3589 goto done;
3591 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3592 NULL, pack_fds);
3593 if (error != NULL)
3594 goto done;
3596 error = apply_unveil(got_repo_get_path(repo), 0,
3597 got_worktree_get_root_path(worktree));
3598 if (error)
3599 goto done;
3601 error = check_merge_in_progress(worktree, repo);
3602 if (error)
3603 goto done;
3605 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3606 if (error)
3607 goto done;
3609 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3610 got_worktree_get_head_ref_name(worktree), 0);
3611 if (error != NULL)
3612 goto done;
3613 if (commit_id_str == NULL) {
3614 error = got_ref_resolve(&commit_id, repo, head_ref);
3615 if (error != NULL)
3616 goto done;
3617 error = got_object_id_str(&commit_id_str, commit_id);
3618 if (error != NULL)
3619 goto done;
3620 } else {
3621 struct got_reflist_head refs;
3622 char *keyword_idstr = NULL;
3624 TAILQ_INIT(&refs);
3626 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3627 NULL);
3628 if (error)
3629 goto done;
3631 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3632 repo, worktree);
3633 if (error != NULL)
3634 goto done;
3635 if (keyword_idstr != NULL) {
3636 free(commit_id_str);
3637 commit_id_str = keyword_idstr;
3640 error = got_repo_match_object_id(&commit_id, NULL,
3641 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3642 got_ref_list_free(&refs);
3643 free(commit_id_str);
3644 commit_id_str = NULL;
3645 if (error)
3646 goto done;
3647 error = got_object_id_str(&commit_id_str, commit_id);
3648 if (error)
3649 goto done;
3652 if (branch_name) {
3653 struct got_object_id *head_commit_id;
3654 TAILQ_FOREACH(pe, &paths, entry) {
3655 if (pe->path_len == 0)
3656 continue;
3657 error = got_error_msg(GOT_ERR_BAD_PATH,
3658 "switching between branches requires that "
3659 "the entire work tree gets updated");
3660 goto done;
3662 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3663 if (error)
3664 goto done;
3665 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3666 repo);
3667 free(head_commit_id);
3668 if (error != NULL)
3669 goto done;
3670 error = check_same_branch(commit_id, head_ref, repo);
3671 if (error)
3672 goto done;
3673 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3674 if (error)
3675 goto done;
3676 } else {
3677 error = check_linear_ancestry(commit_id,
3678 got_worktree_get_base_commit_id(worktree), 0, repo);
3679 if (error != NULL) {
3680 if (error->code == GOT_ERR_ANCESTRY)
3681 error = got_error(GOT_ERR_BRANCH_MOVED);
3682 goto done;
3684 error = check_same_branch(commit_id, head_ref, repo);
3685 if (error)
3686 goto done;
3689 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3690 commit_id) != 0) {
3691 error = got_worktree_set_base_commit_id(worktree, repo,
3692 commit_id);
3693 if (error)
3694 goto done;
3697 memset(&upa, 0, sizeof(upa));
3698 upa.verbosity = verbosity;
3699 error = got_worktree_checkout_files(worktree, &paths, repo,
3700 update_progress, &upa, check_cancelled, NULL);
3701 if (error != NULL)
3702 goto done;
3704 if (upa.did_something) {
3705 printf("Updated to %s: %s\n",
3706 got_worktree_get_head_ref_name(worktree), commit_id_str);
3707 } else
3708 printf("Already up-to-date\n");
3710 print_update_progress_stats(&upa);
3711 done:
3712 if (pack_fds) {
3713 const struct got_error *pack_err =
3714 got_repo_pack_fds_close(pack_fds);
3715 if (error == NULL)
3716 error = pack_err;
3718 if (repo) {
3719 close_err = got_repo_close(repo);
3720 if (error == NULL)
3721 error = close_err;
3723 if (worktree != NULL) {
3724 close_err = got_worktree_close(worktree);
3725 if (error == NULL)
3726 error = close_err;
3728 if (head_ref != NULL)
3729 got_ref_close(head_ref);
3730 free(worktree_path);
3731 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3732 free(commit_id);
3733 free(commit_id_str);
3734 return error;
3737 static const struct got_error *
3738 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3739 const char *path, int diff_context, int ignore_whitespace,
3740 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3741 struct got_repository *repo, FILE *outfile)
3743 const struct got_error *err = NULL;
3744 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3745 FILE *f1 = NULL, *f2 = NULL;
3746 int fd1 = -1, fd2 = -1;
3748 fd1 = got_opentempfd();
3749 if (fd1 == -1)
3750 return got_error_from_errno("got_opentempfd");
3751 fd2 = got_opentempfd();
3752 if (fd2 == -1) {
3753 err = got_error_from_errno("got_opentempfd");
3754 goto done;
3757 if (blob_id1) {
3758 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3759 fd1);
3760 if (err)
3761 goto done;
3764 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3765 if (err)
3766 goto done;
3768 f1 = got_opentemp();
3769 if (f1 == NULL) {
3770 err = got_error_from_errno("got_opentemp");
3771 goto done;
3773 f2 = got_opentemp();
3774 if (f2 == NULL) {
3775 err = got_error_from_errno("got_opentemp");
3776 goto done;
3779 while (path[0] == '/')
3780 path++;
3781 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3782 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3783 force_text_diff, dsa, outfile);
3784 done:
3785 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3786 err = got_error_from_errno("close");
3787 if (blob1)
3788 got_object_blob_close(blob1);
3789 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3790 err = got_error_from_errno("close");
3791 if (blob2)
3792 got_object_blob_close(blob2);
3793 if (f1 && fclose(f1) == EOF && err == NULL)
3794 err = got_error_from_errno("fclose");
3795 if (f2 && fclose(f2) == EOF && err == NULL)
3796 err = got_error_from_errno("fclose");
3797 return err;
3800 static const struct got_error *
3801 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3802 const char *path, int diff_context, int ignore_whitespace,
3803 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3804 struct got_repository *repo, FILE *outfile)
3806 const struct got_error *err = NULL;
3807 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3808 struct got_diff_blob_output_unidiff_arg arg;
3809 FILE *f1 = NULL, *f2 = NULL;
3810 int fd1 = -1, fd2 = -1;
3812 if (tree_id1) {
3813 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3814 if (err)
3815 goto done;
3816 fd1 = got_opentempfd();
3817 if (fd1 == -1) {
3818 err = got_error_from_errno("got_opentempfd");
3819 goto done;
3823 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3824 if (err)
3825 goto done;
3827 f1 = got_opentemp();
3828 if (f1 == NULL) {
3829 err = got_error_from_errno("got_opentemp");
3830 goto done;
3833 f2 = got_opentemp();
3834 if (f2 == NULL) {
3835 err = got_error_from_errno("got_opentemp");
3836 goto done;
3838 fd2 = got_opentempfd();
3839 if (fd2 == -1) {
3840 err = got_error_from_errno("got_opentempfd");
3841 goto done;
3843 arg.diff_context = diff_context;
3844 arg.ignore_whitespace = ignore_whitespace;
3845 arg.force_text_diff = force_text_diff;
3846 arg.diffstat = dsa;
3847 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3848 arg.outfile = outfile;
3849 arg.lines = NULL;
3850 arg.nlines = 0;
3851 while (path[0] == '/')
3852 path++;
3853 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3854 got_diff_blob_output_unidiff, &arg, 1);
3855 done:
3856 if (tree1)
3857 got_object_tree_close(tree1);
3858 if (tree2)
3859 got_object_tree_close(tree2);
3860 if (f1 && fclose(f1) == EOF && err == NULL)
3861 err = got_error_from_errno("fclose");
3862 if (f2 && fclose(f2) == EOF && err == NULL)
3863 err = got_error_from_errno("fclose");
3864 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3865 err = got_error_from_errno("close");
3866 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3867 err = got_error_from_errno("close");
3868 return err;
3871 static const struct got_error *
3872 get_changed_paths(struct got_pathlist_head *paths,
3873 struct got_commit_object *commit, struct got_repository *repo,
3874 struct got_diffstat_cb_arg *dsa)
3876 const struct got_error *err = NULL;
3877 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3878 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3879 struct got_object_qid *qid;
3880 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3881 FILE *f1 = NULL, *f2 = NULL;
3882 int fd1 = -1, fd2 = -1;
3884 if (dsa) {
3885 cb = got_diff_tree_compute_diffstat;
3887 f1 = got_opentemp();
3888 if (f1 == NULL) {
3889 err = got_error_from_errno("got_opentemp");
3890 goto done;
3892 f2 = got_opentemp();
3893 if (f2 == NULL) {
3894 err = got_error_from_errno("got_opentemp");
3895 goto done;
3897 fd1 = got_opentempfd();
3898 if (fd1 == -1) {
3899 err = got_error_from_errno("got_opentempfd");
3900 goto done;
3902 fd2 = got_opentempfd();
3903 if (fd2 == -1) {
3904 err = got_error_from_errno("got_opentempfd");
3905 goto done;
3909 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3910 if (qid != NULL) {
3911 struct got_commit_object *pcommit;
3912 err = got_object_open_as_commit(&pcommit, repo,
3913 &qid->id);
3914 if (err)
3915 return err;
3917 tree_id1 = got_object_id_dup(
3918 got_object_commit_get_tree_id(pcommit));
3919 if (tree_id1 == NULL) {
3920 got_object_commit_close(pcommit);
3921 return got_error_from_errno("got_object_id_dup");
3923 got_object_commit_close(pcommit);
3927 if (tree_id1) {
3928 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3929 if (err)
3930 goto done;
3933 tree_id2 = got_object_commit_get_tree_id(commit);
3934 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3935 if (err)
3936 goto done;
3938 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3939 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3940 done:
3941 if (tree1)
3942 got_object_tree_close(tree1);
3943 if (tree2)
3944 got_object_tree_close(tree2);
3945 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3946 err = got_error_from_errno("close");
3947 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3948 err = got_error_from_errno("close");
3949 if (f1 && fclose(f1) == EOF && err == NULL)
3950 err = got_error_from_errno("fclose");
3951 if (f2 && fclose(f2) == EOF && err == NULL)
3952 err = got_error_from_errno("fclose");
3953 free(tree_id1);
3954 return err;
3957 static const struct got_error *
3958 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3959 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3960 struct got_repository *repo, FILE *outfile)
3962 const struct got_error *err = NULL;
3963 struct got_commit_object *pcommit = NULL;
3964 char *id_str1 = NULL, *id_str2 = NULL;
3965 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3966 struct got_object_qid *qid;
3968 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3969 if (qid != NULL) {
3970 err = got_object_open_as_commit(&pcommit, repo,
3971 &qid->id);
3972 if (err)
3973 return err;
3974 err = got_object_id_str(&id_str1, &qid->id);
3975 if (err)
3976 goto done;
3979 err = got_object_id_str(&id_str2, id);
3980 if (err)
3981 goto done;
3983 if (path && path[0] != '\0') {
3984 int obj_type;
3985 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3986 if (err)
3987 goto done;
3988 if (pcommit) {
3989 err = got_object_id_by_path(&obj_id1, repo,
3990 pcommit, path);
3991 if (err) {
3992 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3993 free(obj_id2);
3994 goto done;
3998 err = got_object_get_type(&obj_type, repo, obj_id2);
3999 if (err) {
4000 free(obj_id2);
4001 goto done;
4003 fprintf(outfile,
4004 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4005 fprintf(outfile, "commit - %s\n",
4006 id_str1 ? id_str1 : "/dev/null");
4007 fprintf(outfile, "commit + %s\n", id_str2);
4008 switch (obj_type) {
4009 case GOT_OBJ_TYPE_BLOB:
4010 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4011 0, 0, dsa, repo, outfile);
4012 break;
4013 case GOT_OBJ_TYPE_TREE:
4014 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4015 0, 0, dsa, repo, outfile);
4016 break;
4017 default:
4018 err = got_error(GOT_ERR_OBJ_TYPE);
4019 break;
4021 free(obj_id1);
4022 free(obj_id2);
4023 } else {
4024 obj_id2 = got_object_commit_get_tree_id(commit);
4025 if (pcommit)
4026 obj_id1 = got_object_commit_get_tree_id(pcommit);
4027 fprintf(outfile,
4028 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4029 fprintf(outfile, "commit - %s\n",
4030 id_str1 ? id_str1 : "/dev/null");
4031 fprintf(outfile, "commit + %s\n", id_str2);
4032 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4033 dsa, repo, outfile);
4035 done:
4036 free(id_str1);
4037 free(id_str2);
4038 if (pcommit)
4039 got_object_commit_close(pcommit);
4040 return err;
4043 static char *
4044 get_datestr(time_t *time, char *datebuf)
4046 struct tm mytm, *tm;
4047 char *p, *s;
4049 tm = gmtime_r(time, &mytm);
4050 if (tm == NULL)
4051 return NULL;
4052 s = asctime_r(tm, datebuf);
4053 if (s == NULL)
4054 return NULL;
4055 p = strchr(s, '\n');
4056 if (p)
4057 *p = '\0';
4058 return s;
4061 static const struct got_error *
4062 match_commit(int *have_match, struct got_object_id *id,
4063 struct got_commit_object *commit, regex_t *regex)
4065 const struct got_error *err = NULL;
4066 regmatch_t regmatch;
4067 char *id_str = NULL, *logmsg = NULL;
4069 *have_match = 0;
4071 err = got_object_id_str(&id_str, id);
4072 if (err)
4073 return err;
4075 err = got_object_commit_get_logmsg(&logmsg, commit);
4076 if (err)
4077 goto done;
4079 if (regexec(regex, got_object_commit_get_author(commit), 1,
4080 &regmatch, 0) == 0 ||
4081 regexec(regex, got_object_commit_get_committer(commit), 1,
4082 &regmatch, 0) == 0 ||
4083 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4084 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4085 *have_match = 1;
4086 done:
4087 free(id_str);
4088 free(logmsg);
4089 return err;
4092 static void
4093 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4094 regex_t *regex)
4096 regmatch_t regmatch;
4097 struct got_pathlist_entry *pe;
4099 *have_match = 0;
4101 TAILQ_FOREACH(pe, changed_paths, entry) {
4102 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4103 *have_match = 1;
4104 break;
4109 static const struct got_error *
4110 match_patch(int *have_match, struct got_commit_object *commit,
4111 struct got_object_id *id, const char *path, int diff_context,
4112 struct got_repository *repo, regex_t *regex, FILE *f)
4114 const struct got_error *err = NULL;
4115 char *line = NULL;
4116 size_t linesize = 0;
4117 regmatch_t regmatch;
4119 *have_match = 0;
4121 err = got_opentemp_truncate(f);
4122 if (err)
4123 return err;
4125 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4126 if (err)
4127 goto done;
4129 if (fseeko(f, 0L, SEEK_SET) == -1) {
4130 err = got_error_from_errno("fseeko");
4131 goto done;
4134 while (getline(&line, &linesize, f) != -1) {
4135 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4136 *have_match = 1;
4137 break;
4140 done:
4141 free(line);
4142 return err;
4145 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4147 static const struct got_error*
4148 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4149 struct got_object_id *id, struct got_repository *repo,
4150 int local_only)
4152 static const struct got_error *err = NULL;
4153 struct got_reflist_entry *re;
4154 char *s;
4155 const char *name;
4157 *refs_str = NULL;
4159 TAILQ_FOREACH(re, refs, entry) {
4160 struct got_tag_object *tag = NULL;
4161 struct got_object_id *ref_id;
4162 int cmp;
4164 name = got_ref_get_name(re->ref);
4165 if (strcmp(name, GOT_REF_HEAD) == 0)
4166 continue;
4167 if (strncmp(name, "refs/", 5) == 0)
4168 name += 5;
4169 if (strncmp(name, "got/", 4) == 0)
4170 continue;
4171 if (strncmp(name, "heads/", 6) == 0)
4172 name += 6;
4173 if (strncmp(name, "remotes/", 8) == 0) {
4174 if (local_only)
4175 continue;
4176 name += 8;
4177 s = strstr(name, "/" GOT_REF_HEAD);
4178 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4179 continue;
4181 err = got_ref_resolve(&ref_id, repo, re->ref);
4182 if (err)
4183 break;
4184 if (strncmp(name, "tags/", 5) == 0) {
4185 err = got_object_open_as_tag(&tag, repo, ref_id);
4186 if (err) {
4187 if (err->code != GOT_ERR_OBJ_TYPE) {
4188 free(ref_id);
4189 break;
4191 /* Ref points at something other than a tag. */
4192 err = NULL;
4193 tag = NULL;
4196 cmp = got_object_id_cmp(tag ?
4197 got_object_tag_get_object_id(tag) : ref_id, id);
4198 free(ref_id);
4199 if (tag)
4200 got_object_tag_close(tag);
4201 if (cmp != 0)
4202 continue;
4203 s = *refs_str;
4204 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4205 s ? ", " : "", name) == -1) {
4206 err = got_error_from_errno("asprintf");
4207 free(s);
4208 *refs_str = NULL;
4209 break;
4211 free(s);
4214 return err;
4217 static const struct got_error *
4218 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4219 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4221 const struct got_error *err = NULL;
4222 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4223 char *comma, *s, *nl;
4224 struct got_reflist_head *refs;
4225 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4226 struct tm tm;
4227 time_t committer_time;
4229 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4230 if (refs) {
4231 err = build_refs_str(&ref_str, refs, id, repo, 1);
4232 if (err)
4233 return err;
4235 /* Display the first matching ref only. */
4236 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4237 *comma = '\0';
4240 if (ref_str == NULL) {
4241 err = got_object_id_str(&id_str, id);
4242 if (err)
4243 return err;
4246 committer_time = got_object_commit_get_committer_time(commit);
4247 if (gmtime_r(&committer_time, &tm) == NULL) {
4248 err = got_error_from_errno("gmtime_r");
4249 goto done;
4251 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4252 err = got_error(GOT_ERR_NO_SPACE);
4253 goto done;
4256 err = got_object_commit_get_logmsg(&logmsg0, commit);
4257 if (err)
4258 goto done;
4260 s = logmsg0;
4261 while (isspace((unsigned char)s[0]))
4262 s++;
4264 nl = strchr(s, '\n');
4265 if (nl) {
4266 *nl = '\0';
4269 if (ref_str)
4270 printf("%s%-7s %s\n", datebuf, ref_str, s);
4271 else
4272 printf("%s%.7s %s\n", datebuf, id_str, s);
4274 if (fflush(stdout) != 0 && err == NULL)
4275 err = got_error_from_errno("fflush");
4276 done:
4277 free(id_str);
4278 free(ref_str);
4279 free(logmsg0);
4280 return err;
4283 static const struct got_error *
4284 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4286 struct got_pathlist_entry *pe;
4288 if (header != NULL)
4289 printf("%s\n", header);
4291 TAILQ_FOREACH(pe, dsa->paths, entry) {
4292 struct got_diff_changed_path *cp = pe->data;
4293 int pad = dsa->max_path_len - pe->path_len + 1;
4295 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4296 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4298 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4299 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4300 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4302 if (fflush(stdout) != 0)
4303 return got_error_from_errno("fflush");
4305 return NULL;
4308 static const struct got_error *
4309 printfile(FILE *f)
4311 char buf[8192];
4312 size_t r;
4314 if (fseeko(f, 0L, SEEK_SET) == -1)
4315 return got_error_from_errno("fseek");
4317 for (;;) {
4318 r = fread(buf, 1, sizeof(buf), f);
4319 if (r == 0) {
4320 if (ferror(f))
4321 return got_error_from_errno("fread");
4322 if (feof(f))
4323 break;
4325 if (fwrite(buf, 1, r, stdout) != r)
4326 return got_ferror(stdout, GOT_ERR_IO);
4329 return NULL;
4332 static const struct got_error *
4333 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4334 struct got_repository *repo, const char *path,
4335 struct got_pathlist_head *changed_paths,
4336 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4337 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4338 const char *prefix)
4340 const struct got_error *err = NULL;
4341 FILE *f = NULL;
4342 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4343 char datebuf[26];
4344 time_t committer_time;
4345 const char *author, *committer;
4346 char *refs_str = NULL;
4348 err = got_object_id_str(&id_str, id);
4349 if (err)
4350 return err;
4352 if (custom_refs_str == NULL) {
4353 struct got_reflist_head *refs;
4354 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4355 if (refs) {
4356 err = build_refs_str(&refs_str, refs, id, repo, 0);
4357 if (err)
4358 goto done;
4362 printf(GOT_COMMIT_SEP_STR);
4363 if (custom_refs_str)
4364 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4365 custom_refs_str);
4366 else
4367 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4368 refs_str ? " (" : "", refs_str ? refs_str : "",
4369 refs_str ? ")" : "");
4370 free(id_str);
4371 id_str = NULL;
4372 free(refs_str);
4373 refs_str = NULL;
4374 printf("from: %s\n", got_object_commit_get_author(commit));
4375 author = got_object_commit_get_author(commit);
4376 committer = got_object_commit_get_committer(commit);
4377 if (strcmp(author, committer) != 0)
4378 printf("via: %s\n", committer);
4379 committer_time = got_object_commit_get_committer_time(commit);
4380 datestr = get_datestr(&committer_time, datebuf);
4381 if (datestr)
4382 printf("date: %s UTC\n", datestr);
4383 if (got_object_commit_get_nparents(commit) > 1) {
4384 const struct got_object_id_queue *parent_ids;
4385 struct got_object_qid *qid;
4386 int n = 1;
4387 parent_ids = got_object_commit_get_parent_ids(commit);
4388 STAILQ_FOREACH(qid, parent_ids, entry) {
4389 err = got_object_id_str(&id_str, &qid->id);
4390 if (err)
4391 goto done;
4392 printf("parent %d: %s\n", n++, id_str);
4393 free(id_str);
4394 id_str = NULL;
4398 err = got_object_commit_get_logmsg(&logmsg0, commit);
4399 if (err)
4400 goto done;
4402 logmsg = logmsg0;
4403 do {
4404 line = strsep(&logmsg, "\n");
4405 if (line)
4406 printf(" %s\n", line);
4407 } while (line);
4408 free(logmsg0);
4410 if (changed_paths && diffstat == NULL) {
4411 struct got_pathlist_entry *pe;
4413 TAILQ_FOREACH(pe, changed_paths, entry) {
4414 struct got_diff_changed_path *cp = pe->data;
4416 printf(" %c %s\n", cp->status, pe->path);
4418 printf("\n");
4420 if (show_patch) {
4421 if (diffstat) {
4422 f = got_opentemp();
4423 if (f == NULL) {
4424 err = got_error_from_errno("got_opentemp");
4425 goto done;
4429 err = print_patch(commit, id, path, diff_context, diffstat,
4430 repo, diffstat == NULL ? stdout : f);
4431 if (err)
4432 goto done;
4434 if (diffstat) {
4435 err = print_diffstat(diffstat, NULL);
4436 if (err)
4437 goto done;
4438 if (show_patch) {
4439 err = printfile(f);
4440 if (err)
4441 goto done;
4444 if (show_patch)
4445 printf("\n");
4447 if (fflush(stdout) != 0 && err == NULL)
4448 err = got_error_from_errno("fflush");
4449 done:
4450 if (f && fclose(f) == EOF && err == NULL)
4451 err = got_error_from_errno("fclose");
4452 free(id_str);
4453 free(refs_str);
4454 return err;
4457 static const struct got_error *
4458 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4459 struct got_repository *repo, const char *path, int show_changed_paths,
4460 int show_diffstat, int show_patch, const char *search_pattern,
4461 int diff_context, int limit, int log_branches, int reverse_display_order,
4462 struct got_reflist_object_id_map *refs_idmap, int one_line,
4463 FILE *tmpfile)
4465 const struct got_error *err;
4466 struct got_commit_graph *graph;
4467 regex_t regex;
4468 int have_match;
4469 struct got_object_id_queue reversed_commits;
4470 struct got_object_qid *qid;
4471 struct got_commit_object *commit;
4472 struct got_pathlist_head changed_paths;
4474 STAILQ_INIT(&reversed_commits);
4475 TAILQ_INIT(&changed_paths);
4477 if (search_pattern && regcomp(&regex, search_pattern,
4478 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4479 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4481 err = got_commit_graph_open(&graph, path, !log_branches);
4482 if (err)
4483 return err;
4484 err = got_commit_graph_iter_start(graph, root_id, repo,
4485 check_cancelled, NULL);
4486 if (err)
4487 goto done;
4488 for (;;) {
4489 struct got_object_id id;
4490 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4491 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4493 if (sigint_received || sigpipe_received)
4494 break;
4496 err = got_commit_graph_iter_next(&id, graph, repo,
4497 check_cancelled, NULL);
4498 if (err) {
4499 if (err->code == GOT_ERR_ITER_COMPLETED)
4500 err = NULL;
4501 break;
4504 err = got_object_open_as_commit(&commit, repo, &id);
4505 if (err)
4506 break;
4508 if (((show_changed_paths && !show_diffstat) ||
4509 (show_diffstat && !show_patch))
4510 && !reverse_display_order) {
4511 err = get_changed_paths(&changed_paths, commit, repo,
4512 show_diffstat ? &dsa : NULL);
4513 if (err)
4514 break;
4517 if (search_pattern) {
4518 err = match_commit(&have_match, &id, commit, &regex);
4519 if (err) {
4520 got_object_commit_close(commit);
4521 break;
4523 if (have_match == 0 && show_changed_paths)
4524 match_changed_paths(&have_match,
4525 &changed_paths, &regex);
4526 if (have_match == 0 && show_patch) {
4527 err = match_patch(&have_match, commit, &id,
4528 path, diff_context, repo, &regex, tmpfile);
4529 if (err)
4530 break;
4532 if (have_match == 0) {
4533 got_object_commit_close(commit);
4534 got_pathlist_free(&changed_paths,
4535 GOT_PATHLIST_FREE_ALL);
4536 continue;
4540 if (reverse_display_order) {
4541 err = got_object_qid_alloc(&qid, &id);
4542 if (err)
4543 break;
4544 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4545 got_object_commit_close(commit);
4546 } else {
4547 if (one_line)
4548 err = print_commit_oneline(commit, &id,
4549 repo, refs_idmap);
4550 else
4551 err = print_commit(commit, &id, repo, path,
4552 (show_changed_paths || show_diffstat) ?
4553 &changed_paths : NULL,
4554 show_diffstat ? &dsa : NULL, show_patch,
4555 diff_context, refs_idmap, NULL, NULL);
4556 got_object_commit_close(commit);
4557 if (err)
4558 break;
4560 if ((limit && --limit == 0) ||
4561 (end_id && got_object_id_cmp(&id, end_id) == 0))
4562 break;
4564 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4566 if (reverse_display_order) {
4567 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4568 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4569 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4571 err = got_object_open_as_commit(&commit, repo,
4572 &qid->id);
4573 if (err)
4574 break;
4575 if ((show_changed_paths && !show_diffstat) ||
4576 (show_diffstat && !show_patch)) {
4577 err = get_changed_paths(&changed_paths, commit,
4578 repo, show_diffstat ? &dsa : NULL);
4579 if (err)
4580 break;
4582 if (one_line)
4583 err = print_commit_oneline(commit, &qid->id,
4584 repo, refs_idmap);
4585 else
4586 err = print_commit(commit, &qid->id, repo, path,
4587 (show_changed_paths || show_diffstat) ?
4588 &changed_paths : NULL,
4589 show_diffstat ? &dsa : NULL, show_patch,
4590 diff_context, refs_idmap, NULL, NULL);
4591 got_object_commit_close(commit);
4592 if (err)
4593 break;
4594 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4597 done:
4598 while (!STAILQ_EMPTY(&reversed_commits)) {
4599 qid = STAILQ_FIRST(&reversed_commits);
4600 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4601 got_object_qid_free(qid);
4603 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4604 if (search_pattern)
4605 regfree(&regex);
4606 got_commit_graph_close(graph);
4607 return err;
4610 __dead static void
4611 usage_log(void)
4613 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4614 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4615 "[path]\n", getprogname());
4616 exit(1);
4619 static int
4620 get_default_log_limit(void)
4622 const char *got_default_log_limit;
4623 long long n;
4624 const char *errstr;
4626 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4627 if (got_default_log_limit == NULL)
4628 return 0;
4629 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4630 if (errstr != NULL)
4631 return 0;
4632 return n;
4635 static const struct got_error *
4636 cmd_log(int argc, char *argv[])
4638 const struct got_error *error;
4639 struct got_repository *repo = NULL;
4640 struct got_worktree *worktree = NULL;
4641 struct got_object_id *start_id = NULL, *end_id = NULL;
4642 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4643 char *keyword_idstr = NULL;
4644 const char *start_commit = NULL, *end_commit = NULL;
4645 const char *search_pattern = NULL;
4646 int diff_context = -1, ch;
4647 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4648 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4649 const char *errstr;
4650 struct got_reflist_head refs;
4651 struct got_reflist_object_id_map *refs_idmap = NULL;
4652 FILE *tmpfile = NULL;
4653 int *pack_fds = NULL;
4655 TAILQ_INIT(&refs);
4657 #ifndef PROFILE
4658 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4659 NULL)
4660 == -1)
4661 err(1, "pledge");
4662 #endif
4664 limit = get_default_log_limit();
4666 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4667 switch (ch) {
4668 case 'b':
4669 log_branches = 1;
4670 break;
4671 case 'C':
4672 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4673 &errstr);
4674 if (errstr != NULL)
4675 errx(1, "number of context lines is %s: %s",
4676 errstr, optarg);
4677 break;
4678 case 'c':
4679 start_commit = optarg;
4680 break;
4681 case 'd':
4682 show_diffstat = 1;
4683 break;
4684 case 'l':
4685 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4686 if (errstr != NULL)
4687 errx(1, "number of commits is %s: %s",
4688 errstr, optarg);
4689 break;
4690 case 'P':
4691 show_changed_paths = 1;
4692 break;
4693 case 'p':
4694 show_patch = 1;
4695 break;
4696 case 'R':
4697 reverse_display_order = 1;
4698 break;
4699 case 'r':
4700 repo_path = realpath(optarg, NULL);
4701 if (repo_path == NULL)
4702 return got_error_from_errno2("realpath",
4703 optarg);
4704 got_path_strip_trailing_slashes(repo_path);
4705 break;
4706 case 'S':
4707 search_pattern = optarg;
4708 break;
4709 case 's':
4710 one_line = 1;
4711 break;
4712 case 'x':
4713 end_commit = optarg;
4714 break;
4715 default:
4716 usage_log();
4717 /* NOTREACHED */
4721 argc -= optind;
4722 argv += optind;
4724 if (diff_context == -1)
4725 diff_context = 3;
4726 else if (!show_patch)
4727 errx(1, "-C requires -p");
4729 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4730 errx(1, "cannot use -s with -d, -p or -P");
4732 cwd = getcwd(NULL, 0);
4733 if (cwd == NULL) {
4734 error = got_error_from_errno("getcwd");
4735 goto done;
4738 error = got_repo_pack_fds_open(&pack_fds);
4739 if (error != NULL)
4740 goto done;
4742 if (repo_path == NULL) {
4743 error = got_worktree_open(&worktree, cwd,
4744 GOT_WORKTREE_GOT_DIR);
4745 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4746 goto done;
4747 error = NULL;
4750 if (argc == 1) {
4751 if (worktree) {
4752 error = got_worktree_resolve_path(&path, worktree,
4753 argv[0]);
4754 if (error)
4755 goto done;
4756 } else {
4757 path = strdup(argv[0]);
4758 if (path == NULL) {
4759 error = got_error_from_errno("strdup");
4760 goto done;
4763 } else if (argc != 0)
4764 usage_log();
4766 if (repo_path == NULL) {
4767 repo_path = worktree ?
4768 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4770 if (repo_path == NULL) {
4771 error = got_error_from_errno("strdup");
4772 goto done;
4775 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4776 if (error != NULL)
4777 goto done;
4779 error = apply_unveil(got_repo_get_path(repo), 1,
4780 worktree ? got_worktree_get_root_path(worktree) : NULL);
4781 if (error)
4782 goto done;
4784 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4785 if (error)
4786 goto done;
4788 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4789 if (error)
4790 goto done;
4792 if (start_commit == NULL) {
4793 struct got_reference *head_ref;
4794 struct got_commit_object *commit = NULL;
4795 error = got_ref_open(&head_ref, repo,
4796 worktree ? got_worktree_get_head_ref_name(worktree)
4797 : GOT_REF_HEAD, 0);
4798 if (error != NULL)
4799 goto done;
4800 error = got_ref_resolve(&start_id, repo, head_ref);
4801 got_ref_close(head_ref);
4802 if (error != NULL)
4803 goto done;
4804 error = got_object_open_as_commit(&commit, repo,
4805 start_id);
4806 if (error != NULL)
4807 goto done;
4808 got_object_commit_close(commit);
4809 } else {
4810 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4811 repo, worktree);
4812 if (error != NULL)
4813 goto done;
4814 if (keyword_idstr != NULL)
4815 start_commit = keyword_idstr;
4817 error = got_repo_match_object_id(&start_id, NULL,
4818 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4819 if (error != NULL)
4820 goto done;
4822 if (end_commit != NULL) {
4823 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4824 repo, worktree);
4825 if (error != NULL)
4826 goto done;
4827 if (keyword_idstr != NULL)
4828 end_commit = keyword_idstr;
4830 error = got_repo_match_object_id(&end_id, NULL,
4831 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4832 if (error != NULL)
4833 goto done;
4836 if (worktree) {
4838 * If a path was specified on the command line it was resolved
4839 * to a path in the work tree above. Prepend the work tree's
4840 * path prefix to obtain the corresponding in-repository path.
4842 if (path) {
4843 const char *prefix;
4844 prefix = got_worktree_get_path_prefix(worktree);
4845 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4846 (path[0] != '\0') ? "/" : "", path) == -1) {
4847 error = got_error_from_errno("asprintf");
4848 goto done;
4851 } else
4852 error = got_repo_map_path(&in_repo_path, repo,
4853 path ? path : "");
4854 if (error != NULL)
4855 goto done;
4856 if (in_repo_path) {
4857 free(path);
4858 path = in_repo_path;
4861 if (worktree) {
4862 /* Release work tree lock. */
4863 got_worktree_close(worktree);
4864 worktree = NULL;
4867 if (search_pattern && show_patch) {
4868 tmpfile = got_opentemp();
4869 if (tmpfile == NULL) {
4870 error = got_error_from_errno("got_opentemp");
4871 goto done;
4875 error = print_commits(start_id, end_id, repo, path ? path : "",
4876 show_changed_paths, show_diffstat, show_patch, search_pattern,
4877 diff_context, limit, log_branches, reverse_display_order,
4878 refs_idmap, one_line, tmpfile);
4879 done:
4880 free(path);
4881 free(repo_path);
4882 free(cwd);
4883 free(start_id);
4884 free(end_id);
4885 free(keyword_idstr);
4886 if (worktree)
4887 got_worktree_close(worktree);
4888 if (repo) {
4889 const struct got_error *close_err = got_repo_close(repo);
4890 if (error == NULL)
4891 error = close_err;
4893 if (pack_fds) {
4894 const struct got_error *pack_err =
4895 got_repo_pack_fds_close(pack_fds);
4896 if (error == NULL)
4897 error = pack_err;
4899 if (refs_idmap)
4900 got_reflist_object_id_map_free(refs_idmap);
4901 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4902 error = got_error_from_errno("fclose");
4903 got_ref_list_free(&refs);
4904 return error;
4907 __dead static void
4908 usage_diff(void)
4910 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4911 "[-r repository-path] [object1 object2 | path ...]\n",
4912 getprogname());
4913 exit(1);
4916 struct print_diff_arg {
4917 struct got_repository *repo;
4918 struct got_worktree *worktree;
4919 struct got_diffstat_cb_arg *diffstat;
4920 int diff_context;
4921 const char *id_str;
4922 int header_shown;
4923 int diff_staged;
4924 enum got_diff_algorithm diff_algo;
4925 int ignore_whitespace;
4926 int force_text_diff;
4927 FILE *f1;
4928 FILE *f2;
4929 FILE *outfile;
4933 * Create a file which contains the target path of a symlink so we can feed
4934 * it as content to the diff engine.
4936 static const struct got_error *
4937 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4938 const char *abspath)
4940 const struct got_error *err = NULL;
4941 char target_path[PATH_MAX];
4942 ssize_t target_len, outlen;
4944 *fd = -1;
4946 if (dirfd != -1) {
4947 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4948 if (target_len == -1)
4949 return got_error_from_errno2("readlinkat", abspath);
4950 } else {
4951 target_len = readlink(abspath, target_path, PATH_MAX);
4952 if (target_len == -1)
4953 return got_error_from_errno2("readlink", abspath);
4956 *fd = got_opentempfd();
4957 if (*fd == -1)
4958 return got_error_from_errno("got_opentempfd");
4960 outlen = write(*fd, target_path, target_len);
4961 if (outlen == -1) {
4962 err = got_error_from_errno("got_opentempfd");
4963 goto done;
4966 if (lseek(*fd, 0, SEEK_SET) == -1) {
4967 err = got_error_from_errno2("lseek", abspath);
4968 goto done;
4970 done:
4971 if (err) {
4972 close(*fd);
4973 *fd = -1;
4975 return err;
4978 static const struct got_error *
4979 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4980 const char *path, struct got_object_id *blob_id,
4981 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4982 int dirfd, const char *de_name)
4984 struct print_diff_arg *a = arg;
4985 const struct got_error *err = NULL;
4986 struct got_blob_object *blob1 = NULL;
4987 int fd = -1, fd1 = -1, fd2 = -1;
4988 FILE *f2 = NULL;
4989 char *abspath = NULL, *label1 = NULL;
4990 struct stat sb;
4991 off_t size1 = 0;
4992 int f2_exists = 0;
4994 memset(&sb, 0, sizeof(sb));
4996 if (a->diff_staged) {
4997 if (staged_status != GOT_STATUS_MODIFY &&
4998 staged_status != GOT_STATUS_ADD &&
4999 staged_status != GOT_STATUS_DELETE)
5000 return NULL;
5001 } else {
5002 if (staged_status == GOT_STATUS_DELETE)
5003 return NULL;
5004 if (status == GOT_STATUS_NONEXISTENT)
5005 return got_error_set_errno(ENOENT, path);
5006 if (status != GOT_STATUS_MODIFY &&
5007 status != GOT_STATUS_ADD &&
5008 status != GOT_STATUS_DELETE &&
5009 status != GOT_STATUS_CONFLICT)
5010 return NULL;
5013 err = got_opentemp_truncate(a->f1);
5014 if (err)
5015 return got_error_from_errno("got_opentemp_truncate");
5016 err = got_opentemp_truncate(a->f2);
5017 if (err)
5018 return got_error_from_errno("got_opentemp_truncate");
5020 if (!a->header_shown) {
5021 if (fprintf(a->outfile, "diff %s%s\n",
5022 a->diff_staged ? "-s " : "",
5023 got_worktree_get_root_path(a->worktree)) < 0) {
5024 err = got_error_from_errno("fprintf");
5025 goto done;
5027 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5028 err = got_error_from_errno("fprintf");
5029 goto done;
5031 if (fprintf(a->outfile, "path + %s%s\n",
5032 got_worktree_get_root_path(a->worktree),
5033 a->diff_staged ? " (staged changes)" : "") < 0) {
5034 err = got_error_from_errno("fprintf");
5035 goto done;
5037 a->header_shown = 1;
5040 if (a->diff_staged) {
5041 const char *label1 = NULL, *label2 = NULL;
5042 switch (staged_status) {
5043 case GOT_STATUS_MODIFY:
5044 label1 = path;
5045 label2 = path;
5046 break;
5047 case GOT_STATUS_ADD:
5048 label2 = path;
5049 break;
5050 case GOT_STATUS_DELETE:
5051 label1 = path;
5052 break;
5053 default:
5054 return got_error(GOT_ERR_FILE_STATUS);
5056 fd1 = got_opentempfd();
5057 if (fd1 == -1) {
5058 err = got_error_from_errno("got_opentempfd");
5059 goto done;
5061 fd2 = got_opentempfd();
5062 if (fd2 == -1) {
5063 err = got_error_from_errno("got_opentempfd");
5064 goto done;
5066 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5067 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5068 a->diff_algo, a->diff_context, a->ignore_whitespace,
5069 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5070 goto done;
5073 fd1 = got_opentempfd();
5074 if (fd1 == -1) {
5075 err = got_error_from_errno("got_opentempfd");
5076 goto done;
5079 if (staged_status == GOT_STATUS_ADD ||
5080 staged_status == GOT_STATUS_MODIFY) {
5081 char *id_str;
5082 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5083 8192, fd1);
5084 if (err)
5085 goto done;
5086 err = got_object_id_str(&id_str, staged_blob_id);
5087 if (err)
5088 goto done;
5089 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5090 err = got_error_from_errno("asprintf");
5091 free(id_str);
5092 goto done;
5094 free(id_str);
5095 } else if (status != GOT_STATUS_ADD) {
5096 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5097 fd1);
5098 if (err)
5099 goto done;
5102 if (status != GOT_STATUS_DELETE) {
5103 if (asprintf(&abspath, "%s/%s",
5104 got_worktree_get_root_path(a->worktree), path) == -1) {
5105 err = got_error_from_errno("asprintf");
5106 goto done;
5109 if (dirfd != -1) {
5110 fd = openat(dirfd, de_name,
5111 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5112 if (fd == -1) {
5113 if (!got_err_open_nofollow_on_symlink()) {
5114 err = got_error_from_errno2("openat",
5115 abspath);
5116 goto done;
5118 err = get_symlink_target_file(&fd, dirfd,
5119 de_name, abspath);
5120 if (err)
5121 goto done;
5123 } else {
5124 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5125 if (fd == -1) {
5126 if (!got_err_open_nofollow_on_symlink()) {
5127 err = got_error_from_errno2("open",
5128 abspath);
5129 goto done;
5131 err = get_symlink_target_file(&fd, dirfd,
5132 de_name, abspath);
5133 if (err)
5134 goto done;
5137 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5138 err = got_error_from_errno2("fstatat", abspath);
5139 goto done;
5141 f2 = fdopen(fd, "r");
5142 if (f2 == NULL) {
5143 err = got_error_from_errno2("fdopen", abspath);
5144 goto done;
5146 fd = -1;
5147 f2_exists = 1;
5150 if (blob1) {
5151 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5152 a->f1, blob1);
5153 if (err)
5154 goto done;
5157 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5158 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5159 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5160 done:
5161 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5162 err = got_error_from_errno("close");
5163 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5164 err = got_error_from_errno("close");
5165 if (blob1)
5166 got_object_blob_close(blob1);
5167 if (fd != -1 && close(fd) == -1 && err == NULL)
5168 err = got_error_from_errno("close");
5169 if (f2 && fclose(f2) == EOF && err == NULL)
5170 err = got_error_from_errno("fclose");
5171 free(abspath);
5172 return err;
5175 static const struct got_error *
5176 cmd_diff(int argc, char *argv[])
5178 const struct got_error *error;
5179 struct got_repository *repo = NULL;
5180 struct got_worktree *worktree = NULL;
5181 char *cwd = NULL, *repo_path = NULL;
5182 const char *commit_args[2] = { NULL, NULL };
5183 int ncommit_args = 0;
5184 struct got_object_id *ids[2] = { NULL, NULL };
5185 char *labels[2] = { NULL, NULL };
5186 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5187 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5188 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5189 const char *errstr;
5190 struct got_reflist_head refs;
5191 struct got_pathlist_head diffstat_paths, paths;
5192 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5193 int fd1 = -1, fd2 = -1;
5194 int *pack_fds = NULL;
5195 struct got_diffstat_cb_arg dsa;
5197 memset(&dsa, 0, sizeof(dsa));
5199 TAILQ_INIT(&refs);
5200 TAILQ_INIT(&paths);
5201 TAILQ_INIT(&diffstat_paths);
5203 #ifndef PROFILE
5204 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5205 NULL) == -1)
5206 err(1, "pledge");
5207 #endif
5209 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5210 switch (ch) {
5211 case 'a':
5212 force_text_diff = 1;
5213 break;
5214 case 'C':
5215 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5216 &errstr);
5217 if (errstr != NULL)
5218 errx(1, "number of context lines is %s: %s",
5219 errstr, optarg);
5220 break;
5221 case 'c':
5222 if (ncommit_args >= 2)
5223 errx(1, "too many -c options used");
5224 commit_args[ncommit_args++] = optarg;
5225 break;
5226 case 'd':
5227 show_diffstat = 1;
5228 break;
5229 case 'P':
5230 force_path = 1;
5231 break;
5232 case 'r':
5233 repo_path = realpath(optarg, NULL);
5234 if (repo_path == NULL)
5235 return got_error_from_errno2("realpath",
5236 optarg);
5237 got_path_strip_trailing_slashes(repo_path);
5238 rflag = 1;
5239 break;
5240 case 's':
5241 diff_staged = 1;
5242 break;
5243 case 'w':
5244 ignore_whitespace = 1;
5245 break;
5246 default:
5247 usage_diff();
5248 /* NOTREACHED */
5252 argc -= optind;
5253 argv += optind;
5255 cwd = getcwd(NULL, 0);
5256 if (cwd == NULL) {
5257 error = got_error_from_errno("getcwd");
5258 goto done;
5261 error = got_repo_pack_fds_open(&pack_fds);
5262 if (error != NULL)
5263 goto done;
5265 if (repo_path == NULL) {
5266 error = got_worktree_open(&worktree, cwd,
5267 GOT_WORKTREE_GOT_DIR);
5268 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5269 goto done;
5270 else
5271 error = NULL;
5272 if (worktree) {
5273 repo_path =
5274 strdup(got_worktree_get_repo_path(worktree));
5275 if (repo_path == NULL) {
5276 error = got_error_from_errno("strdup");
5277 goto done;
5279 } else {
5280 repo_path = strdup(cwd);
5281 if (repo_path == NULL) {
5282 error = got_error_from_errno("strdup");
5283 goto done;
5288 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5289 free(repo_path);
5290 if (error != NULL)
5291 goto done;
5293 if (show_diffstat) {
5294 dsa.paths = &diffstat_paths;
5295 dsa.force_text = force_text_diff;
5296 dsa.ignore_ws = ignore_whitespace;
5297 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5300 if (rflag || worktree == NULL || ncommit_args > 0) {
5301 if (force_path) {
5302 error = got_error_msg(GOT_ERR_NOT_IMPL,
5303 "-P option can only be used when diffing "
5304 "a work tree");
5305 goto done;
5307 if (diff_staged) {
5308 error = got_error_msg(GOT_ERR_NOT_IMPL,
5309 "-s option can only be used when diffing "
5310 "a work tree");
5311 goto done;
5315 error = apply_unveil(got_repo_get_path(repo), 1,
5316 worktree ? got_worktree_get_root_path(worktree) : NULL);
5317 if (error)
5318 goto done;
5320 if ((!force_path && argc == 2) || ncommit_args > 0) {
5321 int obj_type = (ncommit_args > 0 ?
5322 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5323 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5324 NULL);
5325 if (error)
5326 goto done;
5327 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5328 const char *arg;
5329 char *keyword_idstr = NULL;
5331 if (ncommit_args > 0)
5332 arg = commit_args[i];
5333 else
5334 arg = argv[i];
5336 error = got_keyword_to_idstr(&keyword_idstr, arg,
5337 repo, worktree);
5338 if (error != NULL)
5339 goto done;
5340 if (keyword_idstr != NULL)
5341 arg = keyword_idstr;
5343 error = got_repo_match_object_id(&ids[i], &labels[i],
5344 arg, obj_type, &refs, repo);
5345 free(keyword_idstr);
5346 if (error) {
5347 if (error->code != GOT_ERR_NOT_REF &&
5348 error->code != GOT_ERR_NO_OBJ)
5349 goto done;
5350 if (ncommit_args > 0)
5351 goto done;
5352 error = NULL;
5353 break;
5358 f1 = got_opentemp();
5359 if (f1 == NULL) {
5360 error = got_error_from_errno("got_opentemp");
5361 goto done;
5364 f2 = got_opentemp();
5365 if (f2 == NULL) {
5366 error = got_error_from_errno("got_opentemp");
5367 goto done;
5370 outfile = got_opentemp();
5371 if (outfile == NULL) {
5372 error = got_error_from_errno("got_opentemp");
5373 goto done;
5376 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5377 struct print_diff_arg arg;
5378 char *id_str;
5380 if (worktree == NULL) {
5381 if (argc == 2 && ids[0] == NULL) {
5382 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5383 goto done;
5384 } else if (argc == 2 && ids[1] == NULL) {
5385 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5386 goto done;
5387 } else if (argc > 0) {
5388 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5389 "%s", "specified paths cannot be resolved");
5390 goto done;
5391 } else {
5392 error = got_error(GOT_ERR_NOT_WORKTREE);
5393 goto done;
5397 error = get_worktree_paths_from_argv(&paths, argc, argv,
5398 worktree);
5399 if (error)
5400 goto done;
5402 error = got_object_id_str(&id_str,
5403 got_worktree_get_base_commit_id(worktree));
5404 if (error)
5405 goto done;
5406 arg.repo = repo;
5407 arg.worktree = worktree;
5408 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5409 arg.diff_context = diff_context;
5410 arg.id_str = id_str;
5411 arg.header_shown = 0;
5412 arg.diff_staged = diff_staged;
5413 arg.ignore_whitespace = ignore_whitespace;
5414 arg.force_text_diff = force_text_diff;
5415 arg.diffstat = show_diffstat ? &dsa : NULL;
5416 arg.f1 = f1;
5417 arg.f2 = f2;
5418 arg.outfile = outfile;
5420 error = got_worktree_status(worktree, &paths, repo, 0,
5421 print_diff, &arg, check_cancelled, NULL);
5422 free(id_str);
5423 if (error)
5424 goto done;
5426 if (show_diffstat && dsa.nfiles > 0) {
5427 char *header;
5429 if (asprintf(&header, "diffstat %s%s",
5430 diff_staged ? "-s " : "",
5431 got_worktree_get_root_path(worktree)) == -1) {
5432 error = got_error_from_errno("asprintf");
5433 goto done;
5436 error = print_diffstat(&dsa, header);
5437 free(header);
5438 if (error)
5439 goto done;
5442 error = printfile(outfile);
5443 goto done;
5446 if (ncommit_args == 1) {
5447 struct got_commit_object *commit;
5448 error = got_object_open_as_commit(&commit, repo, ids[0]);
5449 if (error)
5450 goto done;
5452 labels[1] = labels[0];
5453 ids[1] = ids[0];
5454 if (got_object_commit_get_nparents(commit) > 0) {
5455 const struct got_object_id_queue *pids;
5456 struct got_object_qid *pid;
5457 pids = got_object_commit_get_parent_ids(commit);
5458 pid = STAILQ_FIRST(pids);
5459 ids[0] = got_object_id_dup(&pid->id);
5460 if (ids[0] == NULL) {
5461 error = got_error_from_errno(
5462 "got_object_id_dup");
5463 got_object_commit_close(commit);
5464 goto done;
5466 error = got_object_id_str(&labels[0], ids[0]);
5467 if (error) {
5468 got_object_commit_close(commit);
5469 goto done;
5471 } else {
5472 ids[0] = NULL;
5473 labels[0] = strdup("/dev/null");
5474 if (labels[0] == NULL) {
5475 error = got_error_from_errno("strdup");
5476 got_object_commit_close(commit);
5477 goto done;
5481 got_object_commit_close(commit);
5484 if (ncommit_args == 0 && argc > 2) {
5485 error = got_error_msg(GOT_ERR_BAD_PATH,
5486 "path arguments cannot be used when diffing two objects");
5487 goto done;
5490 if (ids[0]) {
5491 error = got_object_get_type(&type1, repo, ids[0]);
5492 if (error)
5493 goto done;
5496 error = got_object_get_type(&type2, repo, ids[1]);
5497 if (error)
5498 goto done;
5499 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5500 error = got_error(GOT_ERR_OBJ_TYPE);
5501 goto done;
5503 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5504 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5505 "path arguments cannot be used when diffing blobs");
5506 goto done;
5509 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5510 char *in_repo_path;
5511 struct got_pathlist_entry *new;
5512 if (worktree) {
5513 const char *prefix;
5514 char *p;
5515 error = got_worktree_resolve_path(&p, worktree,
5516 argv[i]);
5517 if (error)
5518 goto done;
5519 prefix = got_worktree_get_path_prefix(worktree);
5520 while (prefix[0] == '/')
5521 prefix++;
5522 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5523 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5524 p) == -1) {
5525 error = got_error_from_errno("asprintf");
5526 free(p);
5527 goto done;
5529 free(p);
5530 } else {
5531 char *mapped_path, *s;
5532 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5533 if (error)
5534 goto done;
5535 s = mapped_path;
5536 while (s[0] == '/')
5537 s++;
5538 in_repo_path = strdup(s);
5539 if (in_repo_path == NULL) {
5540 error = got_error_from_errno("asprintf");
5541 free(mapped_path);
5542 goto done;
5544 free(mapped_path);
5547 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5548 if (error || new == NULL /* duplicate */)
5549 free(in_repo_path);
5550 if (error)
5551 goto done;
5554 if (worktree) {
5555 /* Release work tree lock. */
5556 got_worktree_close(worktree);
5557 worktree = NULL;
5560 fd1 = got_opentempfd();
5561 if (fd1 == -1) {
5562 error = got_error_from_errno("got_opentempfd");
5563 goto done;
5566 fd2 = got_opentempfd();
5567 if (fd2 == -1) {
5568 error = got_error_from_errno("got_opentempfd");
5569 goto done;
5572 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5573 case GOT_OBJ_TYPE_BLOB:
5574 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5575 fd1, fd2, ids[0], ids[1], NULL, NULL,
5576 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5577 ignore_whitespace, force_text_diff,
5578 show_diffstat ? &dsa : NULL, repo, outfile);
5579 break;
5580 case GOT_OBJ_TYPE_TREE:
5581 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5582 ids[0], ids[1], &paths, "", "",
5583 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5584 ignore_whitespace, force_text_diff,
5585 show_diffstat ? &dsa : NULL, repo, outfile);
5586 break;
5587 case GOT_OBJ_TYPE_COMMIT:
5588 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5589 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5590 fd1, fd2, ids[0], ids[1], &paths,
5591 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5592 ignore_whitespace, force_text_diff,
5593 show_diffstat ? &dsa : NULL, repo, outfile);
5594 break;
5595 default:
5596 error = got_error(GOT_ERR_OBJ_TYPE);
5598 if (error)
5599 goto done;
5601 if (show_diffstat && dsa.nfiles > 0) {
5602 char *header = NULL;
5604 if (asprintf(&header, "diffstat %s %s",
5605 labels[0], labels[1]) == -1) {
5606 error = got_error_from_errno("asprintf");
5607 goto done;
5610 error = print_diffstat(&dsa, header);
5611 free(header);
5612 if (error)
5613 goto done;
5616 error = printfile(outfile);
5618 done:
5619 free(labels[0]);
5620 free(labels[1]);
5621 free(ids[0]);
5622 free(ids[1]);
5623 if (worktree)
5624 got_worktree_close(worktree);
5625 if (repo) {
5626 const struct got_error *close_err = got_repo_close(repo);
5627 if (error == NULL)
5628 error = close_err;
5630 if (pack_fds) {
5631 const struct got_error *pack_err =
5632 got_repo_pack_fds_close(pack_fds);
5633 if (error == NULL)
5634 error = pack_err;
5636 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5637 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5638 got_ref_list_free(&refs);
5639 if (outfile && fclose(outfile) == EOF && error == NULL)
5640 error = got_error_from_errno("fclose");
5641 if (f1 && fclose(f1) == EOF && error == NULL)
5642 error = got_error_from_errno("fclose");
5643 if (f2 && fclose(f2) == EOF && error == NULL)
5644 error = got_error_from_errno("fclose");
5645 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5646 error = got_error_from_errno("close");
5647 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5648 error = got_error_from_errno("close");
5649 return error;
5652 __dead static void
5653 usage_blame(void)
5655 fprintf(stderr,
5656 "usage: %s blame [-c commit] [-r repository-path] path\n",
5657 getprogname());
5658 exit(1);
5661 struct blame_line {
5662 int annotated;
5663 char *id_str;
5664 char *committer;
5665 char datebuf[11]; /* YYYY-MM-DD + NUL */
5668 struct blame_cb_args {
5669 struct blame_line *lines;
5670 int nlines;
5671 int nlines_prec;
5672 int lineno_cur;
5673 off_t *line_offsets;
5674 FILE *f;
5675 struct got_repository *repo;
5678 static const struct got_error *
5679 blame_cb(void *arg, int nlines, int lineno,
5680 struct got_commit_object *commit, struct got_object_id *id)
5682 const struct got_error *err = NULL;
5683 struct blame_cb_args *a = arg;
5684 struct blame_line *bline;
5685 char *line = NULL;
5686 size_t linesize = 0;
5687 off_t offset;
5688 struct tm tm;
5689 time_t committer_time;
5691 if (nlines != a->nlines ||
5692 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5693 return got_error(GOT_ERR_RANGE);
5695 if (sigint_received)
5696 return got_error(GOT_ERR_ITER_COMPLETED);
5698 if (lineno == -1)
5699 return NULL; /* no change in this commit */
5701 /* Annotate this line. */
5702 bline = &a->lines[lineno - 1];
5703 if (bline->annotated)
5704 return NULL;
5705 err = got_object_id_str(&bline->id_str, id);
5706 if (err)
5707 return err;
5709 bline->committer = strdup(got_object_commit_get_committer(commit));
5710 if (bline->committer == NULL) {
5711 err = got_error_from_errno("strdup");
5712 goto done;
5715 committer_time = got_object_commit_get_committer_time(commit);
5716 if (gmtime_r(&committer_time, &tm) == NULL)
5717 return got_error_from_errno("gmtime_r");
5718 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5719 &tm) == 0) {
5720 err = got_error(GOT_ERR_NO_SPACE);
5721 goto done;
5723 bline->annotated = 1;
5725 /* Print lines annotated so far. */
5726 bline = &a->lines[a->lineno_cur - 1];
5727 if (!bline->annotated)
5728 goto done;
5730 offset = a->line_offsets[a->lineno_cur - 1];
5731 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5732 err = got_error_from_errno("fseeko");
5733 goto done;
5736 while (a->lineno_cur <= a->nlines && bline->annotated) {
5737 char *smallerthan, *at, *nl, *committer;
5738 size_t len;
5740 if (getline(&line, &linesize, a->f) == -1) {
5741 if (ferror(a->f))
5742 err = got_error_from_errno("getline");
5743 break;
5746 committer = bline->committer;
5747 smallerthan = strchr(committer, '<');
5748 if (smallerthan && smallerthan[1] != '\0')
5749 committer = smallerthan + 1;
5750 at = strchr(committer, '@');
5751 if (at)
5752 *at = '\0';
5753 len = strlen(committer);
5754 if (len >= 9)
5755 committer[8] = '\0';
5757 nl = strchr(line, '\n');
5758 if (nl)
5759 *nl = '\0';
5760 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5761 bline->id_str, bline->datebuf, committer, line);
5763 a->lineno_cur++;
5764 bline = &a->lines[a->lineno_cur - 1];
5766 done:
5767 free(line);
5768 return err;
5771 static const struct got_error *
5772 cmd_blame(int argc, char *argv[])
5774 const struct got_error *error;
5775 struct got_repository *repo = NULL;
5776 struct got_worktree *worktree = NULL;
5777 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5778 char *link_target = NULL;
5779 struct got_object_id *obj_id = NULL;
5780 struct got_object_id *commit_id = NULL;
5781 struct got_commit_object *commit = NULL;
5782 struct got_blob_object *blob = NULL;
5783 char *commit_id_str = NULL, *keyword_idstr = NULL;
5784 struct blame_cb_args bca;
5785 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5786 off_t filesize;
5787 int *pack_fds = NULL;
5788 FILE *f1 = NULL, *f2 = NULL;
5790 fd1 = got_opentempfd();
5791 if (fd1 == -1)
5792 return got_error_from_errno("got_opentempfd");
5794 memset(&bca, 0, sizeof(bca));
5796 #ifndef PROFILE
5797 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5798 NULL) == -1)
5799 err(1, "pledge");
5800 #endif
5802 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5803 switch (ch) {
5804 case 'c':
5805 commit_id_str = optarg;
5806 break;
5807 case 'r':
5808 repo_path = realpath(optarg, NULL);
5809 if (repo_path == NULL)
5810 return got_error_from_errno2("realpath",
5811 optarg);
5812 got_path_strip_trailing_slashes(repo_path);
5813 break;
5814 default:
5815 usage_blame();
5816 /* NOTREACHED */
5820 argc -= optind;
5821 argv += optind;
5823 if (argc == 1)
5824 path = argv[0];
5825 else
5826 usage_blame();
5828 cwd = getcwd(NULL, 0);
5829 if (cwd == NULL) {
5830 error = got_error_from_errno("getcwd");
5831 goto done;
5834 error = got_repo_pack_fds_open(&pack_fds);
5835 if (error != NULL)
5836 goto done;
5838 if (repo_path == NULL) {
5839 error = got_worktree_open(&worktree, cwd,
5840 GOT_WORKTREE_GOT_DIR);
5841 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5842 goto done;
5843 else
5844 error = NULL;
5845 if (worktree) {
5846 repo_path =
5847 strdup(got_worktree_get_repo_path(worktree));
5848 if (repo_path == NULL) {
5849 error = got_error_from_errno("strdup");
5850 if (error)
5851 goto done;
5853 } else {
5854 repo_path = strdup(cwd);
5855 if (repo_path == NULL) {
5856 error = got_error_from_errno("strdup");
5857 goto done;
5862 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5863 if (error != NULL)
5864 goto done;
5866 if (worktree) {
5867 const char *prefix = got_worktree_get_path_prefix(worktree);
5868 char *p;
5870 error = got_worktree_resolve_path(&p, worktree, path);
5871 if (error)
5872 goto done;
5873 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5874 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5875 p) == -1) {
5876 error = got_error_from_errno("asprintf");
5877 free(p);
5878 goto done;
5880 free(p);
5881 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5882 } else {
5883 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5884 if (error)
5885 goto done;
5886 error = got_repo_map_path(&in_repo_path, repo, path);
5888 if (error)
5889 goto done;
5891 if (commit_id_str == NULL) {
5892 struct got_reference *head_ref;
5893 error = got_ref_open(&head_ref, repo, worktree ?
5894 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5895 if (error != NULL)
5896 goto done;
5897 error = got_ref_resolve(&commit_id, repo, head_ref);
5898 got_ref_close(head_ref);
5899 if (error != NULL)
5900 goto done;
5901 } else {
5902 struct got_reflist_head refs;
5904 TAILQ_INIT(&refs);
5905 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5906 NULL);
5907 if (error)
5908 goto done;
5910 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5911 repo, worktree);
5912 if (error != NULL)
5913 goto done;
5914 if (keyword_idstr != NULL)
5915 commit_id_str = keyword_idstr;
5917 error = got_repo_match_object_id(&commit_id, NULL,
5918 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5919 got_ref_list_free(&refs);
5920 if (error)
5921 goto done;
5924 if (worktree) {
5925 /* Release work tree lock. */
5926 got_worktree_close(worktree);
5927 worktree = NULL;
5930 error = got_object_open_as_commit(&commit, repo, commit_id);
5931 if (error)
5932 goto done;
5934 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5935 commit, repo);
5936 if (error)
5937 goto done;
5939 error = got_object_id_by_path(&obj_id, repo, commit,
5940 link_target ? link_target : in_repo_path);
5941 if (error)
5942 goto done;
5944 error = got_object_get_type(&obj_type, repo, obj_id);
5945 if (error)
5946 goto done;
5948 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5949 error = got_error_path(link_target ? link_target : in_repo_path,
5950 GOT_ERR_OBJ_TYPE);
5951 goto done;
5954 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5955 if (error)
5956 goto done;
5957 bca.f = got_opentemp();
5958 if (bca.f == NULL) {
5959 error = got_error_from_errno("got_opentemp");
5960 goto done;
5962 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5963 &bca.line_offsets, bca.f, blob);
5964 if (error || bca.nlines == 0)
5965 goto done;
5967 /* Don't include \n at EOF in the blame line count. */
5968 if (bca.line_offsets[bca.nlines - 1] == filesize)
5969 bca.nlines--;
5971 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5972 if (bca.lines == NULL) {
5973 error = got_error_from_errno("calloc");
5974 goto done;
5976 bca.lineno_cur = 1;
5977 bca.nlines_prec = 0;
5978 i = bca.nlines;
5979 while (i > 0) {
5980 i /= 10;
5981 bca.nlines_prec++;
5983 bca.repo = repo;
5985 fd2 = got_opentempfd();
5986 if (fd2 == -1) {
5987 error = got_error_from_errno("got_opentempfd");
5988 goto done;
5990 fd3 = got_opentempfd();
5991 if (fd3 == -1) {
5992 error = got_error_from_errno("got_opentempfd");
5993 goto done;
5995 f1 = got_opentemp();
5996 if (f1 == NULL) {
5997 error = got_error_from_errno("got_opentemp");
5998 goto done;
6000 f2 = got_opentemp();
6001 if (f2 == NULL) {
6002 error = got_error_from_errno("got_opentemp");
6003 goto done;
6005 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6006 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6007 check_cancelled, NULL, fd2, fd3, f1, f2);
6008 done:
6009 free(keyword_idstr);
6010 free(in_repo_path);
6011 free(link_target);
6012 free(repo_path);
6013 free(cwd);
6014 free(commit_id);
6015 free(obj_id);
6016 if (commit)
6017 got_object_commit_close(commit);
6019 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6020 error = got_error_from_errno("close");
6021 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6022 error = got_error_from_errno("close");
6023 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6024 error = got_error_from_errno("close");
6025 if (f1 && fclose(f1) == EOF && error == NULL)
6026 error = got_error_from_errno("fclose");
6027 if (f2 && fclose(f2) == EOF && error == NULL)
6028 error = got_error_from_errno("fclose");
6030 if (blob)
6031 got_object_blob_close(blob);
6032 if (worktree)
6033 got_worktree_close(worktree);
6034 if (repo) {
6035 const struct got_error *close_err = got_repo_close(repo);
6036 if (error == NULL)
6037 error = close_err;
6039 if (pack_fds) {
6040 const struct got_error *pack_err =
6041 got_repo_pack_fds_close(pack_fds);
6042 if (error == NULL)
6043 error = pack_err;
6045 if (bca.lines) {
6046 for (i = 0; i < bca.nlines; i++) {
6047 struct blame_line *bline = &bca.lines[i];
6048 free(bline->id_str);
6049 free(bline->committer);
6051 free(bca.lines);
6053 free(bca.line_offsets);
6054 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6055 error = got_error_from_errno("fclose");
6056 return error;
6059 __dead static void
6060 usage_tree(void)
6062 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6063 "[path]\n", getprogname());
6064 exit(1);
6067 static const struct got_error *
6068 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6069 const char *root_path, struct got_repository *repo)
6071 const struct got_error *err = NULL;
6072 int is_root_path = (strcmp(path, root_path) == 0);
6073 const char *modestr = "";
6074 mode_t mode = got_tree_entry_get_mode(te);
6075 char *link_target = NULL;
6077 path += strlen(root_path);
6078 while (path[0] == '/')
6079 path++;
6081 if (got_object_tree_entry_is_submodule(te))
6082 modestr = "$";
6083 else if (S_ISLNK(mode)) {
6084 int i;
6086 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6087 if (err)
6088 return err;
6089 for (i = 0; link_target[i] != '\0'; i++) {
6090 if (!isprint((unsigned char)link_target[i]))
6091 link_target[i] = '?';
6094 modestr = "@";
6096 else if (S_ISDIR(mode))
6097 modestr = "/";
6098 else if (mode & S_IXUSR)
6099 modestr = "*";
6101 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6102 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6103 link_target ? " -> ": "", link_target ? link_target : "");
6105 free(link_target);
6106 return NULL;
6109 static const struct got_error *
6110 print_tree(const char *path, struct got_commit_object *commit,
6111 int show_ids, int recurse, const char *root_path,
6112 struct got_repository *repo)
6114 const struct got_error *err = NULL;
6115 struct got_object_id *tree_id = NULL;
6116 struct got_tree_object *tree = NULL;
6117 int nentries, i;
6119 err = got_object_id_by_path(&tree_id, repo, commit, path);
6120 if (err)
6121 goto done;
6123 err = got_object_open_as_tree(&tree, repo, tree_id);
6124 if (err)
6125 goto done;
6126 nentries = got_object_tree_get_nentries(tree);
6127 for (i = 0; i < nentries; i++) {
6128 struct got_tree_entry *te;
6129 char *id = NULL;
6131 if (sigint_received || sigpipe_received)
6132 break;
6134 te = got_object_tree_get_entry(tree, i);
6135 if (show_ids) {
6136 char *id_str;
6137 err = got_object_id_str(&id_str,
6138 got_tree_entry_get_id(te));
6139 if (err)
6140 goto done;
6141 if (asprintf(&id, "%s ", id_str) == -1) {
6142 err = got_error_from_errno("asprintf");
6143 free(id_str);
6144 goto done;
6146 free(id_str);
6148 err = print_entry(te, id, path, root_path, repo);
6149 free(id);
6150 if (err)
6151 goto done;
6153 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6154 char *child_path;
6155 if (asprintf(&child_path, "%s%s%s", path,
6156 path[0] == '/' && path[1] == '\0' ? "" : "/",
6157 got_tree_entry_get_name(te)) == -1) {
6158 err = got_error_from_errno("asprintf");
6159 goto done;
6161 err = print_tree(child_path, commit, show_ids, 1,
6162 root_path, repo);
6163 free(child_path);
6164 if (err)
6165 goto done;
6168 done:
6169 if (tree)
6170 got_object_tree_close(tree);
6171 free(tree_id);
6172 return err;
6175 static const struct got_error *
6176 cmd_tree(int argc, char *argv[])
6178 const struct got_error *error;
6179 struct got_repository *repo = NULL;
6180 struct got_worktree *worktree = NULL;
6181 const char *path, *refname = NULL;
6182 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6183 struct got_object_id *commit_id = NULL;
6184 struct got_commit_object *commit = NULL;
6185 char *commit_id_str = NULL, *keyword_idstr = NULL;
6186 int show_ids = 0, recurse = 0;
6187 int ch;
6188 int *pack_fds = NULL;
6190 #ifndef PROFILE
6191 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6192 NULL) == -1)
6193 err(1, "pledge");
6194 #endif
6196 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6197 switch (ch) {
6198 case 'c':
6199 commit_id_str = optarg;
6200 break;
6201 case 'i':
6202 show_ids = 1;
6203 break;
6204 case 'R':
6205 recurse = 1;
6206 break;
6207 case 'r':
6208 repo_path = realpath(optarg, NULL);
6209 if (repo_path == NULL)
6210 return got_error_from_errno2("realpath",
6211 optarg);
6212 got_path_strip_trailing_slashes(repo_path);
6213 break;
6214 default:
6215 usage_tree();
6216 /* NOTREACHED */
6220 argc -= optind;
6221 argv += optind;
6223 if (argc == 1)
6224 path = argv[0];
6225 else if (argc > 1)
6226 usage_tree();
6227 else
6228 path = NULL;
6230 cwd = getcwd(NULL, 0);
6231 if (cwd == NULL) {
6232 error = got_error_from_errno("getcwd");
6233 goto done;
6236 error = got_repo_pack_fds_open(&pack_fds);
6237 if (error != NULL)
6238 goto done;
6240 if (repo_path == NULL) {
6241 error = got_worktree_open(&worktree, cwd,
6242 GOT_WORKTREE_GOT_DIR);
6243 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6244 goto done;
6245 else
6246 error = NULL;
6247 if (worktree) {
6248 repo_path =
6249 strdup(got_worktree_get_repo_path(worktree));
6250 if (repo_path == NULL)
6251 error = got_error_from_errno("strdup");
6252 if (error)
6253 goto done;
6254 } else {
6255 repo_path = strdup(cwd);
6256 if (repo_path == NULL) {
6257 error = got_error_from_errno("strdup");
6258 goto done;
6263 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6264 if (error != NULL)
6265 goto done;
6267 if (worktree) {
6268 const char *prefix = got_worktree_get_path_prefix(worktree);
6269 char *p;
6271 if (path == NULL || got_path_is_root_dir(path))
6272 path = "";
6273 error = got_worktree_resolve_path(&p, worktree, path);
6274 if (error)
6275 goto done;
6276 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6277 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6278 p) == -1) {
6279 error = got_error_from_errno("asprintf");
6280 free(p);
6281 goto done;
6283 free(p);
6284 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6285 if (error)
6286 goto done;
6287 } else {
6288 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6289 if (error)
6290 goto done;
6291 if (path == NULL)
6292 path = "/";
6293 error = got_repo_map_path(&in_repo_path, repo, path);
6294 if (error != NULL)
6295 goto done;
6298 if (commit_id_str == NULL) {
6299 struct got_reference *head_ref;
6300 if (worktree)
6301 refname = got_worktree_get_head_ref_name(worktree);
6302 else
6303 refname = GOT_REF_HEAD;
6304 error = got_ref_open(&head_ref, repo, refname, 0);
6305 if (error != NULL)
6306 goto done;
6307 error = got_ref_resolve(&commit_id, repo, head_ref);
6308 got_ref_close(head_ref);
6309 if (error != NULL)
6310 goto done;
6311 } else {
6312 struct got_reflist_head refs;
6314 TAILQ_INIT(&refs);
6315 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6316 NULL);
6317 if (error)
6318 goto done;
6320 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6321 repo, worktree);
6322 if (error != NULL)
6323 goto done;
6324 if (keyword_idstr != NULL)
6325 commit_id_str = keyword_idstr;
6327 error = got_repo_match_object_id(&commit_id, NULL,
6328 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6329 got_ref_list_free(&refs);
6330 if (error)
6331 goto done;
6334 if (worktree) {
6335 /* Release work tree lock. */
6336 got_worktree_close(worktree);
6337 worktree = NULL;
6340 error = got_object_open_as_commit(&commit, repo, commit_id);
6341 if (error)
6342 goto done;
6344 error = print_tree(in_repo_path, commit, show_ids, recurse,
6345 in_repo_path, repo);
6346 done:
6347 free(keyword_idstr);
6348 free(in_repo_path);
6349 free(repo_path);
6350 free(cwd);
6351 free(commit_id);
6352 if (commit)
6353 got_object_commit_close(commit);
6354 if (worktree)
6355 got_worktree_close(worktree);
6356 if (repo) {
6357 const struct got_error *close_err = got_repo_close(repo);
6358 if (error == NULL)
6359 error = close_err;
6361 if (pack_fds) {
6362 const struct got_error *pack_err =
6363 got_repo_pack_fds_close(pack_fds);
6364 if (error == NULL)
6365 error = pack_err;
6367 return error;
6370 __dead static void
6371 usage_status(void)
6373 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6374 "[-s status-codes] [path ...]\n", getprogname());
6375 exit(1);
6378 struct got_status_arg {
6379 char *status_codes;
6380 int suppress;
6383 static const struct got_error *
6384 print_status(void *arg, unsigned char status, unsigned char staged_status,
6385 const char *path, struct got_object_id *blob_id,
6386 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6387 int dirfd, const char *de_name)
6389 struct got_status_arg *st = arg;
6391 if (status == staged_status && (status == GOT_STATUS_DELETE))
6392 status = GOT_STATUS_NO_CHANGE;
6393 if (st != NULL && st->status_codes) {
6394 size_t ncodes = strlen(st->status_codes);
6395 int i, j = 0;
6397 for (i = 0; i < ncodes ; i++) {
6398 if (st->suppress) {
6399 if (status == st->status_codes[i] ||
6400 staged_status == st->status_codes[i]) {
6401 j++;
6402 continue;
6404 } else {
6405 if (status == st->status_codes[i] ||
6406 staged_status == st->status_codes[i])
6407 break;
6411 if (st->suppress && j == 0)
6412 goto print;
6414 if (i == ncodes)
6415 return NULL;
6417 print:
6418 printf("%c%c %s\n", status, staged_status, path);
6419 return NULL;
6422 static const struct got_error *
6423 cmd_status(int argc, char *argv[])
6425 const struct got_error *close_err, *error = NULL;
6426 struct got_repository *repo = NULL;
6427 struct got_worktree *worktree = NULL;
6428 struct got_status_arg st;
6429 char *cwd = NULL;
6430 struct got_pathlist_head paths;
6431 int ch, i, no_ignores = 0;
6432 int *pack_fds = NULL;
6434 TAILQ_INIT(&paths);
6436 memset(&st, 0, sizeof(st));
6437 st.status_codes = NULL;
6438 st.suppress = 0;
6440 #ifndef PROFILE
6441 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6442 NULL) == -1)
6443 err(1, "pledge");
6444 #endif
6446 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6447 switch (ch) {
6448 case 'I':
6449 no_ignores = 1;
6450 break;
6451 case 'S':
6452 if (st.status_codes != NULL && st.suppress == 0)
6453 option_conflict('S', 's');
6454 st.suppress = 1;
6455 /* fallthrough */
6456 case 's':
6457 for (i = 0; optarg[i] != '\0'; i++) {
6458 switch (optarg[i]) {
6459 case GOT_STATUS_MODIFY:
6460 case GOT_STATUS_ADD:
6461 case GOT_STATUS_DELETE:
6462 case GOT_STATUS_CONFLICT:
6463 case GOT_STATUS_MISSING:
6464 case GOT_STATUS_OBSTRUCTED:
6465 case GOT_STATUS_UNVERSIONED:
6466 case GOT_STATUS_MODE_CHANGE:
6467 case GOT_STATUS_NONEXISTENT:
6468 break;
6469 default:
6470 errx(1, "invalid status code '%c'",
6471 optarg[i]);
6474 if (ch == 's' && st.suppress)
6475 option_conflict('s', 'S');
6476 st.status_codes = optarg;
6477 break;
6478 default:
6479 usage_status();
6480 /* NOTREACHED */
6484 argc -= optind;
6485 argv += optind;
6487 cwd = getcwd(NULL, 0);
6488 if (cwd == NULL) {
6489 error = got_error_from_errno("getcwd");
6490 goto done;
6493 error = got_repo_pack_fds_open(&pack_fds);
6494 if (error != NULL)
6495 goto done;
6497 error = got_worktree_open(&worktree, cwd,
6498 GOT_WORKTREE_GOT_DIR);
6499 if (error) {
6500 if (error->code == GOT_ERR_NOT_WORKTREE)
6501 error = wrap_not_worktree_error(error, "status", cwd);
6502 goto done;
6505 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6506 NULL, pack_fds);
6507 if (error != NULL)
6508 goto done;
6510 error = apply_unveil(got_repo_get_path(repo), 1,
6511 got_worktree_get_root_path(worktree));
6512 if (error)
6513 goto done;
6515 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6516 if (error)
6517 goto done;
6519 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6520 print_status, &st, check_cancelled, NULL);
6521 done:
6522 if (pack_fds) {
6523 const struct got_error *pack_err =
6524 got_repo_pack_fds_close(pack_fds);
6525 if (error == NULL)
6526 error = pack_err;
6528 if (repo) {
6529 close_err = got_repo_close(repo);
6530 if (error == NULL)
6531 error = close_err;
6533 if (worktree != NULL) {
6534 close_err = got_worktree_close(worktree);
6535 if (error == NULL)
6536 error = close_err;
6539 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6540 free(cwd);
6541 return error;
6544 __dead static void
6545 usage_ref(void)
6547 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6548 "[-s reference] [name]\n", getprogname());
6549 exit(1);
6552 static const struct got_error *
6553 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6555 static const struct got_error *err = NULL;
6556 struct got_reflist_head refs;
6557 struct got_reflist_entry *re;
6559 TAILQ_INIT(&refs);
6560 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6561 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6562 repo);
6563 if (err)
6564 return err;
6566 TAILQ_FOREACH(re, &refs, entry) {
6567 char *refstr;
6568 refstr = got_ref_to_str(re->ref);
6569 if (refstr == NULL) {
6570 err = got_error_from_errno("got_ref_to_str");
6571 break;
6573 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6574 free(refstr);
6577 got_ref_list_free(&refs);
6578 return err;
6581 static const struct got_error *
6582 delete_ref_by_name(struct got_repository *repo, const char *refname)
6584 const struct got_error *err;
6585 struct got_reference *ref;
6587 err = got_ref_open(&ref, repo, refname, 0);
6588 if (err)
6589 return err;
6591 err = delete_ref(repo, ref);
6592 got_ref_close(ref);
6593 return err;
6596 static const struct got_error *
6597 add_ref(struct got_repository *repo, const char *refname, const char *target)
6599 const struct got_error *err = NULL;
6600 struct got_object_id *id = NULL;
6601 struct got_reference *ref = NULL;
6602 struct got_reflist_head refs;
6605 * Don't let the user create a reference name with a leading '-'.
6606 * While technically a valid reference name, this case is usually
6607 * an unintended typo.
6609 if (refname[0] == '-')
6610 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6612 TAILQ_INIT(&refs);
6613 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6614 if (err)
6615 goto done;
6616 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6617 &refs, repo);
6618 got_ref_list_free(&refs);
6619 if (err)
6620 goto done;
6622 err = got_ref_alloc(&ref, refname, id);
6623 if (err)
6624 goto done;
6626 err = got_ref_write(ref, repo);
6627 done:
6628 if (ref)
6629 got_ref_close(ref);
6630 free(id);
6631 return err;
6634 static const struct got_error *
6635 add_symref(struct got_repository *repo, const char *refname, const char *target)
6637 const struct got_error *err = NULL;
6638 struct got_reference *ref = NULL;
6639 struct got_reference *target_ref = NULL;
6642 * Don't let the user create a reference name with a leading '-'.
6643 * While technically a valid reference name, this case is usually
6644 * an unintended typo.
6646 if (refname[0] == '-')
6647 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6649 err = got_ref_open(&target_ref, repo, target, 0);
6650 if (err)
6651 return err;
6653 err = got_ref_alloc_symref(&ref, refname, target_ref);
6654 if (err)
6655 goto done;
6657 err = got_ref_write(ref, repo);
6658 done:
6659 if (target_ref)
6660 got_ref_close(target_ref);
6661 if (ref)
6662 got_ref_close(ref);
6663 return err;
6666 static const struct got_error *
6667 cmd_ref(int argc, char *argv[])
6669 const struct got_error *error = NULL;
6670 struct got_repository *repo = NULL;
6671 struct got_worktree *worktree = NULL;
6672 char *cwd = NULL, *repo_path = NULL;
6673 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6674 const char *obj_arg = NULL, *symref_target= NULL;
6675 char *refname = NULL, *keyword_idstr = NULL;
6676 int *pack_fds = NULL;
6678 #ifndef PROFILE
6679 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6680 "sendfd unveil", NULL) == -1)
6681 err(1, "pledge");
6682 #endif
6684 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6685 switch (ch) {
6686 case 'c':
6687 obj_arg = optarg;
6688 break;
6689 case 'd':
6690 do_delete = 1;
6691 break;
6692 case 'l':
6693 do_list = 1;
6694 break;
6695 case 'r':
6696 repo_path = realpath(optarg, NULL);
6697 if (repo_path == NULL)
6698 return got_error_from_errno2("realpath",
6699 optarg);
6700 got_path_strip_trailing_slashes(repo_path);
6701 break;
6702 case 's':
6703 symref_target = optarg;
6704 break;
6705 case 't':
6706 sort_by_time = 1;
6707 break;
6708 default:
6709 usage_ref();
6710 /* NOTREACHED */
6714 if (obj_arg && do_list)
6715 option_conflict('c', 'l');
6716 if (obj_arg && do_delete)
6717 option_conflict('c', 'd');
6718 if (obj_arg && symref_target)
6719 option_conflict('c', 's');
6720 if (symref_target && do_delete)
6721 option_conflict('s', 'd');
6722 if (symref_target && do_list)
6723 option_conflict('s', 'l');
6724 if (do_delete && do_list)
6725 option_conflict('d', 'l');
6726 if (sort_by_time && !do_list)
6727 errx(1, "-t option requires -l option");
6729 argc -= optind;
6730 argv += optind;
6732 if (do_list) {
6733 if (argc != 0 && argc != 1)
6734 usage_ref();
6735 if (argc == 1) {
6736 refname = strdup(argv[0]);
6737 if (refname == NULL) {
6738 error = got_error_from_errno("strdup");
6739 goto done;
6742 } else {
6743 if (argc != 1)
6744 usage_ref();
6745 refname = strdup(argv[0]);
6746 if (refname == NULL) {
6747 error = got_error_from_errno("strdup");
6748 goto done;
6752 if (refname)
6753 got_path_strip_trailing_slashes(refname);
6755 cwd = getcwd(NULL, 0);
6756 if (cwd == NULL) {
6757 error = got_error_from_errno("getcwd");
6758 goto done;
6761 error = got_repo_pack_fds_open(&pack_fds);
6762 if (error != NULL)
6763 goto done;
6765 if (repo_path == NULL) {
6766 error = got_worktree_open(&worktree, cwd,
6767 GOT_WORKTREE_GOT_DIR);
6768 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6769 goto done;
6770 else
6771 error = NULL;
6772 if (worktree) {
6773 repo_path =
6774 strdup(got_worktree_get_repo_path(worktree));
6775 if (repo_path == NULL)
6776 error = got_error_from_errno("strdup");
6777 if (error)
6778 goto done;
6779 } else {
6780 repo_path = strdup(cwd);
6781 if (repo_path == NULL) {
6782 error = got_error_from_errno("strdup");
6783 goto done;
6788 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6789 if (error != NULL)
6790 goto done;
6792 #ifndef PROFILE
6793 if (do_list) {
6794 /* Remove "cpath" promise. */
6795 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6796 NULL) == -1)
6797 err(1, "pledge");
6799 #endif
6801 error = apply_unveil(got_repo_get_path(repo), do_list,
6802 worktree ? got_worktree_get_root_path(worktree) : NULL);
6803 if (error)
6804 goto done;
6806 if (do_list)
6807 error = list_refs(repo, refname, sort_by_time);
6808 else if (do_delete)
6809 error = delete_ref_by_name(repo, refname);
6810 else if (symref_target)
6811 error = add_symref(repo, refname, symref_target);
6812 else {
6813 if (obj_arg == NULL)
6814 usage_ref();
6816 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6817 repo, worktree);
6818 if (error != NULL)
6819 goto done;
6820 if (keyword_idstr != NULL)
6821 obj_arg = keyword_idstr;
6823 error = add_ref(repo, refname, obj_arg);
6825 done:
6826 free(refname);
6827 if (repo) {
6828 const struct got_error *close_err = got_repo_close(repo);
6829 if (error == NULL)
6830 error = close_err;
6832 if (worktree)
6833 got_worktree_close(worktree);
6834 if (pack_fds) {
6835 const struct got_error *pack_err =
6836 got_repo_pack_fds_close(pack_fds);
6837 if (error == NULL)
6838 error = pack_err;
6840 free(cwd);
6841 free(repo_path);
6842 free(keyword_idstr);
6843 return error;
6846 __dead static void
6847 usage_branch(void)
6849 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6850 "[-r repository-path] [name]\n", getprogname());
6851 exit(1);
6854 static const struct got_error *
6855 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6856 struct got_reference *ref)
6858 const struct got_error *err = NULL;
6859 const char *refname;
6860 char *refstr;
6861 char marker = ' ';
6863 refname = got_ref_get_name(ref);
6864 if (worktree && strcmp(refname,
6865 got_worktree_get_head_ref_name(worktree)) == 0) {
6866 err = got_worktree_get_state(&marker, repo, worktree,
6867 check_cancelled, NULL);
6868 if (err != NULL)
6869 return err;
6872 if (strncmp(refname, "refs/heads/", 11) == 0)
6873 refname += 11;
6874 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6875 refname += 18;
6876 if (strncmp(refname, "refs/remotes/", 13) == 0)
6877 refname += 13;
6879 refstr = got_ref_to_str(ref);
6880 if (refstr == NULL)
6881 return got_error_from_errno("got_ref_to_str");
6883 printf("%c %s: %s\n", marker, refname, refstr);
6884 free(refstr);
6885 return NULL;
6888 static const struct got_error *
6889 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6891 const char *refname;
6893 if (worktree == NULL)
6894 return got_error(GOT_ERR_NOT_WORKTREE);
6896 refname = got_worktree_get_head_ref_name(worktree);
6898 if (strncmp(refname, "refs/heads/", 11) == 0)
6899 refname += 11;
6900 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6901 refname += 18;
6903 printf("%s\n", refname);
6905 return NULL;
6908 static const struct got_error *
6909 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6910 int sort_by_time)
6912 static const struct got_error *err = NULL;
6913 struct got_reflist_head refs;
6914 struct got_reflist_entry *re;
6915 struct got_reference *temp_ref = NULL;
6916 int rebase_in_progress, histedit_in_progress;
6918 TAILQ_INIT(&refs);
6920 if (worktree) {
6921 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6922 worktree);
6923 if (err)
6924 return err;
6926 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6927 worktree);
6928 if (err)
6929 return err;
6931 if (rebase_in_progress || histedit_in_progress) {
6932 err = got_ref_open(&temp_ref, repo,
6933 got_worktree_get_head_ref_name(worktree), 0);
6934 if (err)
6935 return err;
6936 list_branch(repo, worktree, temp_ref);
6937 got_ref_close(temp_ref);
6941 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6942 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6943 repo);
6944 if (err)
6945 return err;
6947 TAILQ_FOREACH(re, &refs, entry)
6948 list_branch(repo, worktree, re->ref);
6950 got_ref_list_free(&refs);
6952 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6953 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6954 repo);
6955 if (err)
6956 return err;
6958 TAILQ_FOREACH(re, &refs, entry)
6959 list_branch(repo, worktree, re->ref);
6961 got_ref_list_free(&refs);
6963 return NULL;
6966 static const struct got_error *
6967 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6968 const char *branch_name)
6970 const struct got_error *err = NULL;
6971 struct got_reference *ref = NULL;
6972 char *refname, *remote_refname = NULL;
6974 if (strncmp(branch_name, "refs/", 5) == 0)
6975 branch_name += 5;
6976 if (strncmp(branch_name, "heads/", 6) == 0)
6977 branch_name += 6;
6978 else if (strncmp(branch_name, "remotes/", 8) == 0)
6979 branch_name += 8;
6981 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6982 return got_error_from_errno("asprintf");
6984 if (asprintf(&remote_refname, "refs/remotes/%s",
6985 branch_name) == -1) {
6986 err = got_error_from_errno("asprintf");
6987 goto done;
6990 err = got_ref_open(&ref, repo, refname, 0);
6991 if (err) {
6992 const struct got_error *err2;
6993 if (err->code != GOT_ERR_NOT_REF)
6994 goto done;
6996 * Keep 'err' intact such that if neither branch exists
6997 * we report "refs/heads" rather than "refs/remotes" in
6998 * our error message.
7000 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7001 if (err2)
7002 goto done;
7003 err = NULL;
7006 if (worktree &&
7007 strcmp(got_worktree_get_head_ref_name(worktree),
7008 got_ref_get_name(ref)) == 0) {
7009 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7010 "will not delete this work tree's current branch");
7011 goto done;
7014 err = delete_ref(repo, ref);
7015 done:
7016 if (ref)
7017 got_ref_close(ref);
7018 free(refname);
7019 free(remote_refname);
7020 return err;
7023 static const struct got_error *
7024 add_branch(struct got_repository *repo, const char *branch_name,
7025 struct got_object_id *base_commit_id)
7027 const struct got_error *err = NULL;
7028 struct got_reference *ref = NULL;
7029 char *refname = NULL;
7032 * Don't let the user create a branch name with a leading '-'.
7033 * While technically a valid reference name, this case is usually
7034 * an unintended typo.
7036 if (branch_name[0] == '-')
7037 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7039 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7040 branch_name += 11;
7042 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7043 err = got_error_from_errno("asprintf");
7044 goto done;
7047 err = got_ref_open(&ref, repo, refname, 0);
7048 if (err == NULL) {
7049 err = got_error(GOT_ERR_BRANCH_EXISTS);
7050 goto done;
7051 } else if (err->code != GOT_ERR_NOT_REF)
7052 goto done;
7054 err = got_ref_alloc(&ref, refname, base_commit_id);
7055 if (err)
7056 goto done;
7058 err = got_ref_write(ref, repo);
7059 done:
7060 if (ref)
7061 got_ref_close(ref);
7062 free(refname);
7063 return err;
7066 static const struct got_error *
7067 cmd_branch(int argc, char *argv[])
7069 const struct got_error *error = NULL;
7070 struct got_repository *repo = NULL;
7071 struct got_worktree *worktree = NULL;
7072 char *cwd = NULL, *repo_path = NULL;
7073 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7074 const char *delref = NULL, *commit_id_arg = NULL;
7075 struct got_reference *ref = NULL;
7076 struct got_pathlist_head paths;
7077 struct got_object_id *commit_id = NULL;
7078 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7079 int *pack_fds = NULL;
7081 TAILQ_INIT(&paths);
7083 #ifndef PROFILE
7084 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7085 "sendfd unveil", NULL) == -1)
7086 err(1, "pledge");
7087 #endif
7089 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7090 switch (ch) {
7091 case 'c':
7092 commit_id_arg = optarg;
7093 break;
7094 case 'd':
7095 delref = optarg;
7096 break;
7097 case 'l':
7098 do_list = 1;
7099 break;
7100 case 'n':
7101 do_update = 0;
7102 break;
7103 case 'r':
7104 repo_path = realpath(optarg, NULL);
7105 if (repo_path == NULL)
7106 return got_error_from_errno2("realpath",
7107 optarg);
7108 got_path_strip_trailing_slashes(repo_path);
7109 break;
7110 case 't':
7111 sort_by_time = 1;
7112 break;
7113 default:
7114 usage_branch();
7115 /* NOTREACHED */
7119 if (do_list && delref)
7120 option_conflict('l', 'd');
7121 if (sort_by_time && !do_list)
7122 errx(1, "-t option requires -l option");
7124 argc -= optind;
7125 argv += optind;
7127 if (!do_list && !delref && argc == 0)
7128 do_show = 1;
7130 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7131 errx(1, "-c option can only be used when creating a branch");
7133 if (do_list || delref) {
7134 if (argc > 0)
7135 usage_branch();
7136 } else if (!do_show && argc != 1)
7137 usage_branch();
7139 cwd = getcwd(NULL, 0);
7140 if (cwd == NULL) {
7141 error = got_error_from_errno("getcwd");
7142 goto done;
7145 error = got_repo_pack_fds_open(&pack_fds);
7146 if (error != NULL)
7147 goto done;
7149 if (repo_path == NULL) {
7150 error = got_worktree_open(&worktree, cwd,
7151 GOT_WORKTREE_GOT_DIR);
7152 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7153 goto done;
7154 else
7155 error = NULL;
7156 if (worktree) {
7157 repo_path =
7158 strdup(got_worktree_get_repo_path(worktree));
7159 if (repo_path == NULL)
7160 error = got_error_from_errno("strdup");
7161 if (error)
7162 goto done;
7163 } else {
7164 repo_path = strdup(cwd);
7165 if (repo_path == NULL) {
7166 error = got_error_from_errno("strdup");
7167 goto done;
7172 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7173 if (error != NULL)
7174 goto done;
7176 #ifndef PROFILE
7177 if (do_list || do_show) {
7178 /* Remove "cpath" promise. */
7179 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7180 NULL) == -1)
7181 err(1, "pledge");
7183 #endif
7185 error = apply_unveil(got_repo_get_path(repo), do_list,
7186 worktree ? got_worktree_get_root_path(worktree) : NULL);
7187 if (error)
7188 goto done;
7190 if (do_show)
7191 error = show_current_branch(repo, worktree);
7192 else if (do_list)
7193 error = list_branches(repo, worktree, sort_by_time);
7194 else if (delref)
7195 error = delete_branch(repo, worktree, delref);
7196 else {
7197 struct got_reflist_head refs;
7198 TAILQ_INIT(&refs);
7199 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7200 NULL);
7201 if (error)
7202 goto done;
7203 if (commit_id_arg == NULL)
7204 commit_id_arg = worktree ?
7205 got_worktree_get_head_ref_name(worktree) :
7206 GOT_REF_HEAD;
7207 else {
7208 error = got_keyword_to_idstr(&keyword_idstr,
7209 commit_id_arg, repo, worktree);
7210 if (error != NULL)
7211 goto done;
7212 if (keyword_idstr != NULL)
7213 commit_id_arg = keyword_idstr;
7215 error = got_repo_match_object_id(&commit_id, NULL,
7216 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7217 got_ref_list_free(&refs);
7218 if (error)
7219 goto done;
7220 error = add_branch(repo, argv[0], commit_id);
7221 if (error)
7222 goto done;
7223 if (worktree && do_update) {
7224 struct got_update_progress_arg upa;
7225 char *branch_refname = NULL;
7227 error = got_object_id_str(&commit_id_str, commit_id);
7228 if (error)
7229 goto done;
7230 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7231 worktree);
7232 if (error)
7233 goto done;
7234 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7235 == -1) {
7236 error = got_error_from_errno("asprintf");
7237 goto done;
7239 error = got_ref_open(&ref, repo, branch_refname, 0);
7240 free(branch_refname);
7241 if (error)
7242 goto done;
7243 error = switch_head_ref(ref, commit_id, worktree,
7244 repo);
7245 if (error)
7246 goto done;
7247 error = got_worktree_set_base_commit_id(worktree, repo,
7248 commit_id);
7249 if (error)
7250 goto done;
7251 memset(&upa, 0, sizeof(upa));
7252 error = got_worktree_checkout_files(worktree, &paths,
7253 repo, update_progress, &upa, check_cancelled,
7254 NULL);
7255 if (error)
7256 goto done;
7257 if (upa.did_something) {
7258 printf("Updated to %s: %s\n",
7259 got_worktree_get_head_ref_name(worktree),
7260 commit_id_str);
7262 print_update_progress_stats(&upa);
7265 done:
7266 free(keyword_idstr);
7267 if (ref)
7268 got_ref_close(ref);
7269 if (repo) {
7270 const struct got_error *close_err = got_repo_close(repo);
7271 if (error == NULL)
7272 error = close_err;
7274 if (worktree)
7275 got_worktree_close(worktree);
7276 if (pack_fds) {
7277 const struct got_error *pack_err =
7278 got_repo_pack_fds_close(pack_fds);
7279 if (error == NULL)
7280 error = pack_err;
7282 free(cwd);
7283 free(repo_path);
7284 free(commit_id);
7285 free(commit_id_str);
7286 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7287 return error;
7291 __dead static void
7292 usage_tag(void)
7294 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7295 "[-r repository-path] [-s signer-id] name\n", getprogname());
7296 exit(1);
7299 #if 0
7300 static const struct got_error *
7301 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7303 const struct got_error *err = NULL;
7304 struct got_reflist_entry *re, *se, *new;
7305 struct got_object_id *re_id, *se_id;
7306 struct got_tag_object *re_tag, *se_tag;
7307 time_t re_time, se_time;
7309 STAILQ_FOREACH(re, tags, entry) {
7310 se = STAILQ_FIRST(sorted);
7311 if (se == NULL) {
7312 err = got_reflist_entry_dup(&new, re);
7313 if (err)
7314 return err;
7315 STAILQ_INSERT_HEAD(sorted, new, entry);
7316 continue;
7317 } else {
7318 err = got_ref_resolve(&re_id, repo, re->ref);
7319 if (err)
7320 break;
7321 err = got_object_open_as_tag(&re_tag, repo, re_id);
7322 free(re_id);
7323 if (err)
7324 break;
7325 re_time = got_object_tag_get_tagger_time(re_tag);
7326 got_object_tag_close(re_tag);
7329 while (se) {
7330 err = got_ref_resolve(&se_id, repo, re->ref);
7331 if (err)
7332 break;
7333 err = got_object_open_as_tag(&se_tag, repo, se_id);
7334 free(se_id);
7335 if (err)
7336 break;
7337 se_time = got_object_tag_get_tagger_time(se_tag);
7338 got_object_tag_close(se_tag);
7340 if (se_time > re_time) {
7341 err = got_reflist_entry_dup(&new, re);
7342 if (err)
7343 return err;
7344 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7345 break;
7347 se = STAILQ_NEXT(se, entry);
7348 continue;
7351 done:
7352 return err;
7354 #endif
7356 static const struct got_error *
7357 get_tag_refname(char **refname, const char *tag_name)
7359 const struct got_error *err;
7361 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7362 *refname = strdup(tag_name);
7363 if (*refname == NULL)
7364 return got_error_from_errno("strdup");
7365 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7366 err = got_error_from_errno("asprintf");
7367 *refname = NULL;
7368 return err;
7371 return NULL;
7374 static const struct got_error *
7375 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7376 const char *allowed_signers, const char *revoked_signers, int verbosity)
7378 static const struct got_error *err = NULL;
7379 struct got_reflist_head refs;
7380 struct got_reflist_entry *re;
7381 char *wanted_refname = NULL;
7382 int bad_sigs = 0;
7384 TAILQ_INIT(&refs);
7386 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7387 if (err)
7388 return err;
7390 if (tag_name) {
7391 struct got_reference *ref;
7392 err = get_tag_refname(&wanted_refname, tag_name);
7393 if (err)
7394 goto done;
7395 /* Wanted tag reference should exist. */
7396 err = got_ref_open(&ref, repo, wanted_refname, 0);
7397 if (err)
7398 goto done;
7399 got_ref_close(ref);
7402 TAILQ_FOREACH(re, &refs, entry) {
7403 const char *refname;
7404 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7405 char datebuf[26];
7406 const char *tagger, *ssh_sig = NULL;
7407 char *sig_msg = NULL;
7408 time_t tagger_time;
7409 struct got_object_id *id;
7410 struct got_tag_object *tag;
7411 struct got_commit_object *commit = NULL;
7413 refname = got_ref_get_name(re->ref);
7414 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7415 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7416 continue;
7417 refname += 10;
7418 refstr = got_ref_to_str(re->ref);
7419 if (refstr == NULL) {
7420 err = got_error_from_errno("got_ref_to_str");
7421 break;
7424 err = got_ref_resolve(&id, repo, re->ref);
7425 if (err)
7426 break;
7427 err = got_object_open_as_tag(&tag, repo, id);
7428 if (err) {
7429 if (err->code != GOT_ERR_OBJ_TYPE) {
7430 free(id);
7431 break;
7433 /* "lightweight" tag */
7434 err = got_object_open_as_commit(&commit, repo, id);
7435 if (err) {
7436 free(id);
7437 break;
7439 tagger = got_object_commit_get_committer(commit);
7440 tagger_time =
7441 got_object_commit_get_committer_time(commit);
7442 err = got_object_id_str(&id_str, id);
7443 free(id);
7444 if (err)
7445 break;
7446 } else {
7447 free(id);
7448 tagger = got_object_tag_get_tagger(tag);
7449 tagger_time = got_object_tag_get_tagger_time(tag);
7450 err = got_object_id_str(&id_str,
7451 got_object_tag_get_object_id(tag));
7452 if (err)
7453 break;
7456 if (tag && verify_tags) {
7457 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7458 got_object_tag_get_message(tag));
7459 if (ssh_sig && allowed_signers == NULL) {
7460 err = got_error_msg(
7461 GOT_ERR_VERIFY_TAG_SIGNATURE,
7462 "SSH signature verification requires "
7463 "setting allowed_signers in "
7464 "got.conf(5)");
7465 break;
7469 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7470 free(refstr);
7471 printf("from: %s\n", tagger);
7472 datestr = get_datestr(&tagger_time, datebuf);
7473 if (datestr)
7474 printf("date: %s UTC\n", datestr);
7475 if (commit)
7476 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7477 else {
7478 switch (got_object_tag_get_object_type(tag)) {
7479 case GOT_OBJ_TYPE_BLOB:
7480 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7481 id_str);
7482 break;
7483 case GOT_OBJ_TYPE_TREE:
7484 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7485 id_str);
7486 break;
7487 case GOT_OBJ_TYPE_COMMIT:
7488 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7489 id_str);
7490 break;
7491 case GOT_OBJ_TYPE_TAG:
7492 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7493 id_str);
7494 break;
7495 default:
7496 break;
7499 free(id_str);
7501 if (ssh_sig) {
7502 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7503 allowed_signers, revoked_signers, verbosity);
7504 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7505 bad_sigs = 1;
7506 else if (err)
7507 break;
7508 printf("signature: %s", sig_msg);
7509 free(sig_msg);
7510 sig_msg = NULL;
7513 if (commit) {
7514 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7515 if (err)
7516 break;
7517 got_object_commit_close(commit);
7518 } else {
7519 tagmsg0 = strdup(got_object_tag_get_message(tag));
7520 got_object_tag_close(tag);
7521 if (tagmsg0 == NULL) {
7522 err = got_error_from_errno("strdup");
7523 break;
7527 tagmsg = tagmsg0;
7528 do {
7529 line = strsep(&tagmsg, "\n");
7530 if (line)
7531 printf(" %s\n", line);
7532 } while (line);
7533 free(tagmsg0);
7535 done:
7536 got_ref_list_free(&refs);
7537 free(wanted_refname);
7539 if (err == NULL && bad_sigs)
7540 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7541 return err;
7544 static const struct got_error *
7545 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7546 const char *tag_name, const char *repo_path)
7548 const struct got_error *err = NULL;
7549 char *template = NULL, *initial_content = NULL;
7550 char *editor = NULL;
7551 int initial_content_len;
7552 int fd = -1;
7554 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7555 err = got_error_from_errno("asprintf");
7556 goto done;
7559 initial_content_len = asprintf(&initial_content,
7560 "\n# tagging commit %s as %s\n",
7561 commit_id_str, tag_name);
7562 if (initial_content_len == -1) {
7563 err = got_error_from_errno("asprintf");
7564 goto done;
7567 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7568 if (err)
7569 goto done;
7571 if (write(fd, initial_content, initial_content_len) == -1) {
7572 err = got_error_from_errno2("write", *tagmsg_path);
7573 goto done;
7575 if (close(fd) == -1) {
7576 err = got_error_from_errno2("close", *tagmsg_path);
7577 goto done;
7579 fd = -1;
7581 err = get_editor(&editor);
7582 if (err)
7583 goto done;
7584 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7585 initial_content_len, 1);
7586 done:
7587 free(initial_content);
7588 free(template);
7589 free(editor);
7591 if (fd != -1 && close(fd) == -1 && err == NULL)
7592 err = got_error_from_errno2("close", *tagmsg_path);
7594 if (err) {
7595 free(*tagmsg);
7596 *tagmsg = NULL;
7598 return err;
7601 static const struct got_error *
7602 add_tag(struct got_repository *repo, const char *tagger,
7603 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7604 const char *signer_id, int verbosity)
7606 const struct got_error *err = NULL;
7607 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7608 char *label = NULL, *commit_id_str = NULL;
7609 struct got_reference *ref = NULL;
7610 char *refname = NULL, *tagmsg = NULL;
7611 char *tagmsg_path = NULL, *tag_id_str = NULL;
7612 int preserve_tagmsg = 0;
7613 struct got_reflist_head refs;
7615 TAILQ_INIT(&refs);
7618 * Don't let the user create a tag name with a leading '-'.
7619 * While technically a valid reference name, this case is usually
7620 * an unintended typo.
7622 if (tag_name[0] == '-')
7623 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7625 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7626 if (err)
7627 goto done;
7629 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7630 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7631 if (err)
7632 goto done;
7634 err = got_object_id_str(&commit_id_str, commit_id);
7635 if (err)
7636 goto done;
7638 err = get_tag_refname(&refname, tag_name);
7639 if (err)
7640 goto done;
7641 if (strncmp("refs/tags/", tag_name, 10) == 0)
7642 tag_name += 10;
7644 err = got_ref_open(&ref, repo, refname, 0);
7645 if (err == NULL) {
7646 err = got_error(GOT_ERR_TAG_EXISTS);
7647 goto done;
7648 } else if (err->code != GOT_ERR_NOT_REF)
7649 goto done;
7651 if (tagmsg_arg == NULL) {
7652 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7653 tag_name, got_repo_get_path(repo));
7654 if (err) {
7655 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7656 tagmsg_path != NULL)
7657 preserve_tagmsg = 1;
7658 goto done;
7660 /* Editor is done; we can now apply unveil(2) */
7661 err = got_sigs_apply_unveil();
7662 if (err)
7663 goto done;
7664 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7665 if (err)
7666 goto done;
7669 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7670 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7671 verbosity);
7672 if (err) {
7673 if (tagmsg_path)
7674 preserve_tagmsg = 1;
7675 goto done;
7678 err = got_ref_alloc(&ref, refname, tag_id);
7679 if (err) {
7680 if (tagmsg_path)
7681 preserve_tagmsg = 1;
7682 goto done;
7685 err = got_ref_write(ref, repo);
7686 if (err) {
7687 if (tagmsg_path)
7688 preserve_tagmsg = 1;
7689 goto done;
7692 err = got_object_id_str(&tag_id_str, tag_id);
7693 if (err) {
7694 if (tagmsg_path)
7695 preserve_tagmsg = 1;
7696 goto done;
7698 printf("Created tag %s\n", tag_id_str);
7699 done:
7700 if (preserve_tagmsg) {
7701 fprintf(stderr, "%s: tag message preserved in %s\n",
7702 getprogname(), tagmsg_path);
7703 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7704 err = got_error_from_errno2("unlink", tagmsg_path);
7705 free(tag_id_str);
7706 if (ref)
7707 got_ref_close(ref);
7708 free(commit_id);
7709 free(commit_id_str);
7710 free(refname);
7711 free(tagmsg);
7712 free(tagmsg_path);
7713 got_ref_list_free(&refs);
7714 return err;
7717 static const struct got_error *
7718 cmd_tag(int argc, char *argv[])
7720 const struct got_error *error = NULL;
7721 struct got_repository *repo = NULL;
7722 struct got_worktree *worktree = NULL;
7723 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7724 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7725 char *allowed_signers = NULL, *revoked_signers = NULL;
7726 const char *signer_id = NULL;
7727 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7728 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7729 int *pack_fds = NULL;
7731 #ifndef PROFILE
7732 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7733 "sendfd unveil", NULL) == -1)
7734 err(1, "pledge");
7735 #endif
7737 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7738 switch (ch) {
7739 case 'c':
7740 commit_id_arg = optarg;
7741 break;
7742 case 'l':
7743 do_list = 1;
7744 break;
7745 case 'm':
7746 tagmsg = optarg;
7747 break;
7748 case 'r':
7749 repo_path = realpath(optarg, NULL);
7750 if (repo_path == NULL) {
7751 error = got_error_from_errno2("realpath",
7752 optarg);
7753 goto done;
7755 got_path_strip_trailing_slashes(repo_path);
7756 break;
7757 case 's':
7758 signer_id = optarg;
7759 break;
7760 case 'V':
7761 verify_tags = 1;
7762 break;
7763 case 'v':
7764 if (verbosity < 0)
7765 verbosity = 0;
7766 else if (verbosity < 3)
7767 verbosity++;
7768 break;
7769 default:
7770 usage_tag();
7771 /* NOTREACHED */
7775 argc -= optind;
7776 argv += optind;
7778 if (do_list || verify_tags) {
7779 if (commit_id_arg != NULL)
7780 errx(1,
7781 "-c option can only be used when creating a tag");
7782 if (tagmsg) {
7783 if (do_list)
7784 option_conflict('l', 'm');
7785 else
7786 option_conflict('V', 'm');
7788 if (signer_id) {
7789 if (do_list)
7790 option_conflict('l', 's');
7791 else
7792 option_conflict('V', 's');
7794 if (argc > 1)
7795 usage_tag();
7796 } else if (argc != 1)
7797 usage_tag();
7799 if (argc == 1)
7800 tag_name = argv[0];
7802 cwd = getcwd(NULL, 0);
7803 if (cwd == NULL) {
7804 error = got_error_from_errno("getcwd");
7805 goto done;
7808 error = got_repo_pack_fds_open(&pack_fds);
7809 if (error != NULL)
7810 goto done;
7812 if (repo_path == NULL) {
7813 error = got_worktree_open(&worktree, cwd,
7814 GOT_WORKTREE_GOT_DIR);
7815 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7816 goto done;
7817 else
7818 error = NULL;
7819 if (worktree) {
7820 repo_path =
7821 strdup(got_worktree_get_repo_path(worktree));
7822 if (repo_path == NULL)
7823 error = got_error_from_errno("strdup");
7824 if (error)
7825 goto done;
7826 } else {
7827 repo_path = strdup(cwd);
7828 if (repo_path == NULL) {
7829 error = got_error_from_errno("strdup");
7830 goto done;
7835 if (do_list || verify_tags) {
7836 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7837 if (error != NULL)
7838 goto done;
7839 error = get_allowed_signers(&allowed_signers, repo, worktree);
7840 if (error)
7841 goto done;
7842 error = get_revoked_signers(&revoked_signers, repo, worktree);
7843 if (error)
7844 goto done;
7845 if (worktree) {
7846 /* Release work tree lock. */
7847 got_worktree_close(worktree);
7848 worktree = NULL;
7852 * Remove "cpath" promise unless needed for signature tmpfile
7853 * creation.
7855 if (verify_tags)
7856 got_sigs_apply_unveil();
7857 else {
7858 #ifndef PROFILE
7859 if (pledge("stdio rpath wpath flock proc exec sendfd "
7860 "unveil", NULL) == -1)
7861 err(1, "pledge");
7862 #endif
7864 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7865 if (error)
7866 goto done;
7867 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7868 revoked_signers, verbosity);
7869 } else {
7870 error = get_gitconfig_path(&gitconfig_path);
7871 if (error)
7872 goto done;
7873 error = got_repo_open(&repo, repo_path, gitconfig_path,
7874 pack_fds);
7875 if (error != NULL)
7876 goto done;
7878 error = get_author(&tagger, repo, worktree);
7879 if (error)
7880 goto done;
7881 if (signer_id == NULL)
7882 signer_id = get_signer_id(repo, worktree);
7884 if (tagmsg) {
7885 if (signer_id) {
7886 error = got_sigs_apply_unveil();
7887 if (error)
7888 goto done;
7890 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7891 if (error)
7892 goto done;
7895 if (commit_id_arg == NULL) {
7896 struct got_reference *head_ref;
7897 struct got_object_id *commit_id;
7898 error = got_ref_open(&head_ref, repo,
7899 worktree ? got_worktree_get_head_ref_name(worktree)
7900 : GOT_REF_HEAD, 0);
7901 if (error)
7902 goto done;
7903 error = got_ref_resolve(&commit_id, repo, head_ref);
7904 got_ref_close(head_ref);
7905 if (error)
7906 goto done;
7907 error = got_object_id_str(&commit_id_str, commit_id);
7908 free(commit_id);
7909 if (error)
7910 goto done;
7911 } else {
7912 error = got_keyword_to_idstr(&keyword_idstr,
7913 commit_id_arg, repo, worktree);
7914 if (error != NULL)
7915 goto done;
7916 commit_id_str = keyword_idstr;
7919 if (worktree) {
7920 /* Release work tree lock. */
7921 got_worktree_close(worktree);
7922 worktree = NULL;
7925 error = add_tag(repo, tagger, tag_name,
7926 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7927 signer_id, verbosity);
7929 done:
7930 if (repo) {
7931 const struct got_error *close_err = got_repo_close(repo);
7932 if (error == NULL)
7933 error = close_err;
7935 if (worktree)
7936 got_worktree_close(worktree);
7937 if (pack_fds) {
7938 const struct got_error *pack_err =
7939 got_repo_pack_fds_close(pack_fds);
7940 if (error == NULL)
7941 error = pack_err;
7943 free(cwd);
7944 free(repo_path);
7945 free(gitconfig_path);
7946 free(commit_id_str);
7947 free(tagger);
7948 free(allowed_signers);
7949 free(revoked_signers);
7950 return error;
7953 __dead static void
7954 usage_add(void)
7956 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7957 exit(1);
7960 static const struct got_error *
7961 add_progress(void *arg, unsigned char status, const char *path)
7963 while (path[0] == '/')
7964 path++;
7965 printf("%c %s\n", status, path);
7966 return NULL;
7969 static const struct got_error *
7970 cmd_add(int argc, char *argv[])
7972 const struct got_error *error = NULL;
7973 struct got_repository *repo = NULL;
7974 struct got_worktree *worktree = NULL;
7975 char *cwd = NULL;
7976 struct got_pathlist_head paths;
7977 struct got_pathlist_entry *pe;
7978 int ch, can_recurse = 0, no_ignores = 0;
7979 int *pack_fds = NULL;
7981 TAILQ_INIT(&paths);
7983 #ifndef PROFILE
7984 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7985 NULL) == -1)
7986 err(1, "pledge");
7987 #endif
7989 while ((ch = getopt(argc, argv, "IR")) != -1) {
7990 switch (ch) {
7991 case 'I':
7992 no_ignores = 1;
7993 break;
7994 case 'R':
7995 can_recurse = 1;
7996 break;
7997 default:
7998 usage_add();
7999 /* NOTREACHED */
8003 argc -= optind;
8004 argv += optind;
8006 if (argc < 1)
8007 usage_add();
8009 cwd = getcwd(NULL, 0);
8010 if (cwd == NULL) {
8011 error = got_error_from_errno("getcwd");
8012 goto done;
8015 error = got_repo_pack_fds_open(&pack_fds);
8016 if (error != NULL)
8017 goto done;
8019 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8020 if (error) {
8021 if (error->code == GOT_ERR_NOT_WORKTREE)
8022 error = wrap_not_worktree_error(error, "add", cwd);
8023 goto done;
8026 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8027 NULL, pack_fds);
8028 if (error != NULL)
8029 goto done;
8031 error = apply_unveil(got_repo_get_path(repo), 1,
8032 got_worktree_get_root_path(worktree));
8033 if (error)
8034 goto done;
8036 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8037 if (error)
8038 goto done;
8040 if (!can_recurse) {
8041 char *ondisk_path;
8042 struct stat sb;
8043 TAILQ_FOREACH(pe, &paths, entry) {
8044 if (asprintf(&ondisk_path, "%s/%s",
8045 got_worktree_get_root_path(worktree),
8046 pe->path) == -1) {
8047 error = got_error_from_errno("asprintf");
8048 goto done;
8050 if (lstat(ondisk_path, &sb) == -1) {
8051 if (errno == ENOENT) {
8052 free(ondisk_path);
8053 continue;
8055 error = got_error_from_errno2("lstat",
8056 ondisk_path);
8057 free(ondisk_path);
8058 goto done;
8060 free(ondisk_path);
8061 if (S_ISDIR(sb.st_mode)) {
8062 error = got_error_msg(GOT_ERR_BAD_PATH,
8063 "adding directories requires -R option");
8064 goto done;
8069 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8070 NULL, repo, no_ignores);
8071 done:
8072 if (repo) {
8073 const struct got_error *close_err = got_repo_close(repo);
8074 if (error == NULL)
8075 error = close_err;
8077 if (worktree)
8078 got_worktree_close(worktree);
8079 if (pack_fds) {
8080 const struct got_error *pack_err =
8081 got_repo_pack_fds_close(pack_fds);
8082 if (error == NULL)
8083 error = pack_err;
8085 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8086 free(cwd);
8087 return error;
8090 __dead static void
8091 usage_remove(void)
8093 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8094 getprogname());
8095 exit(1);
8098 static const struct got_error *
8099 print_remove_status(void *arg, unsigned char status,
8100 unsigned char staged_status, const char *path)
8102 while (path[0] == '/')
8103 path++;
8104 if (status == GOT_STATUS_NONEXISTENT)
8105 return NULL;
8106 if (status == staged_status && (status == GOT_STATUS_DELETE))
8107 status = GOT_STATUS_NO_CHANGE;
8108 printf("%c%c %s\n", status, staged_status, path);
8109 return NULL;
8112 static const struct got_error *
8113 cmd_remove(int argc, char *argv[])
8115 const struct got_error *error = NULL;
8116 struct got_worktree *worktree = NULL;
8117 struct got_repository *repo = NULL;
8118 const char *status_codes = NULL;
8119 char *cwd = NULL;
8120 struct got_pathlist_head paths;
8121 struct got_pathlist_entry *pe;
8122 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8123 int ignore_missing_paths = 0;
8124 int *pack_fds = NULL;
8126 TAILQ_INIT(&paths);
8128 #ifndef PROFILE
8129 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8130 NULL) == -1)
8131 err(1, "pledge");
8132 #endif
8134 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8135 switch (ch) {
8136 case 'f':
8137 delete_local_mods = 1;
8138 ignore_missing_paths = 1;
8139 break;
8140 case 'k':
8141 keep_on_disk = 1;
8142 break;
8143 case 'R':
8144 can_recurse = 1;
8145 break;
8146 case 's':
8147 for (i = 0; optarg[i] != '\0'; i++) {
8148 switch (optarg[i]) {
8149 case GOT_STATUS_MODIFY:
8150 delete_local_mods = 1;
8151 break;
8152 case GOT_STATUS_MISSING:
8153 ignore_missing_paths = 1;
8154 break;
8155 default:
8156 errx(1, "invalid status code '%c'",
8157 optarg[i]);
8160 status_codes = optarg;
8161 break;
8162 default:
8163 usage_remove();
8164 /* NOTREACHED */
8168 argc -= optind;
8169 argv += optind;
8171 if (argc < 1)
8172 usage_remove();
8174 cwd = getcwd(NULL, 0);
8175 if (cwd == NULL) {
8176 error = got_error_from_errno("getcwd");
8177 goto done;
8180 error = got_repo_pack_fds_open(&pack_fds);
8181 if (error != NULL)
8182 goto done;
8184 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8185 if (error) {
8186 if (error->code == GOT_ERR_NOT_WORKTREE)
8187 error = wrap_not_worktree_error(error, "remove", cwd);
8188 goto done;
8191 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8192 NULL, pack_fds);
8193 if (error)
8194 goto done;
8196 error = apply_unveil(got_repo_get_path(repo), 1,
8197 got_worktree_get_root_path(worktree));
8198 if (error)
8199 goto done;
8201 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8202 if (error)
8203 goto done;
8205 if (!can_recurse) {
8206 char *ondisk_path;
8207 struct stat sb;
8208 TAILQ_FOREACH(pe, &paths, entry) {
8209 if (asprintf(&ondisk_path, "%s/%s",
8210 got_worktree_get_root_path(worktree),
8211 pe->path) == -1) {
8212 error = got_error_from_errno("asprintf");
8213 goto done;
8215 if (lstat(ondisk_path, &sb) == -1) {
8216 if (errno == ENOENT) {
8217 free(ondisk_path);
8218 continue;
8220 error = got_error_from_errno2("lstat",
8221 ondisk_path);
8222 free(ondisk_path);
8223 goto done;
8225 free(ondisk_path);
8226 if (S_ISDIR(sb.st_mode)) {
8227 error = got_error_msg(GOT_ERR_BAD_PATH,
8228 "removing directories requires -R option");
8229 goto done;
8234 error = got_worktree_schedule_delete(worktree, &paths,
8235 delete_local_mods, status_codes, print_remove_status, NULL,
8236 repo, keep_on_disk, ignore_missing_paths);
8237 done:
8238 if (repo) {
8239 const struct got_error *close_err = got_repo_close(repo);
8240 if (error == NULL)
8241 error = close_err;
8243 if (worktree)
8244 got_worktree_close(worktree);
8245 if (pack_fds) {
8246 const struct got_error *pack_err =
8247 got_repo_pack_fds_close(pack_fds);
8248 if (error == NULL)
8249 error = pack_err;
8251 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8252 free(cwd);
8253 return error;
8256 __dead static void
8257 usage_patch(void)
8259 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8260 "[patchfile]\n", getprogname());
8261 exit(1);
8264 static const struct got_error *
8265 patch_from_stdin(int *patchfd)
8267 const struct got_error *err = NULL;
8268 ssize_t r;
8269 char buf[BUFSIZ];
8270 sig_t sighup, sigint, sigquit;
8272 *patchfd = got_opentempfd();
8273 if (*patchfd == -1)
8274 return got_error_from_errno("got_opentempfd");
8276 sighup = signal(SIGHUP, SIG_DFL);
8277 sigint = signal(SIGINT, SIG_DFL);
8278 sigquit = signal(SIGQUIT, SIG_DFL);
8280 for (;;) {
8281 r = read(0, buf, sizeof(buf));
8282 if (r == -1) {
8283 err = got_error_from_errno("read");
8284 break;
8286 if (r == 0)
8287 break;
8288 if (write(*patchfd, buf, r) == -1) {
8289 err = got_error_from_errno("write");
8290 break;
8294 signal(SIGHUP, sighup);
8295 signal(SIGINT, sigint);
8296 signal(SIGQUIT, sigquit);
8298 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8299 err = got_error_from_errno("lseek");
8301 if (err != NULL) {
8302 close(*patchfd);
8303 *patchfd = -1;
8306 return err;
8309 struct got_patch_progress_arg {
8310 int did_something;
8311 int conflicts;
8312 int rejects;
8315 static const struct got_error *
8316 patch_progress(void *arg, const char *old, const char *new,
8317 unsigned char status, const struct got_error *error, int old_from,
8318 int old_lines, int new_from, int new_lines, int offset,
8319 int ws_mangled, const struct got_error *hunk_err)
8321 const char *path = new == NULL ? old : new;
8322 struct got_patch_progress_arg *a = arg;
8324 while (*path == '/')
8325 path++;
8327 if (status != GOT_STATUS_NO_CHANGE &&
8328 status != 0 /* per-hunk progress */) {
8329 printf("%c %s\n", status, path);
8330 a->did_something = 1;
8333 if (hunk_err == NULL) {
8334 if (status == GOT_STATUS_CANNOT_UPDATE)
8335 a->rejects++;
8336 else if (status == GOT_STATUS_CONFLICT)
8337 a->conflicts++;
8340 if (error != NULL)
8341 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8343 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8344 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8345 old_lines, new_from, new_lines);
8346 if (hunk_err != NULL)
8347 printf("%s\n", hunk_err->msg);
8348 else if (offset != 0)
8349 printf("applied with offset %d\n", offset);
8350 else
8351 printf("hunk contains mangled whitespace\n");
8354 return NULL;
8357 static void
8358 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8360 if (!ppa->did_something)
8361 return;
8363 if (ppa->conflicts > 0)
8364 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8366 if (ppa->rejects > 0) {
8367 printf("Files where patch failed to apply: %d\n",
8368 ppa->rejects);
8372 static const struct got_error *
8373 cmd_patch(int argc, char *argv[])
8375 const struct got_error *error = NULL, *close_error = NULL;
8376 struct got_worktree *worktree = NULL;
8377 struct got_repository *repo = NULL;
8378 struct got_reflist_head refs;
8379 struct got_object_id *commit_id = NULL;
8380 const char *commit_id_str = NULL;
8381 struct stat sb;
8382 const char *errstr;
8383 char *cwd = NULL, *keyword_idstr = NULL;
8384 int ch, nop = 0, strip = -1, reverse = 0;
8385 int patchfd;
8386 int *pack_fds = NULL;
8387 struct got_patch_progress_arg ppa;
8389 TAILQ_INIT(&refs);
8391 #ifndef PROFILE
8392 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8393 "unveil", NULL) == -1)
8394 err(1, "pledge");
8395 #endif
8397 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8398 switch (ch) {
8399 case 'c':
8400 commit_id_str = optarg;
8401 break;
8402 case 'n':
8403 nop = 1;
8404 break;
8405 case 'p':
8406 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8407 if (errstr != NULL)
8408 errx(1, "pathname strip count is %s: %s",
8409 errstr, optarg);
8410 break;
8411 case 'R':
8412 reverse = 1;
8413 break;
8414 default:
8415 usage_patch();
8416 /* NOTREACHED */
8420 argc -= optind;
8421 argv += optind;
8423 if (argc == 0) {
8424 error = patch_from_stdin(&patchfd);
8425 if (error)
8426 return error;
8427 } else if (argc == 1) {
8428 patchfd = open(argv[0], O_RDONLY);
8429 if (patchfd == -1) {
8430 error = got_error_from_errno2("open", argv[0]);
8431 return error;
8433 if (fstat(patchfd, &sb) == -1) {
8434 error = got_error_from_errno2("fstat", argv[0]);
8435 goto done;
8437 if (!S_ISREG(sb.st_mode)) {
8438 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8439 goto done;
8441 } else
8442 usage_patch();
8444 if ((cwd = getcwd(NULL, 0)) == NULL) {
8445 error = got_error_from_errno("getcwd");
8446 goto done;
8449 error = got_repo_pack_fds_open(&pack_fds);
8450 if (error != NULL)
8451 goto done;
8453 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8454 if (error != NULL)
8455 goto done;
8457 const char *repo_path = got_worktree_get_repo_path(worktree);
8458 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8459 if (error != NULL)
8460 goto done;
8462 error = apply_unveil(got_repo_get_path(repo), 0,
8463 got_worktree_get_root_path(worktree));
8464 if (error != NULL)
8465 goto done;
8467 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8468 if (error)
8469 goto done;
8471 if (commit_id_str != NULL) {
8472 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8473 repo, worktree);
8474 if (error != NULL)
8475 goto done;
8477 error = got_repo_match_object_id(&commit_id, NULL,
8478 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8479 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8480 if (error)
8481 goto done;
8484 memset(&ppa, 0, sizeof(ppa));
8485 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8486 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8487 print_patch_progress_stats(&ppa);
8488 done:
8489 got_ref_list_free(&refs);
8490 free(keyword_idstr);
8491 free(commit_id);
8492 if (repo) {
8493 close_error = got_repo_close(repo);
8494 if (error == NULL)
8495 error = close_error;
8497 if (worktree != NULL) {
8498 close_error = got_worktree_close(worktree);
8499 if (error == NULL)
8500 error = close_error;
8502 if (pack_fds) {
8503 const struct got_error *pack_err =
8504 got_repo_pack_fds_close(pack_fds);
8505 if (error == NULL)
8506 error = pack_err;
8508 free(cwd);
8509 return error;
8512 __dead static void
8513 usage_revert(void)
8515 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8516 getprogname());
8517 exit(1);
8520 static const struct got_error *
8521 revert_progress(void *arg, unsigned char status, const char *path)
8523 if (status == GOT_STATUS_UNVERSIONED)
8524 return NULL;
8526 while (path[0] == '/')
8527 path++;
8528 printf("%c %s\n", status, path);
8529 return NULL;
8532 struct choose_patch_arg {
8533 FILE *patch_script_file;
8534 const char *action;
8537 static const struct got_error *
8538 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8539 int nchanges, const char *action)
8541 const struct got_error *err;
8542 char *line = NULL;
8543 size_t linesize = 0;
8544 ssize_t linelen;
8546 switch (status) {
8547 case GOT_STATUS_ADD:
8548 printf("A %s\n%s this addition? [y/n] ", path, action);
8549 break;
8550 case GOT_STATUS_DELETE:
8551 printf("D %s\n%s this deletion? [y/n] ", path, action);
8552 break;
8553 case GOT_STATUS_MODIFY:
8554 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8555 return got_error_from_errno("fseek");
8556 printf(GOT_COMMIT_SEP_STR);
8557 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8558 printf("%s", line);
8559 if (linelen == -1 && ferror(patch_file)) {
8560 err = got_error_from_errno("getline");
8561 free(line);
8562 return err;
8564 free(line);
8565 printf(GOT_COMMIT_SEP_STR);
8566 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8567 path, n, nchanges, action);
8568 break;
8569 default:
8570 return got_error_path(path, GOT_ERR_FILE_STATUS);
8573 fflush(stdout);
8574 return NULL;
8577 static const struct got_error *
8578 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8579 FILE *patch_file, int n, int nchanges)
8581 const struct got_error *err = NULL;
8582 char *line = NULL;
8583 size_t linesize = 0;
8584 ssize_t linelen;
8585 int resp = ' ';
8586 struct choose_patch_arg *a = arg;
8588 *choice = GOT_PATCH_CHOICE_NONE;
8590 if (a->patch_script_file) {
8591 char *nl;
8592 err = show_change(status, path, patch_file, n, nchanges,
8593 a->action);
8594 if (err)
8595 return err;
8596 linelen = getline(&line, &linesize, a->patch_script_file);
8597 if (linelen == -1) {
8598 if (ferror(a->patch_script_file))
8599 return got_error_from_errno("getline");
8600 return NULL;
8602 nl = strchr(line, '\n');
8603 if (nl)
8604 *nl = '\0';
8605 if (strcmp(line, "y") == 0) {
8606 *choice = GOT_PATCH_CHOICE_YES;
8607 printf("y\n");
8608 } else if (strcmp(line, "n") == 0) {
8609 *choice = GOT_PATCH_CHOICE_NO;
8610 printf("n\n");
8611 } else if (strcmp(line, "q") == 0 &&
8612 status == GOT_STATUS_MODIFY) {
8613 *choice = GOT_PATCH_CHOICE_QUIT;
8614 printf("q\n");
8615 } else
8616 printf("invalid response '%s'\n", line);
8617 free(line);
8618 return NULL;
8621 while (resp != 'y' && resp != 'n' && resp != 'q') {
8622 err = show_change(status, path, patch_file, n, nchanges,
8623 a->action);
8624 if (err)
8625 return err;
8626 resp = getchar();
8627 if (resp == '\n')
8628 resp = getchar();
8629 if (status == GOT_STATUS_MODIFY) {
8630 if (resp != 'y' && resp != 'n' && resp != 'q') {
8631 printf("invalid response '%c'\n", resp);
8632 resp = ' ';
8634 } else if (resp != 'y' && resp != 'n') {
8635 printf("invalid response '%c'\n", resp);
8636 resp = ' ';
8640 if (resp == 'y')
8641 *choice = GOT_PATCH_CHOICE_YES;
8642 else if (resp == 'n')
8643 *choice = GOT_PATCH_CHOICE_NO;
8644 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8645 *choice = GOT_PATCH_CHOICE_QUIT;
8647 return NULL;
8650 struct wt_commitable_path_arg {
8651 struct got_pathlist_head *commit_paths;
8652 int *has_changes;
8656 * Shortcut work tree status callback to determine if the set of paths scanned
8657 * has at least one versioned path that is being modified and, if not NULL, is
8658 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8659 * soon as a path is passed with a status that satisfies this criteria.
8661 static const struct got_error *
8662 worktree_has_commitable_path(void *arg, unsigned char status,
8663 unsigned char staged_status, const char *path,
8664 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8665 struct got_object_id *commit_id, int dirfd, const char *de_name)
8667 struct wt_commitable_path_arg *a = arg;
8669 if (status == staged_status && (status == GOT_STATUS_DELETE))
8670 status = GOT_STATUS_NO_CHANGE;
8672 if (!(status == GOT_STATUS_NO_CHANGE ||
8673 status == GOT_STATUS_UNVERSIONED) ||
8674 staged_status != GOT_STATUS_NO_CHANGE) {
8675 if (a->commit_paths != NULL) {
8676 struct got_pathlist_entry *pe;
8678 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8679 if (strncmp(path, pe->path,
8680 pe->path_len) == 0) {
8681 *a->has_changes = 1;
8682 break;
8685 } else
8686 *a->has_changes = 1;
8688 if (*a->has_changes)
8689 return got_error(GOT_ERR_FILE_MODIFIED);
8692 return NULL;
8696 * Check that the changeset of the commit identified by id is
8697 * comprised of at least one modified path that is being committed.
8699 static const struct got_error *
8700 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8701 struct got_object_id *id, struct got_worktree *worktree,
8702 struct got_repository *repo)
8704 const struct got_error *err;
8705 struct got_pathlist_head paths;
8706 struct got_commit_object *commit = NULL, *pcommit = NULL;
8707 struct got_tree_object *tree = NULL, *ptree = NULL;
8708 struct got_object_qid *pid;
8710 TAILQ_INIT(&paths);
8712 err = got_object_open_as_commit(&commit, repo, id);
8713 if (err)
8714 goto done;
8716 err = got_object_open_as_tree(&tree, repo,
8717 got_object_commit_get_tree_id(commit));
8718 if (err)
8719 goto done;
8721 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8722 if (pid != NULL) {
8723 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8724 if (err)
8725 goto done;
8727 err = got_object_open_as_tree(&ptree, repo,
8728 got_object_commit_get_tree_id(pcommit));
8729 if (err)
8730 goto done;
8733 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8734 got_diff_tree_collect_changed_paths, &paths, 0);
8735 if (err)
8736 goto done;
8738 err = got_worktree_status(worktree, &paths, repo, 0,
8739 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8740 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8742 * At least one changed path in the referenced commit is
8743 * modified in the work tree, that's all we need to know!
8745 err = NULL;
8748 done:
8749 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8750 if (commit)
8751 got_object_commit_close(commit);
8752 if (pcommit)
8753 got_object_commit_close(pcommit);
8754 if (tree)
8755 got_object_tree_close(tree);
8756 if (ptree)
8757 got_object_tree_close(ptree);
8758 return err;
8762 * Remove any "logmsg" reference comprised entirely of paths that have
8763 * been reverted in this work tree. If any path in the logmsg ref changeset
8764 * remains in a changed state in the worktree, do not remove the reference.
8766 static const struct got_error *
8767 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8769 const struct got_error *err;
8770 struct got_reflist_head refs;
8771 struct got_reflist_entry *re;
8772 struct got_commit_object *commit = NULL;
8773 struct got_object_id *commit_id = NULL;
8774 struct wt_commitable_path_arg wcpa;
8775 char *uuidstr = NULL;
8777 TAILQ_INIT(&refs);
8779 err = got_worktree_get_uuid(&uuidstr, worktree);
8780 if (err)
8781 goto done;
8783 err = got_ref_list(&refs, repo, "refs/got/worktree",
8784 got_ref_cmp_by_name, repo);
8785 if (err)
8786 goto done;
8788 TAILQ_FOREACH(re, &refs, entry) {
8789 const char *refname;
8790 int has_changes = 0;
8792 refname = got_ref_get_name(re->ref);
8794 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8795 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8796 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8797 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8798 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8799 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8800 else
8801 continue;
8803 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8804 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8805 else
8806 continue;
8808 err = got_repo_match_object_id(&commit_id, NULL, refname,
8809 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8810 if (err)
8811 goto done;
8813 err = got_object_open_as_commit(&commit, repo, commit_id);
8814 if (err)
8815 goto done;
8817 wcpa.commit_paths = NULL;
8818 wcpa.has_changes = &has_changes;
8820 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8821 worktree, repo);
8822 if (err)
8823 goto done;
8825 if (!has_changes) {
8826 err = got_ref_delete(re->ref, repo);
8827 if (err)
8828 goto done;
8831 got_object_commit_close(commit);
8832 commit = NULL;
8833 free(commit_id);
8834 commit_id = NULL;
8837 done:
8838 free(uuidstr);
8839 free(commit_id);
8840 got_ref_list_free(&refs);
8841 if (commit)
8842 got_object_commit_close(commit);
8843 return err;
8846 static const struct got_error *
8847 cmd_revert(int argc, char *argv[])
8849 const struct got_error *error = NULL;
8850 struct got_worktree *worktree = NULL;
8851 struct got_repository *repo = NULL;
8852 char *cwd = NULL, *path = NULL;
8853 struct got_pathlist_head paths;
8854 struct got_pathlist_entry *pe;
8855 int ch, can_recurse = 0, pflag = 0;
8856 FILE *patch_script_file = NULL;
8857 const char *patch_script_path = NULL;
8858 struct choose_patch_arg cpa;
8859 int *pack_fds = NULL;
8861 TAILQ_INIT(&paths);
8863 #ifndef PROFILE
8864 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8865 "unveil", NULL) == -1)
8866 err(1, "pledge");
8867 #endif
8869 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8870 switch (ch) {
8871 case 'F':
8872 patch_script_path = optarg;
8873 break;
8874 case 'p':
8875 pflag = 1;
8876 break;
8877 case 'R':
8878 can_recurse = 1;
8879 break;
8880 default:
8881 usage_revert();
8882 /* NOTREACHED */
8886 argc -= optind;
8887 argv += optind;
8889 if (argc < 1)
8890 usage_revert();
8891 if (patch_script_path && !pflag)
8892 errx(1, "-F option can only be used together with -p option");
8894 cwd = getcwd(NULL, 0);
8895 if (cwd == NULL) {
8896 error = got_error_from_errno("getcwd");
8897 goto done;
8900 error = got_repo_pack_fds_open(&pack_fds);
8901 if (error != NULL)
8902 goto done;
8904 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8905 if (error) {
8906 if (error->code == GOT_ERR_NOT_WORKTREE)
8907 error = wrap_not_worktree_error(error, "revert", cwd);
8908 goto done;
8911 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8912 NULL, pack_fds);
8913 if (error != NULL)
8914 goto done;
8916 if (patch_script_path) {
8917 patch_script_file = fopen(patch_script_path, "re");
8918 if (patch_script_file == NULL) {
8919 error = got_error_from_errno2("fopen",
8920 patch_script_path);
8921 goto done;
8926 * XXX "c" perm needed on repo dir to delete merge references.
8928 error = apply_unveil(got_repo_get_path(repo), 0,
8929 got_worktree_get_root_path(worktree));
8930 if (error)
8931 goto done;
8933 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8934 if (error)
8935 goto done;
8937 if (!can_recurse) {
8938 char *ondisk_path;
8939 struct stat sb;
8940 TAILQ_FOREACH(pe, &paths, entry) {
8941 if (asprintf(&ondisk_path, "%s/%s",
8942 got_worktree_get_root_path(worktree),
8943 pe->path) == -1) {
8944 error = got_error_from_errno("asprintf");
8945 goto done;
8947 if (lstat(ondisk_path, &sb) == -1) {
8948 if (errno == ENOENT) {
8949 free(ondisk_path);
8950 continue;
8952 error = got_error_from_errno2("lstat",
8953 ondisk_path);
8954 free(ondisk_path);
8955 goto done;
8957 free(ondisk_path);
8958 if (S_ISDIR(sb.st_mode)) {
8959 error = got_error_msg(GOT_ERR_BAD_PATH,
8960 "reverting directories requires -R option");
8961 goto done;
8966 cpa.patch_script_file = patch_script_file;
8967 cpa.action = "revert";
8968 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8969 pflag ? choose_patch : NULL, &cpa, repo);
8971 error = rm_logmsg_ref(worktree, repo);
8972 done:
8973 if (patch_script_file && fclose(patch_script_file) == EOF &&
8974 error == NULL)
8975 error = got_error_from_errno2("fclose", patch_script_path);
8976 if (repo) {
8977 const struct got_error *close_err = got_repo_close(repo);
8978 if (error == NULL)
8979 error = close_err;
8981 if (worktree)
8982 got_worktree_close(worktree);
8983 if (pack_fds) {
8984 const struct got_error *pack_err =
8985 got_repo_pack_fds_close(pack_fds);
8986 if (error == NULL)
8987 error = pack_err;
8989 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8990 free(path);
8991 free(cwd);
8992 return error;
8995 __dead static void
8996 usage_commit(void)
8998 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8999 "[-m message] [path ...]\n", getprogname());
9000 exit(1);
9003 struct collect_commit_logmsg_arg {
9004 const char *cmdline_log;
9005 const char *prepared_log;
9006 const char *merged_log;
9007 int non_interactive;
9008 const char *editor;
9009 const char *worktree_path;
9010 const char *branch_name;
9011 const char *repo_path;
9012 char *logmsg_path;
9016 static const struct got_error *
9017 read_prepared_logmsg(char **logmsg, const char *path)
9019 const struct got_error *err = NULL;
9020 FILE *f = NULL;
9021 struct stat sb;
9022 size_t r;
9024 *logmsg = NULL;
9025 memset(&sb, 0, sizeof(sb));
9027 f = fopen(path, "re");
9028 if (f == NULL)
9029 return got_error_from_errno2("fopen", path);
9031 if (fstat(fileno(f), &sb) == -1) {
9032 err = got_error_from_errno2("fstat", path);
9033 goto done;
9035 if (sb.st_size == 0) {
9036 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9037 goto done;
9040 *logmsg = malloc(sb.st_size + 1);
9041 if (*logmsg == NULL) {
9042 err = got_error_from_errno("malloc");
9043 goto done;
9046 r = fread(*logmsg, 1, sb.st_size, f);
9047 if (r != sb.st_size) {
9048 if (ferror(f))
9049 err = got_error_from_errno2("fread", path);
9050 else
9051 err = got_error(GOT_ERR_IO);
9052 goto done;
9054 (*logmsg)[sb.st_size] = '\0';
9055 done:
9056 if (fclose(f) == EOF && err == NULL)
9057 err = got_error_from_errno2("fclose", path);
9058 if (err) {
9059 free(*logmsg);
9060 *logmsg = NULL;
9062 return err;
9065 static const struct got_error *
9066 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9067 const char *diff_path, char **logmsg, void *arg)
9069 char *initial_content = NULL;
9070 struct got_pathlist_entry *pe;
9071 const struct got_error *err = NULL;
9072 char *template = NULL;
9073 char *prepared_msg = NULL, *merged_msg = NULL;
9074 struct collect_commit_logmsg_arg *a = arg;
9075 int initial_content_len;
9076 int fd = -1;
9077 size_t len;
9079 /* if a message was specified on the command line, just use it */
9080 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9081 len = strlen(a->cmdline_log) + 1;
9082 *logmsg = malloc(len + 1);
9083 if (*logmsg == NULL)
9084 return got_error_from_errno("malloc");
9085 strlcpy(*logmsg, a->cmdline_log, len);
9086 return NULL;
9087 } else if (a->prepared_log != NULL && a->non_interactive)
9088 return read_prepared_logmsg(logmsg, a->prepared_log);
9090 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9091 return got_error_from_errno("asprintf");
9093 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9094 if (err)
9095 goto done;
9097 if (a->prepared_log) {
9098 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9099 if (err)
9100 goto done;
9101 } else if (a->merged_log) {
9102 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9103 if (err)
9104 goto done;
9107 initial_content_len = asprintf(&initial_content,
9108 "%s%s\n# changes to be committed on branch %s:\n",
9109 prepared_msg ? prepared_msg : "",
9110 merged_msg ? merged_msg : "", a->branch_name);
9111 if (initial_content_len == -1) {
9112 err = got_error_from_errno("asprintf");
9113 goto done;
9116 if (write(fd, initial_content, initial_content_len) == -1) {
9117 err = got_error_from_errno2("write", a->logmsg_path);
9118 goto done;
9121 TAILQ_FOREACH(pe, commitable_paths, entry) {
9122 struct got_commitable *ct = pe->data;
9123 dprintf(fd, "# %c %s\n",
9124 got_commitable_get_status(ct),
9125 got_commitable_get_path(ct));
9128 if (diff_path) {
9129 dprintf(fd, "# detailed changes can be viewed in %s\n",
9130 diff_path);
9133 if (close(fd) == -1) {
9134 err = got_error_from_errno2("close", a->logmsg_path);
9135 goto done;
9137 fd = -1;
9139 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9140 initial_content_len, a->prepared_log ? 0 : 1);
9141 done:
9142 free(initial_content);
9143 free(template);
9144 free(prepared_msg);
9145 free(merged_msg);
9147 if (fd != -1 && close(fd) == -1 && err == NULL)
9148 err = got_error_from_errno2("close", a->logmsg_path);
9150 /* Editor is done; we can now apply unveil(2) */
9151 if (err == NULL)
9152 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9153 if (err) {
9154 free(*logmsg);
9155 *logmsg = NULL;
9157 return err;
9160 static const struct got_error *
9161 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9162 const char *type, int has_content)
9164 const struct got_error *err = NULL;
9165 char *logmsg = NULL;
9167 err = got_object_commit_get_logmsg(&logmsg, commit);
9168 if (err)
9169 return err;
9171 if (fprintf(f, "%s# log message of %s commit %s:%s",
9172 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9173 err = got_ferror(f, GOT_ERR_IO);
9175 free(logmsg);
9176 return err;
9180 * Lookup "logmsg" references of backed-out and cherrypicked commits
9181 * belonging to the current work tree. If found, and the worktree has
9182 * at least one modified file that was changed in the referenced commit,
9183 * add its log message to a new temporary file at *logmsg_path.
9184 * Add all refs found to matched_refs to be scheduled for removal on
9185 * successful commit.
9187 static const struct got_error *
9188 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9189 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9190 struct got_repository *repo)
9192 const struct got_error *err;
9193 struct got_commit_object *commit = NULL;
9194 struct got_object_id *id = NULL;
9195 struct got_reflist_head refs;
9196 struct got_reflist_entry *re, *re_match;
9197 FILE *f = NULL;
9198 char *uuidstr = NULL;
9199 int added_logmsg = 0;
9201 TAILQ_INIT(&refs);
9203 *logmsg_path = NULL;
9205 err = got_worktree_get_uuid(&uuidstr, worktree);
9206 if (err)
9207 goto done;
9209 err = got_ref_list(&refs, repo, "refs/got/worktree",
9210 got_ref_cmp_by_name, repo);
9211 if (err)
9212 goto done;
9214 TAILQ_FOREACH(re, &refs, entry) {
9215 const char *refname, *type;
9216 struct wt_commitable_path_arg wcpa;
9217 int add_logmsg = 0;
9219 refname = got_ref_get_name(re->ref);
9221 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9222 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9223 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9224 type = "cherrypicked";
9225 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9226 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9227 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9228 type = "backed-out";
9229 } else
9230 continue;
9232 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9233 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9234 else
9235 continue;
9237 err = got_repo_match_object_id(&id, NULL, refname,
9238 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9239 if (err)
9240 goto done;
9242 err = got_object_open_as_commit(&commit, repo, id);
9243 if (err)
9244 goto done;
9246 wcpa.commit_paths = paths;
9247 wcpa.has_changes = &add_logmsg;
9249 err = commit_path_changed_in_worktree(&wcpa, id,
9250 worktree, repo);
9251 if (err)
9252 goto done;
9254 if (add_logmsg) {
9255 if (f == NULL) {
9256 err = got_opentemp_named(logmsg_path, &f,
9257 "got-commit-logmsg", "");
9258 if (err)
9259 goto done;
9261 err = cat_logmsg(f, commit, refname, type,
9262 added_logmsg);
9263 if (err)
9264 goto done;
9265 if (!added_logmsg)
9266 ++added_logmsg;
9268 err = got_reflist_entry_dup(&re_match, re);
9269 if (err)
9270 goto done;
9271 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9274 got_object_commit_close(commit);
9275 commit = NULL;
9276 free(id);
9277 id = NULL;
9280 done:
9281 free(id);
9282 free(uuidstr);
9283 got_ref_list_free(&refs);
9284 if (commit)
9285 got_object_commit_close(commit);
9286 if (f && fclose(f) == EOF && err == NULL)
9287 err = got_error_from_errno("fclose");
9288 if (!added_logmsg) {
9289 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9290 err = got_error_from_errno2("unlink", *logmsg_path);
9291 *logmsg_path = NULL;
9293 return err;
9296 static const struct got_error *
9297 cmd_commit(int argc, char *argv[])
9299 const struct got_error *error = NULL;
9300 struct got_worktree *worktree = NULL;
9301 struct got_repository *repo = NULL;
9302 char *cwd = NULL, *id_str = NULL;
9303 struct got_object_id *id = NULL;
9304 const char *logmsg = NULL;
9305 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9306 struct collect_commit_logmsg_arg cl_arg;
9307 const char *author = NULL;
9308 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9309 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9310 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9311 int show_diff = 1, commit_conflicts = 0;
9312 struct got_pathlist_head paths;
9313 struct got_reflist_head refs;
9314 struct got_reflist_entry *re;
9315 int *pack_fds = NULL;
9317 TAILQ_INIT(&refs);
9318 TAILQ_INIT(&paths);
9319 cl_arg.logmsg_path = NULL;
9321 #ifndef PROFILE
9322 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9323 "unveil", NULL) == -1)
9324 err(1, "pledge");
9325 #endif
9327 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9328 switch (ch) {
9329 case 'A':
9330 author = optarg;
9331 error = valid_author(author);
9332 if (error)
9333 return error;
9334 break;
9335 case 'C':
9336 commit_conflicts = 1;
9337 break;
9338 case 'F':
9339 if (logmsg != NULL)
9340 option_conflict('F', 'm');
9341 prepared_logmsg = realpath(optarg, NULL);
9342 if (prepared_logmsg == NULL)
9343 return got_error_from_errno2("realpath",
9344 optarg);
9345 break;
9346 case 'm':
9347 if (prepared_logmsg)
9348 option_conflict('m', 'F');
9349 logmsg = optarg;
9350 break;
9351 case 'N':
9352 non_interactive = 1;
9353 break;
9354 case 'n':
9355 show_diff = 0;
9356 break;
9357 case 'S':
9358 allow_bad_symlinks = 1;
9359 break;
9360 default:
9361 usage_commit();
9362 /* NOTREACHED */
9366 argc -= optind;
9367 argv += optind;
9369 cwd = getcwd(NULL, 0);
9370 if (cwd == NULL) {
9371 error = got_error_from_errno("getcwd");
9372 goto done;
9375 error = got_repo_pack_fds_open(&pack_fds);
9376 if (error != NULL)
9377 goto done;
9379 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9380 if (error) {
9381 if (error->code == GOT_ERR_NOT_WORKTREE)
9382 error = wrap_not_worktree_error(error, "commit", cwd);
9383 goto done;
9386 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9387 if (error)
9388 goto done;
9389 if (rebase_in_progress) {
9390 error = got_error(GOT_ERR_REBASING);
9391 goto done;
9394 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9395 worktree);
9396 if (error)
9397 goto done;
9399 error = get_gitconfig_path(&gitconfig_path);
9400 if (error)
9401 goto done;
9402 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9403 gitconfig_path, pack_fds);
9404 if (error != NULL)
9405 goto done;
9407 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9408 if (error)
9409 goto done;
9410 if (merge_in_progress) {
9411 error = got_error(GOT_ERR_MERGE_BUSY);
9412 goto done;
9415 error = get_author(&committer, repo, worktree);
9416 if (error)
9417 goto done;
9419 if (author == NULL)
9420 author = committer;
9423 * unveil(2) traverses exec(2); if an editor is used we have
9424 * to apply unveil after the log message has been written.
9426 if (logmsg == NULL || strlen(logmsg) == 0)
9427 error = get_editor(&editor);
9428 else
9429 error = apply_unveil(got_repo_get_path(repo), 0,
9430 got_worktree_get_root_path(worktree));
9431 if (error)
9432 goto done;
9434 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9435 if (error)
9436 goto done;
9438 if (prepared_logmsg == NULL) {
9439 error = lookup_logmsg_ref(&merged_logmsg,
9440 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9441 if (error)
9442 goto done;
9445 cl_arg.editor = editor;
9446 cl_arg.cmdline_log = logmsg;
9447 cl_arg.prepared_log = prepared_logmsg;
9448 cl_arg.merged_log = merged_logmsg;
9449 cl_arg.non_interactive = non_interactive;
9450 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9451 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9452 if (!histedit_in_progress) {
9453 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9454 error = got_error(GOT_ERR_COMMIT_BRANCH);
9455 goto done;
9457 cl_arg.branch_name += 11;
9459 cl_arg.repo_path = got_repo_get_path(repo);
9460 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9461 allow_bad_symlinks, show_diff, commit_conflicts,
9462 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9463 if (error) {
9464 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9465 cl_arg.logmsg_path != NULL)
9466 preserve_logmsg = 1;
9467 goto done;
9470 error = got_object_id_str(&id_str, id);
9471 if (error)
9472 goto done;
9473 printf("Created commit %s\n", id_str);
9475 TAILQ_FOREACH(re, &refs, entry) {
9476 error = got_ref_delete(re->ref, repo);
9477 if (error)
9478 goto done;
9481 done:
9482 if (preserve_logmsg) {
9483 fprintf(stderr, "%s: log message preserved in %s\n",
9484 getprogname(), cl_arg.logmsg_path);
9485 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9486 error == NULL)
9487 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9488 free(cl_arg.logmsg_path);
9489 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9490 error = got_error_from_errno2("unlink", merged_logmsg);
9491 free(merged_logmsg);
9492 if (repo) {
9493 const struct got_error *close_err = got_repo_close(repo);
9494 if (error == NULL)
9495 error = close_err;
9497 if (worktree)
9498 got_worktree_close(worktree);
9499 if (pack_fds) {
9500 const struct got_error *pack_err =
9501 got_repo_pack_fds_close(pack_fds);
9502 if (error == NULL)
9503 error = pack_err;
9505 got_ref_list_free(&refs);
9506 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9507 free(cwd);
9508 free(id_str);
9509 free(gitconfig_path);
9510 free(editor);
9511 free(committer);
9512 free(prepared_logmsg);
9513 return error;
9516 __dead static void
9517 usage_send(void)
9519 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9520 "[-r repository-path] [-t tag] [remote-repository]\n",
9521 getprogname());
9522 exit(1);
9525 static void
9526 print_load_info(int print_colored, int print_found, int print_trees,
9527 int ncolored, int nfound, int ntrees)
9529 if (print_colored) {
9530 printf("%d commit%s colored", ncolored,
9531 ncolored == 1 ? "" : "s");
9533 if (print_found) {
9534 printf("%s%d object%s found",
9535 ncolored > 0 ? "; " : "",
9536 nfound, nfound == 1 ? "" : "s");
9538 if (print_trees) {
9539 printf("; %d tree%s scanned", ntrees,
9540 ntrees == 1 ? "" : "s");
9544 struct got_send_progress_arg {
9545 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9546 int verbosity;
9547 int last_ncolored;
9548 int last_nfound;
9549 int last_ntrees;
9550 int loading_done;
9551 int last_ncommits;
9552 int last_nobj_total;
9553 int last_p_deltify;
9554 int last_p_written;
9555 int last_p_sent;
9556 int printed_something;
9557 int sent_something;
9558 struct got_pathlist_head *delete_branches;
9561 static const struct got_error *
9562 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9563 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9564 int nobj_written, off_t bytes_sent, const char *refname,
9565 const char *errmsg, int success)
9567 struct got_send_progress_arg *a = arg;
9568 char scaled_packsize[FMT_SCALED_STRSIZE];
9569 char scaled_sent[FMT_SCALED_STRSIZE];
9570 int p_deltify = 0, p_written = 0, p_sent = 0;
9571 int print_colored = 0, print_found = 0, print_trees = 0;
9572 int print_searching = 0, print_total = 0;
9573 int print_deltify = 0, print_written = 0, print_sent = 0;
9575 if (a->verbosity < 0)
9576 return NULL;
9578 if (refname) {
9579 const char *status = success ? "accepted" : "rejected";
9581 if (success) {
9582 struct got_pathlist_entry *pe;
9583 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9584 const char *branchname = pe->path;
9585 if (got_path_cmp(branchname, refname,
9586 strlen(branchname), strlen(refname)) == 0) {
9587 status = "deleted";
9588 a->sent_something = 1;
9589 break;
9594 if (a->printed_something)
9595 putchar('\n');
9596 printf("Server has %s %s", status, refname);
9597 if (errmsg)
9598 printf(": %s", errmsg);
9599 a->printed_something = 1;
9600 return NULL;
9603 if (a->last_ncolored != ncolored) {
9604 print_colored = 1;
9605 a->last_ncolored = ncolored;
9608 if (a->last_nfound != nfound) {
9609 print_colored = 1;
9610 print_found = 1;
9611 a->last_nfound = nfound;
9614 if (a->last_ntrees != ntrees) {
9615 print_colored = 1;
9616 print_found = 1;
9617 print_trees = 1;
9618 a->last_ntrees = ntrees;
9621 if ((print_colored || print_found || print_trees) &&
9622 !a->loading_done) {
9623 printf("\r");
9624 print_load_info(print_colored, print_found, print_trees,
9625 ncolored, nfound, ntrees);
9626 a->printed_something = 1;
9627 fflush(stdout);
9628 return NULL;
9629 } else if (!a->loading_done) {
9630 printf("\r");
9631 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9632 printf("\n");
9633 a->loading_done = 1;
9636 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9637 return got_error_from_errno("fmt_scaled");
9638 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9639 return got_error_from_errno("fmt_scaled");
9641 if (a->last_ncommits != ncommits) {
9642 print_searching = 1;
9643 a->last_ncommits = ncommits;
9646 if (a->last_nobj_total != nobj_total) {
9647 print_searching = 1;
9648 print_total = 1;
9649 a->last_nobj_total = nobj_total;
9652 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9653 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9654 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9655 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9656 return got_error(GOT_ERR_NO_SPACE);
9659 if (nobj_deltify > 0 || nobj_written > 0) {
9660 if (nobj_deltify > 0) {
9661 p_deltify = (nobj_deltify * 100) / nobj_total;
9662 if (p_deltify != a->last_p_deltify) {
9663 a->last_p_deltify = p_deltify;
9664 print_searching = 1;
9665 print_total = 1;
9666 print_deltify = 1;
9669 if (nobj_written > 0) {
9670 p_written = (nobj_written * 100) / nobj_total;
9671 if (p_written != a->last_p_written) {
9672 a->last_p_written = p_written;
9673 print_searching = 1;
9674 print_total = 1;
9675 print_deltify = 1;
9676 print_written = 1;
9681 if (bytes_sent > 0) {
9682 p_sent = (bytes_sent * 100) / packfile_size;
9683 if (p_sent != a->last_p_sent) {
9684 a->last_p_sent = p_sent;
9685 print_searching = 1;
9686 print_total = 1;
9687 print_deltify = 1;
9688 print_written = 1;
9689 print_sent = 1;
9691 a->sent_something = 1;
9694 if (print_searching || print_total || print_deltify || print_written ||
9695 print_sent)
9696 printf("\r");
9697 if (print_searching)
9698 printf("packing %d reference%s", ncommits,
9699 ncommits == 1 ? "" : "s");
9700 if (print_total)
9701 printf("; %d object%s", nobj_total,
9702 nobj_total == 1 ? "" : "s");
9703 if (print_deltify)
9704 printf("; deltify: %d%%", p_deltify);
9705 if (print_sent)
9706 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9707 scaled_packsize, p_sent);
9708 else if (print_written)
9709 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9710 scaled_packsize, p_written);
9711 if (print_searching || print_total || print_deltify ||
9712 print_written || print_sent) {
9713 a->printed_something = 1;
9714 fflush(stdout);
9716 return NULL;
9719 static const struct got_error *
9720 cmd_send(int argc, char *argv[])
9722 const struct got_error *error = NULL;
9723 char *cwd = NULL, *repo_path = NULL;
9724 const char *remote_name;
9725 char *proto = NULL, *host = NULL, *port = NULL;
9726 char *repo_name = NULL, *server_path = NULL;
9727 const struct got_remote_repo *remotes;
9728 struct got_remote_repo *remote = NULL;
9729 int nremotes, nbranches = 0, ndelete_branches = 0;
9730 struct got_repository *repo = NULL;
9731 struct got_worktree *worktree = NULL;
9732 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9733 struct got_pathlist_head branches;
9734 struct got_pathlist_head tags;
9735 struct got_reflist_head all_branches;
9736 struct got_reflist_head all_tags;
9737 struct got_pathlist_head delete_args;
9738 struct got_pathlist_head delete_branches;
9739 struct got_reflist_entry *re;
9740 struct got_pathlist_entry *pe;
9741 int i, ch, sendfd = -1, sendstatus;
9742 pid_t sendpid = -1;
9743 struct got_send_progress_arg spa;
9744 int verbosity = 0, overwrite_refs = 0;
9745 int send_all_branches = 0, send_all_tags = 0;
9746 struct got_reference *ref = NULL;
9747 int *pack_fds = NULL;
9749 TAILQ_INIT(&branches);
9750 TAILQ_INIT(&tags);
9751 TAILQ_INIT(&all_branches);
9752 TAILQ_INIT(&all_tags);
9753 TAILQ_INIT(&delete_args);
9754 TAILQ_INIT(&delete_branches);
9756 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9757 switch (ch) {
9758 case 'a':
9759 send_all_branches = 1;
9760 break;
9761 case 'b':
9762 error = got_pathlist_append(&branches, optarg, NULL);
9763 if (error)
9764 return error;
9765 nbranches++;
9766 break;
9767 case 'd':
9768 error = got_pathlist_append(&delete_args, optarg, NULL);
9769 if (error)
9770 return error;
9771 break;
9772 case 'f':
9773 overwrite_refs = 1;
9774 break;
9775 case 'q':
9776 verbosity = -1;
9777 break;
9778 case 'r':
9779 repo_path = realpath(optarg, NULL);
9780 if (repo_path == NULL)
9781 return got_error_from_errno2("realpath",
9782 optarg);
9783 got_path_strip_trailing_slashes(repo_path);
9784 break;
9785 case 'T':
9786 send_all_tags = 1;
9787 break;
9788 case 't':
9789 error = got_pathlist_append(&tags, optarg, NULL);
9790 if (error)
9791 return error;
9792 break;
9793 case 'v':
9794 if (verbosity < 0)
9795 verbosity = 0;
9796 else if (verbosity < 3)
9797 verbosity++;
9798 break;
9799 default:
9800 usage_send();
9801 /* NOTREACHED */
9804 argc -= optind;
9805 argv += optind;
9807 if (send_all_branches && !TAILQ_EMPTY(&branches))
9808 option_conflict('a', 'b');
9809 if (send_all_tags && !TAILQ_EMPTY(&tags))
9810 option_conflict('T', 't');
9813 if (argc == 0)
9814 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9815 else if (argc == 1)
9816 remote_name = argv[0];
9817 else
9818 usage_send();
9820 cwd = getcwd(NULL, 0);
9821 if (cwd == NULL) {
9822 error = got_error_from_errno("getcwd");
9823 goto done;
9826 error = got_repo_pack_fds_open(&pack_fds);
9827 if (error != NULL)
9828 goto done;
9830 if (repo_path == NULL) {
9831 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9832 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9833 goto done;
9834 else
9835 error = NULL;
9836 if (worktree) {
9837 repo_path =
9838 strdup(got_worktree_get_repo_path(worktree));
9839 if (repo_path == NULL)
9840 error = got_error_from_errno("strdup");
9841 if (error)
9842 goto done;
9843 } else {
9844 repo_path = strdup(cwd);
9845 if (repo_path == NULL) {
9846 error = got_error_from_errno("strdup");
9847 goto done;
9852 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9853 if (error)
9854 goto done;
9856 if (worktree) {
9857 worktree_conf = got_worktree_get_gotconfig(worktree);
9858 if (worktree_conf) {
9859 got_gotconfig_get_remotes(&nremotes, &remotes,
9860 worktree_conf);
9861 for (i = 0; i < nremotes; i++) {
9862 if (strcmp(remotes[i].name, remote_name) == 0) {
9863 error = got_repo_remote_repo_dup(&remote,
9864 &remotes[i]);
9865 if (error)
9866 goto done;
9867 break;
9872 if (remote == NULL) {
9873 repo_conf = got_repo_get_gotconfig(repo);
9874 if (repo_conf) {
9875 got_gotconfig_get_remotes(&nremotes, &remotes,
9876 repo_conf);
9877 for (i = 0; i < nremotes; i++) {
9878 if (strcmp(remotes[i].name, remote_name) == 0) {
9879 error = got_repo_remote_repo_dup(&remote,
9880 &remotes[i]);
9881 if (error)
9882 goto done;
9883 break;
9888 if (remote == NULL) {
9889 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9890 for (i = 0; i < nremotes; i++) {
9891 if (strcmp(remotes[i].name, remote_name) == 0) {
9892 error = got_repo_remote_repo_dup(&remote,
9893 &remotes[i]);
9894 if (error)
9895 goto done;
9896 break;
9900 if (remote == NULL) {
9901 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9902 goto done;
9905 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9906 &repo_name, remote->send_url);
9907 if (error)
9908 goto done;
9910 if (strcmp(proto, "git") == 0) {
9911 #ifndef PROFILE
9912 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9913 "sendfd dns inet unveil", NULL) == -1)
9914 err(1, "pledge");
9915 #endif
9916 } else if (strcmp(proto, "git+ssh") == 0 ||
9917 strcmp(proto, "ssh") == 0) {
9918 #ifndef PROFILE
9919 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9920 "sendfd unveil", NULL) == -1)
9921 err(1, "pledge");
9922 #endif
9923 } else if (strcmp(proto, "http") == 0 ||
9924 strcmp(proto, "git+http") == 0) {
9925 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9926 goto done;
9927 } else {
9928 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9929 goto done;
9932 error = got_dial_apply_unveil(proto);
9933 if (error)
9934 goto done;
9936 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9937 if (error)
9938 goto done;
9940 if (send_all_branches) {
9941 error = got_ref_list(&all_branches, repo, "refs/heads",
9942 got_ref_cmp_by_name, NULL);
9943 if (error)
9944 goto done;
9945 TAILQ_FOREACH(re, &all_branches, entry) {
9946 const char *branchname = got_ref_get_name(re->ref);
9947 error = got_pathlist_append(&branches,
9948 branchname, NULL);
9949 if (error)
9950 goto done;
9951 nbranches++;
9953 } else if (nbranches == 0) {
9954 for (i = 0; i < remote->nsend_branches; i++) {
9955 error = got_pathlist_append(&branches,
9956 remote->send_branches[i], NULL);
9957 if (error)
9958 goto done;
9962 if (send_all_tags) {
9963 error = got_ref_list(&all_tags, repo, "refs/tags",
9964 got_ref_cmp_by_name, NULL);
9965 if (error)
9966 goto done;
9967 TAILQ_FOREACH(re, &all_tags, entry) {
9968 const char *tagname = got_ref_get_name(re->ref);
9969 error = got_pathlist_append(&tags,
9970 tagname, NULL);
9971 if (error)
9972 goto done;
9977 * To prevent accidents only branches in refs/heads/ can be deleted
9978 * with 'got send -d'.
9979 * Deleting anything else requires local repository access or Git.
9981 TAILQ_FOREACH(pe, &delete_args, entry) {
9982 const char *branchname = pe->path;
9983 char *s;
9984 struct got_pathlist_entry *new;
9985 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9986 s = strdup(branchname);
9987 if (s == NULL) {
9988 error = got_error_from_errno("strdup");
9989 goto done;
9991 } else {
9992 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9993 error = got_error_from_errno("asprintf");
9994 goto done;
9997 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9998 if (error || new == NULL /* duplicate */)
9999 free(s);
10000 if (error)
10001 goto done;
10002 ndelete_branches++;
10005 if (nbranches == 0 && ndelete_branches == 0) {
10006 struct got_reference *head_ref;
10007 if (worktree)
10008 error = got_ref_open(&head_ref, repo,
10009 got_worktree_get_head_ref_name(worktree), 0);
10010 else
10011 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10012 if (error)
10013 goto done;
10014 if (got_ref_is_symbolic(head_ref)) {
10015 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10016 got_ref_close(head_ref);
10017 if (error)
10018 goto done;
10019 } else
10020 ref = head_ref;
10021 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10022 NULL);
10023 if (error)
10024 goto done;
10025 nbranches++;
10028 if (worktree) {
10029 /* Release work tree lock. */
10030 got_worktree_close(worktree);
10031 worktree = NULL;
10034 if (verbosity >= 0) {
10035 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10036 remote->name, proto, host,
10037 port ? ":" : "", port ? port : "",
10038 *server_path == '/' ? "" : "/", server_path);
10041 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10042 server_path, verbosity);
10043 if (error)
10044 goto done;
10046 memset(&spa, 0, sizeof(spa));
10047 spa.last_scaled_packsize[0] = '\0';
10048 spa.last_p_deltify = -1;
10049 spa.last_p_written = -1;
10050 spa.verbosity = verbosity;
10051 spa.delete_branches = &delete_branches;
10052 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10053 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10054 check_cancelled, NULL);
10055 if (spa.printed_something)
10056 putchar('\n');
10057 if (error)
10058 goto done;
10059 if (!spa.sent_something && verbosity >= 0)
10060 printf("Already up-to-date\n");
10061 done:
10062 if (sendpid > 0) {
10063 if (kill(sendpid, SIGTERM) == -1)
10064 error = got_error_from_errno("kill");
10065 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10066 error = got_error_from_errno("waitpid");
10068 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10069 error = got_error_from_errno("close");
10070 if (repo) {
10071 const struct got_error *close_err = got_repo_close(repo);
10072 if (error == NULL)
10073 error = close_err;
10075 if (worktree)
10076 got_worktree_close(worktree);
10077 if (pack_fds) {
10078 const struct got_error *pack_err =
10079 got_repo_pack_fds_close(pack_fds);
10080 if (error == NULL)
10081 error = pack_err;
10083 if (ref)
10084 got_ref_close(ref);
10085 got_repo_free_remote_repo_data(remote);
10086 free(remote);
10087 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10088 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10089 got_ref_list_free(&all_branches);
10090 got_ref_list_free(&all_tags);
10091 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10092 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10093 free(cwd);
10094 free(repo_path);
10095 free(proto);
10096 free(host);
10097 free(port);
10098 free(server_path);
10099 free(repo_name);
10100 return error;
10104 * Print and if delete is set delete all ref_prefix references.
10105 * If wanted_ref is not NULL, only print or delete this reference.
10107 static const struct got_error *
10108 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10109 const char *wanted_ref, int delete, struct got_worktree *worktree,
10110 struct got_repository *repo)
10112 const struct got_error *err;
10113 struct got_pathlist_head paths;
10114 struct got_reflist_head refs;
10115 struct got_reflist_entry *re;
10116 struct got_reflist_object_id_map *refs_idmap = NULL;
10117 struct got_commit_object *commit = NULL;
10118 struct got_object_id *id = NULL;
10119 const char *header_prefix;
10120 char *uuidstr = NULL;
10121 int found = 0;
10123 TAILQ_INIT(&refs);
10124 TAILQ_INIT(&paths);
10126 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10127 if (err)
10128 goto done;
10130 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10131 if (err)
10132 goto done;
10134 if (worktree != NULL) {
10135 err = got_worktree_get_uuid(&uuidstr, worktree);
10136 if (err)
10137 goto done;
10140 if (wanted_ref) {
10141 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10142 wanted_ref += 11;
10145 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10146 header_prefix = "backout";
10147 else
10148 header_prefix = "cherrypick";
10150 TAILQ_FOREACH(re, &refs, entry) {
10151 const char *refname, *wt;
10153 refname = got_ref_get_name(re->ref);
10155 err = check_cancelled(NULL);
10156 if (err)
10157 goto done;
10159 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10160 refname += prefix_len + 1; /* skip '-' delimiter */
10161 else
10162 continue;
10164 wt = refname;
10166 if (worktree == NULL || strncmp(refname, uuidstr,
10167 GOT_WORKTREE_UUID_STRLEN) == 0)
10168 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10169 else
10170 continue;
10172 err = got_repo_match_object_id(&id, NULL, refname,
10173 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10174 if (err)
10175 goto done;
10177 err = got_object_open_as_commit(&commit, repo, id);
10178 if (err)
10179 goto done;
10181 if (wanted_ref)
10182 found = strncmp(wanted_ref, refname,
10183 strlen(wanted_ref)) == 0;
10184 if (wanted_ref && !found) {
10185 struct got_reflist_head *ci_refs;
10187 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10188 id);
10190 if (ci_refs) {
10191 char *refs_str = NULL;
10192 char const *r = NULL;
10194 err = build_refs_str(&refs_str, ci_refs, id,
10195 repo, 1);
10196 if (err)
10197 goto done;
10199 r = refs_str;
10200 while (r) {
10201 if (strncmp(r, wanted_ref,
10202 strlen(wanted_ref)) == 0) {
10203 found = 1;
10204 break;
10206 r = strchr(r, ' ');
10207 if (r)
10208 ++r;
10210 free(refs_str);
10214 if (wanted_ref == NULL || found) {
10215 if (delete) {
10216 err = got_ref_delete(re->ref, repo);
10217 if (err)
10218 goto done;
10219 printf("Deleted: ");
10220 err = print_commit_oneline(commit, id, repo,
10221 refs_idmap);
10222 } else {
10224 * Print paths modified by commit to help
10225 * associate commits with worktree changes.
10227 err = get_changed_paths(&paths, commit,
10228 repo, NULL);
10229 if (err)
10230 goto done;
10232 err = print_commit(commit, id, repo, NULL,
10233 &paths, NULL, 0, 0, refs_idmap, NULL,
10234 header_prefix);
10235 got_pathlist_free(&paths,
10236 GOT_PATHLIST_FREE_ALL);
10238 if (worktree == NULL)
10239 printf("work tree: %.*s\n\n",
10240 GOT_WORKTREE_UUID_STRLEN, wt);
10242 if (err || found)
10243 goto done;
10246 got_object_commit_close(commit);
10247 commit = NULL;
10248 free(id);
10249 id = NULL;
10252 if (wanted_ref != NULL && !found)
10253 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10255 done:
10256 free(id);
10257 free(uuidstr);
10258 got_ref_list_free(&refs);
10259 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10260 if (refs_idmap)
10261 got_reflist_object_id_map_free(refs_idmap);
10262 if (commit)
10263 got_object_commit_close(commit);
10264 return err;
10268 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10269 * identified by id for log messages to prepopulate the editor on commit.
10271 static const struct got_error *
10272 logmsg_ref(struct got_object_id *id, const char *prefix,
10273 struct got_worktree *worktree, struct got_repository *repo)
10275 const struct got_error *err = NULL;
10276 char *idstr, *ref = NULL, *refname = NULL;
10277 int histedit_in_progress;
10278 int rebase_in_progress, merge_in_progress;
10281 * Silenty refuse to create merge reference if any histedit, merge,
10282 * or rebase operation is in progress.
10284 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10285 worktree);
10286 if (err)
10287 return err;
10288 if (histedit_in_progress)
10289 return NULL;
10291 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10292 if (err)
10293 return err;
10294 if (rebase_in_progress)
10295 return NULL;
10297 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10298 repo);
10299 if (err)
10300 return err;
10301 if (merge_in_progress)
10302 return NULL;
10304 err = got_object_id_str(&idstr, id);
10305 if (err)
10306 return err;
10308 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10309 if (err)
10310 goto done;
10312 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10313 err = got_error_from_errno("asprintf");
10314 goto done;
10317 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10318 -1, repo);
10319 done:
10320 free(ref);
10321 free(idstr);
10322 free(refname);
10323 return err;
10326 __dead static void
10327 usage_cherrypick(void)
10329 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10330 getprogname());
10331 exit(1);
10334 static const struct got_error *
10335 cmd_cherrypick(int argc, char *argv[])
10337 const struct got_error *error = NULL;
10338 struct got_worktree *worktree = NULL;
10339 struct got_repository *repo = NULL;
10340 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10341 struct got_object_id *commit_id = NULL;
10342 struct got_commit_object *commit = NULL;
10343 struct got_object_qid *pid;
10344 int ch, list_refs = 0, remove_refs = 0;
10345 struct got_update_progress_arg upa;
10346 int *pack_fds = NULL;
10348 #ifndef PROFILE
10349 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10350 "unveil", NULL) == -1)
10351 err(1, "pledge");
10352 #endif
10354 while ((ch = getopt(argc, argv, "lX")) != -1) {
10355 switch (ch) {
10356 case 'l':
10357 list_refs = 1;
10358 break;
10359 case 'X':
10360 remove_refs = 1;
10361 break;
10362 default:
10363 usage_cherrypick();
10364 /* NOTREACHED */
10368 argc -= optind;
10369 argv += optind;
10371 if (list_refs || remove_refs) {
10372 if (argc != 0 && argc != 1)
10373 usage_cherrypick();
10374 } else if (argc != 1)
10375 usage_cherrypick();
10376 if (list_refs && remove_refs)
10377 option_conflict('l', 'X');
10379 cwd = getcwd(NULL, 0);
10380 if (cwd == NULL) {
10381 error = got_error_from_errno("getcwd");
10382 goto done;
10385 error = got_repo_pack_fds_open(&pack_fds);
10386 if (error != NULL)
10387 goto done;
10389 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10390 if (error) {
10391 if (list_refs || remove_refs) {
10392 if (error->code != GOT_ERR_NOT_WORKTREE)
10393 goto done;
10394 } else {
10395 if (error->code == GOT_ERR_NOT_WORKTREE)
10396 error = wrap_not_worktree_error(error,
10397 "cherrypick", cwd);
10398 goto done;
10402 error = got_repo_open(&repo,
10403 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10404 NULL, pack_fds);
10405 if (error != NULL)
10406 goto done;
10408 error = apply_unveil(got_repo_get_path(repo), 0,
10409 worktree ? got_worktree_get_root_path(worktree) : NULL);
10410 if (error)
10411 goto done;
10413 if (list_refs || remove_refs) {
10414 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10415 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10416 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10417 goto done;
10420 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10421 if (error != NULL)
10422 goto done;
10424 error = got_repo_match_object_id(&commit_id, NULL,
10425 keyword_idstr != NULL ? keyword_idstr : argv[0],
10426 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10427 if (error)
10428 goto done;
10429 error = got_object_id_str(&commit_id_str, commit_id);
10430 if (error)
10431 goto done;
10433 error = got_object_open_as_commit(&commit, repo, commit_id);
10434 if (error)
10435 goto done;
10436 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10437 memset(&upa, 0, sizeof(upa));
10438 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10439 commit_id, repo, update_progress, &upa, check_cancelled,
10440 NULL);
10441 if (error != NULL)
10442 goto done;
10444 if (upa.did_something) {
10445 error = logmsg_ref(commit_id,
10446 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10447 if (error)
10448 goto done;
10449 printf("Merged commit %s\n", commit_id_str);
10451 print_merge_progress_stats(&upa);
10452 done:
10453 free(cwd);
10454 free(keyword_idstr);
10455 if (commit)
10456 got_object_commit_close(commit);
10457 free(commit_id_str);
10458 if (worktree)
10459 got_worktree_close(worktree);
10460 if (repo) {
10461 const struct got_error *close_err = got_repo_close(repo);
10462 if (error == NULL)
10463 error = close_err;
10465 if (pack_fds) {
10466 const struct got_error *pack_err =
10467 got_repo_pack_fds_close(pack_fds);
10468 if (error == NULL)
10469 error = pack_err;
10472 return error;
10475 __dead static void
10476 usage_backout(void)
10478 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10479 exit(1);
10482 static const struct got_error *
10483 cmd_backout(int argc, char *argv[])
10485 const struct got_error *error = NULL;
10486 struct got_worktree *worktree = NULL;
10487 struct got_repository *repo = NULL;
10488 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10489 struct got_object_id *commit_id = NULL;
10490 struct got_commit_object *commit = NULL;
10491 struct got_object_qid *pid;
10492 int ch, list_refs = 0, remove_refs = 0;
10493 struct got_update_progress_arg upa;
10494 int *pack_fds = NULL;
10496 #ifndef PROFILE
10497 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10498 "unveil", NULL) == -1)
10499 err(1, "pledge");
10500 #endif
10502 while ((ch = getopt(argc, argv, "lX")) != -1) {
10503 switch (ch) {
10504 case 'l':
10505 list_refs = 1;
10506 break;
10507 case 'X':
10508 remove_refs = 1;
10509 break;
10510 default:
10511 usage_backout();
10512 /* NOTREACHED */
10516 argc -= optind;
10517 argv += optind;
10519 if (list_refs || remove_refs) {
10520 if (argc != 0 && argc != 1)
10521 usage_backout();
10522 } else if (argc != 1)
10523 usage_backout();
10524 if (list_refs && remove_refs)
10525 option_conflict('l', 'X');
10527 cwd = getcwd(NULL, 0);
10528 if (cwd == NULL) {
10529 error = got_error_from_errno("getcwd");
10530 goto done;
10533 error = got_repo_pack_fds_open(&pack_fds);
10534 if (error != NULL)
10535 goto done;
10537 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10538 if (error) {
10539 if (list_refs || remove_refs) {
10540 if (error->code != GOT_ERR_NOT_WORKTREE)
10541 goto done;
10542 } else {
10543 if (error->code == GOT_ERR_NOT_WORKTREE)
10544 error = wrap_not_worktree_error(error,
10545 "backout", cwd);
10546 goto done;
10550 error = got_repo_open(&repo,
10551 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10552 NULL, pack_fds);
10553 if (error != NULL)
10554 goto done;
10556 error = apply_unveil(got_repo_get_path(repo), 0,
10557 worktree ? got_worktree_get_root_path(worktree) : NULL);
10558 if (error)
10559 goto done;
10561 if (list_refs || remove_refs) {
10562 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10563 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10564 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10565 goto done;
10568 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10569 if (error != NULL)
10570 goto done;
10572 error = got_repo_match_object_id(&commit_id, NULL,
10573 keyword_idstr != NULL ? keyword_idstr : argv[0],
10574 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10575 if (error)
10576 goto done;
10577 error = got_object_id_str(&commit_id_str, commit_id);
10578 if (error)
10579 goto done;
10581 error = got_object_open_as_commit(&commit, repo, commit_id);
10582 if (error)
10583 goto done;
10584 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10585 if (pid == NULL) {
10586 error = got_error(GOT_ERR_ROOT_COMMIT);
10587 goto done;
10590 memset(&upa, 0, sizeof(upa));
10591 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10592 repo, update_progress, &upa, check_cancelled, NULL);
10593 if (error != NULL)
10594 goto done;
10596 if (upa.did_something) {
10597 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10598 worktree, repo);
10599 if (error)
10600 goto done;
10601 printf("Backed out commit %s\n", commit_id_str);
10603 print_merge_progress_stats(&upa);
10604 done:
10605 free(cwd);
10606 free(keyword_idstr);
10607 if (commit)
10608 got_object_commit_close(commit);
10609 free(commit_id_str);
10610 if (worktree)
10611 got_worktree_close(worktree);
10612 if (repo) {
10613 const struct got_error *close_err = got_repo_close(repo);
10614 if (error == NULL)
10615 error = close_err;
10617 if (pack_fds) {
10618 const struct got_error *pack_err =
10619 got_repo_pack_fds_close(pack_fds);
10620 if (error == NULL)
10621 error = pack_err;
10623 return error;
10626 __dead static void
10627 usage_rebase(void)
10629 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10630 exit(1);
10633 static void
10634 trim_logmsg(char *logmsg, int limit)
10636 char *nl;
10637 size_t len;
10639 len = strlen(logmsg);
10640 if (len > limit)
10641 len = limit;
10642 logmsg[len] = '\0';
10643 nl = strchr(logmsg, '\n');
10644 if (nl)
10645 *nl = '\0';
10648 static const struct got_error *
10649 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10651 const struct got_error *err;
10652 char *logmsg0 = NULL;
10653 const char *s;
10655 err = got_object_commit_get_logmsg(&logmsg0, commit);
10656 if (err)
10657 return err;
10659 s = logmsg0;
10660 while (isspace((unsigned char)s[0]))
10661 s++;
10663 *logmsg = strdup(s);
10664 if (*logmsg == NULL) {
10665 err = got_error_from_errno("strdup");
10666 goto done;
10669 trim_logmsg(*logmsg, limit);
10670 done:
10671 free(logmsg0);
10672 return err;
10675 static const struct got_error *
10676 show_rebase_merge_conflict(struct got_object_id *id,
10677 struct got_repository *repo)
10679 const struct got_error *err;
10680 struct got_commit_object *commit = NULL;
10681 char *id_str = NULL, *logmsg = NULL;
10683 err = got_object_open_as_commit(&commit, repo, id);
10684 if (err)
10685 return err;
10687 err = got_object_id_str(&id_str, id);
10688 if (err)
10689 goto done;
10691 id_str[12] = '\0';
10693 err = get_short_logmsg(&logmsg, 42, commit);
10694 if (err)
10695 goto done;
10697 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10698 done:
10699 free(id_str);
10700 got_object_commit_close(commit);
10701 free(logmsg);
10702 return err;
10705 static const struct got_error *
10706 show_rebase_progress(struct got_commit_object *commit,
10707 struct got_object_id *old_id, struct got_object_id *new_id)
10709 const struct got_error *err;
10710 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10712 err = got_object_id_str(&old_id_str, old_id);
10713 if (err)
10714 goto done;
10716 if (new_id) {
10717 err = got_object_id_str(&new_id_str, new_id);
10718 if (err)
10719 goto done;
10722 old_id_str[12] = '\0';
10723 if (new_id_str)
10724 new_id_str[12] = '\0';
10726 err = get_short_logmsg(&logmsg, 42, commit);
10727 if (err)
10728 goto done;
10730 printf("%s -> %s: %s\n", old_id_str,
10731 new_id_str ? new_id_str : "no-op change", logmsg);
10732 done:
10733 free(old_id_str);
10734 free(new_id_str);
10735 free(logmsg);
10736 return err;
10739 static const struct got_error *
10740 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10741 struct got_reference *branch, struct got_reference *tmp_branch,
10742 struct got_repository *repo, int create_backup)
10744 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10745 return got_worktree_rebase_complete(worktree, fileindex,
10746 tmp_branch, branch, repo, create_backup);
10749 static const struct got_error *
10750 rebase_commit(struct got_pathlist_head *merged_paths,
10751 struct got_worktree *worktree, struct got_fileindex *fileindex,
10752 struct got_reference *tmp_branch, const char *committer,
10753 struct got_object_id *commit_id, int allow_conflict,
10754 struct got_repository *repo)
10756 const struct got_error *error;
10757 struct got_commit_object *commit;
10758 struct got_object_id *new_commit_id;
10760 error = got_object_open_as_commit(&commit, repo, commit_id);
10761 if (error)
10762 return error;
10764 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10765 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10766 allow_conflict, repo);
10767 if (error) {
10768 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10769 goto done;
10770 error = show_rebase_progress(commit, commit_id, NULL);
10771 } else {
10772 error = show_rebase_progress(commit, commit_id, new_commit_id);
10773 free(new_commit_id);
10775 done:
10776 got_object_commit_close(commit);
10777 return error;
10780 struct check_path_prefix_arg {
10781 const char *path_prefix;
10782 size_t len;
10783 int errcode;
10786 static const struct got_error *
10787 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10788 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10789 struct got_object_id *id1, struct got_object_id *id2,
10790 const char *path1, const char *path2,
10791 mode_t mode1, mode_t mode2, struct got_repository *repo)
10793 struct check_path_prefix_arg *a = arg;
10795 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10796 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10797 return got_error(a->errcode);
10799 return NULL;
10802 static const struct got_error *
10803 check_path_prefix(struct got_object_id *parent_id,
10804 struct got_object_id *commit_id, const char *path_prefix,
10805 int errcode, struct got_repository *repo)
10807 const struct got_error *err;
10808 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10809 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10810 struct check_path_prefix_arg cpp_arg;
10812 if (got_path_is_root_dir(path_prefix))
10813 return NULL;
10815 err = got_object_open_as_commit(&commit, repo, commit_id);
10816 if (err)
10817 goto done;
10819 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10820 if (err)
10821 goto done;
10823 err = got_object_open_as_tree(&tree1, repo,
10824 got_object_commit_get_tree_id(parent_commit));
10825 if (err)
10826 goto done;
10828 err = got_object_open_as_tree(&tree2, repo,
10829 got_object_commit_get_tree_id(commit));
10830 if (err)
10831 goto done;
10833 cpp_arg.path_prefix = path_prefix;
10834 while (cpp_arg.path_prefix[0] == '/')
10835 cpp_arg.path_prefix++;
10836 cpp_arg.len = strlen(cpp_arg.path_prefix);
10837 cpp_arg.errcode = errcode;
10838 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10839 check_path_prefix_in_diff, &cpp_arg, 0);
10840 done:
10841 if (tree1)
10842 got_object_tree_close(tree1);
10843 if (tree2)
10844 got_object_tree_close(tree2);
10845 if (commit)
10846 got_object_commit_close(commit);
10847 if (parent_commit)
10848 got_object_commit_close(parent_commit);
10849 return err;
10852 static const struct got_error *
10853 collect_commits(struct got_object_id_queue *commits,
10854 struct got_object_id *initial_commit_id,
10855 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10856 const char *path_prefix, int path_prefix_errcode,
10857 struct got_repository *repo)
10859 const struct got_error *err = NULL;
10860 struct got_commit_graph *graph = NULL;
10861 struct got_object_id parent_id, commit_id;
10862 struct got_object_qid *qid;
10864 err = got_commit_graph_open(&graph, "/", 1);
10865 if (err)
10866 return err;
10868 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10869 check_cancelled, NULL);
10870 if (err)
10871 goto done;
10873 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10874 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10875 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10876 check_cancelled, NULL);
10877 if (err) {
10878 if (err->code == GOT_ERR_ITER_COMPLETED) {
10879 err = got_error_msg(GOT_ERR_ANCESTRY,
10880 "ran out of commits to rebase before "
10881 "youngest common ancestor commit has "
10882 "been reached?!?");
10884 goto done;
10885 } else {
10886 err = check_path_prefix(&parent_id, &commit_id,
10887 path_prefix, path_prefix_errcode, repo);
10888 if (err)
10889 goto done;
10891 err = got_object_qid_alloc(&qid, &commit_id);
10892 if (err)
10893 goto done;
10894 STAILQ_INSERT_HEAD(commits, qid, entry);
10896 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10899 done:
10900 got_commit_graph_close(graph);
10901 return err;
10904 static const struct got_error *
10905 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10907 const struct got_error *err = NULL;
10908 time_t committer_time;
10909 struct tm tm;
10910 char datebuf[11]; /* YYYY-MM-DD + NUL */
10911 char *author0 = NULL, *author, *smallerthan;
10912 char *logmsg0 = NULL, *logmsg, *newline;
10914 committer_time = got_object_commit_get_committer_time(commit);
10915 if (gmtime_r(&committer_time, &tm) == NULL)
10916 return got_error_from_errno("gmtime_r");
10917 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10918 return got_error(GOT_ERR_NO_SPACE);
10920 author0 = strdup(got_object_commit_get_author(commit));
10921 if (author0 == NULL)
10922 return got_error_from_errno("strdup");
10923 author = author0;
10924 smallerthan = strchr(author, '<');
10925 if (smallerthan && smallerthan[1] != '\0')
10926 author = smallerthan + 1;
10927 author[strcspn(author, "@>")] = '\0';
10929 err = got_object_commit_get_logmsg(&logmsg0, commit);
10930 if (err)
10931 goto done;
10932 logmsg = logmsg0;
10933 while (*logmsg == '\n')
10934 logmsg++;
10935 newline = strchr(logmsg, '\n');
10936 if (newline)
10937 *newline = '\0';
10939 if (asprintf(brief_str, "%s %s %s",
10940 datebuf, author, logmsg) == -1)
10941 err = got_error_from_errno("asprintf");
10942 done:
10943 free(author0);
10944 free(logmsg0);
10945 return err;
10948 static const struct got_error *
10949 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10950 struct got_repository *repo)
10952 const struct got_error *err;
10953 char *id_str;
10955 err = got_object_id_str(&id_str, id);
10956 if (err)
10957 return err;
10959 err = got_ref_delete(ref, repo);
10960 if (err)
10961 goto done;
10963 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10964 done:
10965 free(id_str);
10966 return err;
10969 static const struct got_error *
10970 print_backup_ref(const char *branch_name, const char *new_id_str,
10971 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10972 struct got_reflist_object_id_map *refs_idmap,
10973 struct got_repository *repo)
10975 const struct got_error *err = NULL;
10976 struct got_reflist_head *refs;
10977 char *refs_str = NULL;
10978 struct got_object_id *new_commit_id = NULL;
10979 struct got_commit_object *new_commit = NULL;
10980 char *new_commit_brief_str = NULL;
10981 struct got_object_id *yca_id = NULL;
10982 struct got_commit_object *yca_commit = NULL;
10983 char *yca_id_str = NULL, *yca_brief_str = NULL;
10984 char *custom_refs_str;
10986 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10987 return got_error_from_errno("asprintf");
10989 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10990 0, 0, refs_idmap, custom_refs_str, NULL);
10991 if (err)
10992 goto done;
10994 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10995 if (err)
10996 goto done;
10998 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10999 if (refs) {
11000 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11001 if (err)
11002 goto done;
11005 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11006 if (err)
11007 goto done;
11009 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11010 if (err)
11011 goto done;
11013 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11014 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
11015 if (err)
11016 goto done;
11018 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11019 refs_str ? " (" : "", refs_str ? refs_str : "",
11020 refs_str ? ")" : "", new_commit_brief_str);
11021 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11022 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11023 free(refs_str);
11024 refs_str = NULL;
11026 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11027 if (err)
11028 goto done;
11030 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11031 if (err)
11032 goto done;
11034 err = got_object_id_str(&yca_id_str, yca_id);
11035 if (err)
11036 goto done;
11038 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11039 if (refs) {
11040 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11041 if (err)
11042 goto done;
11044 printf("history forked at %s%s%s%s\n %s\n",
11045 yca_id_str,
11046 refs_str ? " (" : "", refs_str ? refs_str : "",
11047 refs_str ? ")" : "", yca_brief_str);
11049 done:
11050 free(custom_refs_str);
11051 free(new_commit_id);
11052 free(refs_str);
11053 free(yca_id);
11054 free(yca_id_str);
11055 free(yca_brief_str);
11056 if (new_commit)
11057 got_object_commit_close(new_commit);
11058 if (yca_commit)
11059 got_object_commit_close(yca_commit);
11061 return err;
11064 static const struct got_error *
11065 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11066 struct got_repository *repo)
11068 const struct got_error *err;
11069 struct got_reflist_head refs;
11070 struct got_reflist_entry *re;
11071 char *uuidstr = NULL;
11072 static char msg[160];
11074 TAILQ_INIT(&refs);
11076 err = got_worktree_get_uuid(&uuidstr, worktree);
11077 if (err)
11078 goto done;
11080 err = got_ref_list(&refs, repo, "refs/got/worktree",
11081 got_ref_cmp_by_name, repo);
11082 if (err)
11083 goto done;
11085 TAILQ_FOREACH(re, &refs, entry) {
11086 const char *cmd, *refname, *type;
11088 refname = got_ref_get_name(re->ref);
11090 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11091 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11092 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11093 cmd = "cherrypick";
11094 type = "cherrypicked";
11095 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11096 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11097 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11098 cmd = "backout";
11099 type = "backed-out";
11100 } else
11101 continue;
11103 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11104 continue;
11106 snprintf(msg, sizeof(msg),
11107 "work tree has references created by %s commits which "
11108 "must be removed with 'got %s -X' before running the %s "
11109 "command", type, cmd, caller);
11110 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11111 goto done;
11114 done:
11115 free(uuidstr);
11116 got_ref_list_free(&refs);
11117 return err;
11120 static const struct got_error *
11121 process_backup_refs(const char *backup_ref_prefix,
11122 const char *wanted_branch_name,
11123 int delete, struct got_repository *repo)
11125 const struct got_error *err;
11126 struct got_reflist_head refs, backup_refs;
11127 struct got_reflist_entry *re;
11128 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11129 struct got_object_id *old_commit_id = NULL;
11130 char *branch_name = NULL;
11131 struct got_commit_object *old_commit = NULL;
11132 struct got_reflist_object_id_map *refs_idmap = NULL;
11133 int wanted_branch_found = 0;
11135 TAILQ_INIT(&refs);
11136 TAILQ_INIT(&backup_refs);
11138 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11139 if (err)
11140 return err;
11142 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11143 if (err)
11144 goto done;
11146 if (wanted_branch_name) {
11147 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11148 wanted_branch_name += 11;
11151 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11152 got_ref_cmp_by_commit_timestamp_descending, repo);
11153 if (err)
11154 goto done;
11156 TAILQ_FOREACH(re, &backup_refs, entry) {
11157 const char *refname = got_ref_get_name(re->ref);
11158 char *slash;
11160 err = check_cancelled(NULL);
11161 if (err)
11162 break;
11164 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11165 if (err)
11166 break;
11168 err = got_object_open_as_commit(&old_commit, repo,
11169 old_commit_id);
11170 if (err)
11171 break;
11173 if (strncmp(backup_ref_prefix, refname,
11174 backup_ref_prefix_len) == 0)
11175 refname += backup_ref_prefix_len;
11177 while (refname[0] == '/')
11178 refname++;
11180 branch_name = strdup(refname);
11181 if (branch_name == NULL) {
11182 err = got_error_from_errno("strdup");
11183 break;
11185 slash = strrchr(branch_name, '/');
11186 if (slash) {
11187 *slash = '\0';
11188 refname += strlen(branch_name) + 1;
11191 if (wanted_branch_name == NULL ||
11192 strcmp(wanted_branch_name, branch_name) == 0) {
11193 wanted_branch_found = 1;
11194 if (delete) {
11195 err = delete_backup_ref(re->ref,
11196 old_commit_id, repo);
11197 } else {
11198 err = print_backup_ref(branch_name, refname,
11199 old_commit_id, old_commit, refs_idmap,
11200 repo);
11202 if (err)
11203 break;
11206 free(old_commit_id);
11207 old_commit_id = NULL;
11208 free(branch_name);
11209 branch_name = NULL;
11210 got_object_commit_close(old_commit);
11211 old_commit = NULL;
11214 if (wanted_branch_name && !wanted_branch_found) {
11215 err = got_error_fmt(GOT_ERR_NOT_REF,
11216 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11218 done:
11219 if (refs_idmap)
11220 got_reflist_object_id_map_free(refs_idmap);
11221 got_ref_list_free(&refs);
11222 got_ref_list_free(&backup_refs);
11223 free(old_commit_id);
11224 free(branch_name);
11225 if (old_commit)
11226 got_object_commit_close(old_commit);
11227 return err;
11230 static const struct got_error *
11231 abort_progress(void *arg, unsigned char status, const char *path)
11234 * Unversioned files should not clutter progress output when
11235 * an operation is aborted.
11237 if (status == GOT_STATUS_UNVERSIONED)
11238 return NULL;
11240 return update_progress(arg, status, path);
11243 static const struct got_error *
11244 cmd_rebase(int argc, char *argv[])
11246 const struct got_error *error = NULL;
11247 struct got_worktree *worktree = NULL;
11248 struct got_repository *repo = NULL;
11249 struct got_fileindex *fileindex = NULL;
11250 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11251 struct got_reference *branch = NULL;
11252 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11253 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11254 struct got_object_id *resume_commit_id = NULL;
11255 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11256 struct got_object_id *head_commit_id = NULL;
11257 struct got_reference *head_ref = NULL;
11258 struct got_commit_object *commit = NULL;
11259 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11260 int histedit_in_progress = 0, merge_in_progress = 0;
11261 int create_backup = 1, list_backups = 0, delete_backups = 0;
11262 int allow_conflict = 0;
11263 struct got_object_id_queue commits;
11264 struct got_pathlist_head merged_paths;
11265 const struct got_object_id_queue *parent_ids;
11266 struct got_object_qid *qid, *pid;
11267 struct got_update_progress_arg upa;
11268 int *pack_fds = NULL;
11270 STAILQ_INIT(&commits);
11271 TAILQ_INIT(&merged_paths);
11272 memset(&upa, 0, sizeof(upa));
11274 #ifndef PROFILE
11275 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11276 "unveil", NULL) == -1)
11277 err(1, "pledge");
11278 #endif
11280 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11281 switch (ch) {
11282 case 'a':
11283 abort_rebase = 1;
11284 break;
11285 case 'C':
11286 allow_conflict = 1;
11287 break;
11288 case 'c':
11289 continue_rebase = 1;
11290 break;
11291 case 'l':
11292 list_backups = 1;
11293 break;
11294 case 'X':
11295 delete_backups = 1;
11296 break;
11297 default:
11298 usage_rebase();
11299 /* NOTREACHED */
11303 argc -= optind;
11304 argv += optind;
11306 if (list_backups) {
11307 if (abort_rebase)
11308 option_conflict('l', 'a');
11309 if (allow_conflict)
11310 option_conflict('l', 'C');
11311 if (continue_rebase)
11312 option_conflict('l', 'c');
11313 if (delete_backups)
11314 option_conflict('l', 'X');
11315 if (argc != 0 && argc != 1)
11316 usage_rebase();
11317 } else if (delete_backups) {
11318 if (abort_rebase)
11319 option_conflict('X', 'a');
11320 if (allow_conflict)
11321 option_conflict('X', 'C');
11322 if (continue_rebase)
11323 option_conflict('X', 'c');
11324 if (list_backups)
11325 option_conflict('l', 'X');
11326 if (argc != 0 && argc != 1)
11327 usage_rebase();
11328 } else if (allow_conflict) {
11329 if (abort_rebase)
11330 option_conflict('C', 'a');
11331 if (!continue_rebase)
11332 errx(1, "-C option requires -c");
11333 } else {
11334 if (abort_rebase && continue_rebase)
11335 usage_rebase();
11336 else if (abort_rebase || continue_rebase) {
11337 if (argc != 0)
11338 usage_rebase();
11339 } else if (argc != 1)
11340 usage_rebase();
11343 cwd = getcwd(NULL, 0);
11344 if (cwd == NULL) {
11345 error = got_error_from_errno("getcwd");
11346 goto done;
11349 error = got_repo_pack_fds_open(&pack_fds);
11350 if (error != NULL)
11351 goto done;
11353 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11354 if (error) {
11355 if (list_backups || delete_backups) {
11356 if (error->code != GOT_ERR_NOT_WORKTREE)
11357 goto done;
11358 } else {
11359 if (error->code == GOT_ERR_NOT_WORKTREE)
11360 error = wrap_not_worktree_error(error,
11361 "rebase", cwd);
11362 goto done;
11366 error = get_gitconfig_path(&gitconfig_path);
11367 if (error)
11368 goto done;
11369 error = got_repo_open(&repo,
11370 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11371 gitconfig_path, pack_fds);
11372 if (error != NULL)
11373 goto done;
11375 if (worktree != NULL && !list_backups && !delete_backups) {
11376 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11377 if (error)
11378 goto done;
11381 error = get_author(&committer, repo, worktree);
11382 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11383 goto done;
11385 error = apply_unveil(got_repo_get_path(repo), 0,
11386 worktree ? got_worktree_get_root_path(worktree) : NULL);
11387 if (error)
11388 goto done;
11390 if (list_backups || delete_backups) {
11391 error = process_backup_refs(
11392 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11393 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11394 goto done; /* nothing else to do */
11397 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11398 worktree);
11399 if (error)
11400 goto done;
11401 if (histedit_in_progress) {
11402 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11403 goto done;
11406 error = got_worktree_merge_in_progress(&merge_in_progress,
11407 worktree, repo);
11408 if (error)
11409 goto done;
11410 if (merge_in_progress) {
11411 error = got_error(GOT_ERR_MERGE_BUSY);
11412 goto done;
11415 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11416 if (error)
11417 goto done;
11419 if (abort_rebase) {
11420 if (!rebase_in_progress) {
11421 error = got_error(GOT_ERR_NOT_REBASING);
11422 goto done;
11424 error = got_worktree_rebase_continue(&resume_commit_id,
11425 &new_base_branch, &tmp_branch, &branch, &fileindex,
11426 worktree, repo);
11427 if (error)
11428 goto done;
11429 printf("Switching work tree to %s\n",
11430 got_ref_get_symref_target(new_base_branch));
11431 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11432 new_base_branch, abort_progress, &upa);
11433 if (error)
11434 goto done;
11435 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11436 print_merge_progress_stats(&upa);
11437 goto done; /* nothing else to do */
11440 if (continue_rebase) {
11441 if (!rebase_in_progress) {
11442 error = got_error(GOT_ERR_NOT_REBASING);
11443 goto done;
11445 error = got_worktree_rebase_continue(&resume_commit_id,
11446 &new_base_branch, &tmp_branch, &branch, &fileindex,
11447 worktree, repo);
11448 if (error)
11449 goto done;
11451 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11452 committer, resume_commit_id, allow_conflict, repo);
11453 if (error)
11454 goto done;
11456 yca_id = got_object_id_dup(resume_commit_id);
11457 if (yca_id == NULL) {
11458 error = got_error_from_errno("got_object_id_dup");
11459 goto done;
11461 } else {
11462 error = got_ref_open(&branch, repo, argv[0], 0);
11463 if (error != NULL)
11464 goto done;
11465 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11466 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11467 "will not rebase a branch which lives outside "
11468 "the \"refs/heads/\" reference namespace");
11469 goto done;
11473 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11474 if (error)
11475 goto done;
11477 if (!continue_rebase) {
11478 struct got_object_id *base_commit_id;
11480 error = got_ref_open(&head_ref, repo,
11481 got_worktree_get_head_ref_name(worktree), 0);
11482 if (error)
11483 goto done;
11484 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11485 if (error)
11486 goto done;
11487 base_commit_id = got_worktree_get_base_commit_id(worktree);
11488 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11489 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11490 goto done;
11493 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11494 base_commit_id, branch_head_commit_id, 1, repo,
11495 check_cancelled, NULL);
11496 if (error) {
11497 if (error->code == GOT_ERR_ANCESTRY) {
11498 error = got_error_msg(GOT_ERR_ANCESTRY,
11499 "specified branch shares no common "
11500 "ancestry with work tree's branch");
11502 goto done;
11505 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11506 struct got_pathlist_head paths;
11507 printf("%s is already based on %s\n",
11508 got_ref_get_name(branch),
11509 got_worktree_get_head_ref_name(worktree));
11510 error = switch_head_ref(branch, branch_head_commit_id,
11511 worktree, repo);
11512 if (error)
11513 goto done;
11514 error = got_worktree_set_base_commit_id(worktree, repo,
11515 branch_head_commit_id);
11516 if (error)
11517 goto done;
11518 TAILQ_INIT(&paths);
11519 error = got_pathlist_append(&paths, "", NULL);
11520 if (error)
11521 goto done;
11522 error = got_worktree_checkout_files(worktree,
11523 &paths, repo, update_progress, &upa,
11524 check_cancelled, NULL);
11525 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11526 if (error)
11527 goto done;
11528 if (upa.did_something) {
11529 char *id_str;
11530 error = got_object_id_str(&id_str,
11531 branch_head_commit_id);
11532 if (error)
11533 goto done;
11534 printf("Updated to %s: %s\n",
11535 got_worktree_get_head_ref_name(worktree),
11536 id_str);
11537 free(id_str);
11538 } else
11539 printf("Already up-to-date\n");
11540 print_update_progress_stats(&upa);
11541 goto done;
11545 commit_id = branch_head_commit_id;
11546 error = got_object_open_as_commit(&commit, repo, commit_id);
11547 if (error)
11548 goto done;
11550 parent_ids = got_object_commit_get_parent_ids(commit);
11551 pid = STAILQ_FIRST(parent_ids);
11552 if (pid) {
11553 error = collect_commits(&commits, commit_id, &pid->id,
11554 yca_id, got_worktree_get_path_prefix(worktree),
11555 GOT_ERR_REBASE_PATH, repo);
11556 if (error)
11557 goto done;
11560 got_object_commit_close(commit);
11561 commit = NULL;
11563 if (!continue_rebase) {
11564 error = got_worktree_rebase_prepare(&new_base_branch,
11565 &tmp_branch, &fileindex, worktree, branch, repo);
11566 if (error)
11567 goto done;
11570 if (STAILQ_EMPTY(&commits)) {
11571 if (continue_rebase) {
11572 error = rebase_complete(worktree, fileindex,
11573 branch, tmp_branch, repo, create_backup);
11574 goto done;
11575 } else {
11576 /* Fast-forward the reference of the branch. */
11577 struct got_object_id *new_head_commit_id;
11578 char *id_str;
11579 error = got_ref_resolve(&new_head_commit_id, repo,
11580 new_base_branch);
11581 if (error)
11582 goto done;
11583 error = got_object_id_str(&id_str, new_head_commit_id);
11584 if (error)
11585 goto done;
11586 printf("Forwarding %s to commit %s\n",
11587 got_ref_get_name(branch), id_str);
11588 free(id_str);
11589 error = got_ref_change_ref(branch,
11590 new_head_commit_id);
11591 if (error)
11592 goto done;
11593 /* No backup needed since objects did not change. */
11594 create_backup = 0;
11598 pid = NULL;
11599 STAILQ_FOREACH(qid, &commits, entry) {
11601 commit_id = &qid->id;
11602 parent_id = pid ? &pid->id : yca_id;
11603 pid = qid;
11605 memset(&upa, 0, sizeof(upa));
11606 error = got_worktree_rebase_merge_files(&merged_paths,
11607 worktree, fileindex, parent_id, commit_id, repo,
11608 update_progress, &upa, check_cancelled, NULL);
11609 if (error)
11610 goto done;
11612 print_merge_progress_stats(&upa);
11613 if (upa.conflicts > 0 || upa.missing > 0 ||
11614 upa.not_deleted > 0 || upa.unversioned > 0) {
11615 if (upa.conflicts > 0) {
11616 error = show_rebase_merge_conflict(&qid->id,
11617 repo);
11618 if (error)
11619 goto done;
11621 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11622 break;
11625 error = rebase_commit(&merged_paths, worktree, fileindex,
11626 tmp_branch, committer, commit_id, 0, repo);
11627 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11628 if (error)
11629 goto done;
11632 if (upa.conflicts > 0 || upa.missing > 0 ||
11633 upa.not_deleted > 0 || upa.unversioned > 0) {
11634 error = got_worktree_rebase_postpone(worktree, fileindex);
11635 if (error)
11636 goto done;
11637 if (upa.conflicts > 0 && upa.missing == 0 &&
11638 upa.not_deleted == 0 && upa.unversioned == 0) {
11639 error = got_error_msg(GOT_ERR_CONFLICTS,
11640 "conflicts must be resolved before rebasing "
11641 "can continue");
11642 } else if (upa.conflicts > 0) {
11643 error = got_error_msg(GOT_ERR_CONFLICTS,
11644 "conflicts must be resolved before rebasing "
11645 "can continue; changes destined for some "
11646 "files were not yet merged and should be "
11647 "merged manually if required before the "
11648 "rebase operation is continued");
11649 } else {
11650 error = got_error_msg(GOT_ERR_CONFLICTS,
11651 "changes destined for some files were not "
11652 "yet merged and should be merged manually "
11653 "if required before the rebase operation "
11654 "is continued");
11656 } else
11657 error = rebase_complete(worktree, fileindex, branch,
11658 tmp_branch, repo, create_backup);
11659 done:
11660 free(cwd);
11661 free(committer);
11662 free(gitconfig_path);
11663 got_object_id_queue_free(&commits);
11664 free(branch_head_commit_id);
11665 free(resume_commit_id);
11666 free(head_commit_id);
11667 free(yca_id);
11668 if (commit)
11669 got_object_commit_close(commit);
11670 if (branch)
11671 got_ref_close(branch);
11672 if (new_base_branch)
11673 got_ref_close(new_base_branch);
11674 if (tmp_branch)
11675 got_ref_close(tmp_branch);
11676 if (head_ref)
11677 got_ref_close(head_ref);
11678 if (worktree)
11679 got_worktree_close(worktree);
11680 if (repo) {
11681 const struct got_error *close_err = got_repo_close(repo);
11682 if (error == NULL)
11683 error = close_err;
11685 if (pack_fds) {
11686 const struct got_error *pack_err =
11687 got_repo_pack_fds_close(pack_fds);
11688 if (error == NULL)
11689 error = pack_err;
11691 return error;
11694 __dead static void
11695 usage_histedit(void)
11697 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11698 "[branch]\n", getprogname());
11699 exit(1);
11702 #define GOT_HISTEDIT_PICK 'p'
11703 #define GOT_HISTEDIT_EDIT 'e'
11704 #define GOT_HISTEDIT_FOLD 'f'
11705 #define GOT_HISTEDIT_DROP 'd'
11706 #define GOT_HISTEDIT_MESG 'm'
11708 static const struct got_histedit_cmd {
11709 unsigned char code;
11710 const char *name;
11711 const char *desc;
11712 } got_histedit_cmds[] = {
11713 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11714 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11715 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11716 "be used" },
11717 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11718 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11721 struct got_histedit_list_entry {
11722 TAILQ_ENTRY(got_histedit_list_entry) entry;
11723 struct got_object_id *commit_id;
11724 const struct got_histedit_cmd *cmd;
11725 char *logmsg;
11727 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11729 static const struct got_error *
11730 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11731 FILE *f, struct got_repository *repo)
11733 const struct got_error *err = NULL;
11734 char *logmsg = NULL, *id_str = NULL;
11735 struct got_commit_object *commit = NULL;
11736 int n;
11738 err = got_object_open_as_commit(&commit, repo, commit_id);
11739 if (err)
11740 goto done;
11742 err = get_short_logmsg(&logmsg, 34, commit);
11743 if (err)
11744 goto done;
11746 err = got_object_id_str(&id_str, commit_id);
11747 if (err)
11748 goto done;
11750 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11751 if (n < 0)
11752 err = got_ferror(f, GOT_ERR_IO);
11753 done:
11754 if (commit)
11755 got_object_commit_close(commit);
11756 free(id_str);
11757 free(logmsg);
11758 return err;
11761 static const struct got_error *
11762 histedit_write_commit_list(struct got_object_id_queue *commits,
11763 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11764 int edit_only, struct got_repository *repo)
11766 const struct got_error *err = NULL;
11767 struct got_object_qid *qid;
11768 const char *histedit_cmd = NULL;
11770 if (STAILQ_EMPTY(commits))
11771 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11773 STAILQ_FOREACH(qid, commits, entry) {
11774 histedit_cmd = got_histedit_cmds[0].name;
11775 if (drop_only)
11776 histedit_cmd = "drop";
11777 else if (edit_only)
11778 histedit_cmd = "edit";
11779 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11780 histedit_cmd = "fold";
11781 else if (edit_logmsg_only)
11782 histedit_cmd = "mesg";
11783 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11784 if (err)
11785 break;
11788 return err;
11791 static const struct got_error *
11792 write_cmd_list(FILE *f, const char *branch_name,
11793 struct got_object_id_queue *commits)
11795 const struct got_error *err = NULL;
11796 size_t i;
11797 int n;
11798 char *id_str;
11799 struct got_object_qid *qid;
11801 qid = STAILQ_FIRST(commits);
11802 err = got_object_id_str(&id_str, &qid->id);
11803 if (err)
11804 return err;
11806 n = fprintf(f,
11807 "# Editing the history of branch '%s' starting at\n"
11808 "# commit %s\n"
11809 "# Commits will be processed in order from top to "
11810 "bottom of this file.\n", branch_name, id_str);
11811 if (n < 0) {
11812 err = got_ferror(f, GOT_ERR_IO);
11813 goto done;
11816 n = fprintf(f, "# Available histedit commands:\n");
11817 if (n < 0) {
11818 err = got_ferror(f, GOT_ERR_IO);
11819 goto done;
11822 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11823 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11824 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11825 cmd->desc);
11826 if (n < 0) {
11827 err = got_ferror(f, GOT_ERR_IO);
11828 break;
11831 done:
11832 free(id_str);
11833 return err;
11836 static const struct got_error *
11837 histedit_syntax_error(int lineno)
11839 static char msg[42];
11840 int ret;
11842 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11843 lineno);
11844 if (ret < 0 || (size_t)ret >= sizeof(msg))
11845 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11847 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11850 static const struct got_error *
11851 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11852 char *logmsg, struct got_repository *repo)
11854 const struct got_error *err;
11855 struct got_commit_object *folded_commit = NULL;
11856 char *id_str, *folded_logmsg = NULL;
11858 err = got_object_id_str(&id_str, hle->commit_id);
11859 if (err)
11860 return err;
11862 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11863 if (err)
11864 goto done;
11866 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11867 if (err)
11868 goto done;
11869 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11870 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11871 folded_logmsg) == -1) {
11872 err = got_error_from_errno("asprintf");
11874 done:
11875 if (folded_commit)
11876 got_object_commit_close(folded_commit);
11877 free(id_str);
11878 free(folded_logmsg);
11879 return err;
11882 static struct got_histedit_list_entry *
11883 get_folded_commits(struct got_histedit_list_entry *hle)
11885 struct got_histedit_list_entry *prev, *folded = NULL;
11887 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11888 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11889 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11890 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11891 folded = prev;
11892 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11895 return folded;
11898 static const struct got_error *
11899 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11900 struct got_repository *repo)
11902 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11903 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11904 const struct got_error *err = NULL;
11905 struct got_commit_object *commit = NULL;
11906 int logmsg_len;
11907 int fd = -1;
11908 struct got_histedit_list_entry *folded = NULL;
11910 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11911 if (err)
11912 return err;
11914 folded = get_folded_commits(hle);
11915 if (folded) {
11916 while (folded != hle) {
11917 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11918 folded = TAILQ_NEXT(folded, entry);
11919 continue;
11921 err = append_folded_commit_msg(&new_msg, folded,
11922 logmsg, repo);
11923 if (err)
11924 goto done;
11925 free(logmsg);
11926 logmsg = new_msg;
11927 folded = TAILQ_NEXT(folded, entry);
11931 err = got_object_id_str(&id_str, hle->commit_id);
11932 if (err)
11933 goto done;
11934 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11935 if (err)
11936 goto done;
11937 logmsg_len = asprintf(&new_msg,
11938 "%s\n# original log message of commit %s: %s",
11939 logmsg ? logmsg : "", id_str, orig_logmsg);
11940 if (logmsg_len == -1) {
11941 err = got_error_from_errno("asprintf");
11942 goto done;
11944 free(logmsg);
11945 logmsg = new_msg;
11947 err = got_object_id_str(&id_str, hle->commit_id);
11948 if (err)
11949 goto done;
11951 err = got_opentemp_named_fd(&logmsg_path, &fd,
11952 GOT_TMPDIR_STR "/got-logmsg", "");
11953 if (err)
11954 goto done;
11956 if (write(fd, logmsg, logmsg_len) == -1) {
11957 err = got_error_from_errno2("write", logmsg_path);
11958 goto done;
11960 if (close(fd) == -1) {
11961 err = got_error_from_errno2("close", logmsg_path);
11962 goto done;
11964 fd = -1;
11966 err = get_editor(&editor);
11967 if (err)
11968 goto done;
11970 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11971 logmsg_len, 0);
11972 if (err) {
11973 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11974 goto done;
11975 err = NULL;
11976 hle->logmsg = strdup(new_msg);
11977 if (hle->logmsg == NULL)
11978 err = got_error_from_errno("strdup");
11980 done:
11981 if (fd != -1 && close(fd) == -1 && err == NULL)
11982 err = got_error_from_errno2("close", logmsg_path);
11983 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11984 err = got_error_from_errno2("unlink", logmsg_path);
11985 free(logmsg_path);
11986 free(logmsg);
11987 free(orig_logmsg);
11988 free(editor);
11989 if (commit)
11990 got_object_commit_close(commit);
11991 return err;
11994 static const struct got_error *
11995 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11996 FILE *f, struct got_repository *repo)
11998 const struct got_error *err = NULL;
11999 char *line = NULL, *p, *end;
12000 size_t i, linesize = 0;
12001 ssize_t linelen;
12002 int lineno = 0;
12003 const struct got_histedit_cmd *cmd;
12004 struct got_object_id *commit_id = NULL;
12005 struct got_histedit_list_entry *hle = NULL;
12007 for (;;) {
12008 linelen = getline(&line, &linesize, f);
12009 if (linelen == -1) {
12010 const struct got_error *getline_err;
12011 if (feof(f))
12012 break;
12013 getline_err = got_error_from_errno("getline");
12014 err = got_ferror(f, getline_err->code);
12015 break;
12017 lineno++;
12018 p = line;
12019 while (isspace((unsigned char)p[0]))
12020 p++;
12021 if (p[0] == '#' || p[0] == '\0')
12022 continue;
12023 cmd = NULL;
12024 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12025 cmd = &got_histedit_cmds[i];
12026 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12027 isspace((unsigned char)p[strlen(cmd->name)])) {
12028 p += strlen(cmd->name);
12029 break;
12031 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12032 p++;
12033 break;
12036 if (i == nitems(got_histedit_cmds)) {
12037 err = histedit_syntax_error(lineno);
12038 break;
12040 while (isspace((unsigned char)p[0]))
12041 p++;
12042 end = p;
12043 while (end[0] && !isspace((unsigned char)end[0]))
12044 end++;
12045 *end = '\0';
12046 err = got_object_resolve_id_str(&commit_id, repo, p);
12047 if (err) {
12048 /* override error code */
12049 err = histedit_syntax_error(lineno);
12050 break;
12052 hle = malloc(sizeof(*hle));
12053 if (hle == NULL) {
12054 err = got_error_from_errno("malloc");
12055 break;
12057 hle->cmd = cmd;
12058 hle->commit_id = commit_id;
12059 hle->logmsg = NULL;
12060 commit_id = NULL;
12061 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12064 free(line);
12065 free(commit_id);
12066 return err;
12069 static const struct got_error *
12070 histedit_check_script(struct got_histedit_list *histedit_cmds,
12071 struct got_object_id_queue *commits, struct got_repository *repo)
12073 const struct got_error *err = NULL;
12074 struct got_object_qid *qid;
12075 struct got_histedit_list_entry *hle;
12076 static char msg[92];
12077 char *id_str;
12079 if (TAILQ_EMPTY(histedit_cmds))
12080 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12081 "histedit script contains no commands");
12082 if (STAILQ_EMPTY(commits))
12083 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12085 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12086 struct got_histedit_list_entry *hle2;
12087 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12088 if (hle == hle2)
12089 continue;
12090 if (got_object_id_cmp(hle->commit_id,
12091 hle2->commit_id) != 0)
12092 continue;
12093 err = got_object_id_str(&id_str, hle->commit_id);
12094 if (err)
12095 return err;
12096 snprintf(msg, sizeof(msg), "commit %s is listed "
12097 "more than once in histedit script", id_str);
12098 free(id_str);
12099 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12103 STAILQ_FOREACH(qid, commits, entry) {
12104 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12105 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12106 break;
12108 if (hle == NULL) {
12109 err = got_object_id_str(&id_str, &qid->id);
12110 if (err)
12111 return err;
12112 snprintf(msg, sizeof(msg),
12113 "commit %s missing from histedit script", id_str);
12114 free(id_str);
12115 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12119 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12120 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12121 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12122 "last commit in histedit script cannot be folded");
12124 return NULL;
12127 static const struct got_error *
12128 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12129 const char *path, struct got_object_id_queue *commits,
12130 struct got_repository *repo)
12132 const struct got_error *err = NULL;
12133 struct stat st, st2;
12134 struct timespec timeout;
12135 char *editor;
12136 FILE *f = NULL;
12138 err = get_editor(&editor);
12139 if (err)
12140 return err;
12142 if (stat(path, &st) == -1) {
12143 err = got_error_from_errno2("stat", path);
12144 goto done;
12147 if (spawn_editor(editor, path) == -1) {
12148 err = got_error_from_errno("failed spawning editor");
12149 goto done;
12152 timeout.tv_sec = 0;
12153 timeout.tv_nsec = 1;
12154 nanosleep(&timeout, NULL);
12156 if (stat(path, &st2) == -1) {
12157 err = got_error_from_errno2("stat", path);
12158 goto done;
12161 if (st.st_size == st2.st_size &&
12162 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12163 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12164 "no changes made to histedit script, aborting");
12165 goto done;
12168 f = fopen(path, "re");
12169 if (f == NULL) {
12170 err = got_error_from_errno("fopen");
12171 goto done;
12173 err = histedit_parse_list(histedit_cmds, f, repo);
12174 if (err)
12175 goto done;
12177 err = histedit_check_script(histedit_cmds, commits, repo);
12178 done:
12179 if (f && fclose(f) == EOF && err == NULL)
12180 err = got_error_from_errno("fclose");
12181 free(editor);
12182 return err;
12185 static const struct got_error *
12186 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12187 struct got_object_id_queue *, const char *, const char *,
12188 struct got_repository *);
12190 static const struct got_error *
12191 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12192 struct got_object_id_queue *commits, const char *branch_name,
12193 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12194 struct got_repository *repo)
12196 const struct got_error *err;
12197 FILE *f = NULL;
12198 char *path = NULL;
12200 err = got_opentemp_named(&path, &f, "got-histedit", "");
12201 if (err)
12202 return err;
12204 err = write_cmd_list(f, branch_name, commits);
12205 if (err)
12206 goto done;
12208 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12209 fold_only, drop_only, edit_only, repo);
12210 if (err)
12211 goto done;
12213 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12214 rewind(f);
12215 err = histedit_parse_list(histedit_cmds, f, repo);
12216 } else {
12217 if (fclose(f) == EOF) {
12218 err = got_error_from_errno("fclose");
12219 goto done;
12221 f = NULL;
12222 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12223 if (err) {
12224 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12225 err->code != GOT_ERR_HISTEDIT_CMD)
12226 goto done;
12227 err = histedit_edit_list_retry(histedit_cmds, err,
12228 commits, path, branch_name, repo);
12231 done:
12232 if (f && fclose(f) == EOF && err == NULL)
12233 err = got_error_from_errno("fclose");
12234 if (path && unlink(path) != 0 && err == NULL)
12235 err = got_error_from_errno2("unlink", path);
12236 free(path);
12237 return err;
12240 static const struct got_error *
12241 histedit_save_list(struct got_histedit_list *histedit_cmds,
12242 struct got_worktree *worktree, struct got_repository *repo)
12244 const struct got_error *err = NULL;
12245 char *path = NULL;
12246 FILE *f = NULL;
12247 struct got_histedit_list_entry *hle;
12249 err = got_worktree_get_histedit_script_path(&path, worktree);
12250 if (err)
12251 return err;
12253 f = fopen(path, "we");
12254 if (f == NULL) {
12255 err = got_error_from_errno2("fopen", path);
12256 goto done;
12258 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12259 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12260 repo);
12261 if (err)
12262 break;
12264 done:
12265 if (f && fclose(f) == EOF && err == NULL)
12266 err = got_error_from_errno("fclose");
12267 free(path);
12268 return err;
12271 static void
12272 histedit_free_list(struct got_histedit_list *histedit_cmds)
12274 struct got_histedit_list_entry *hle;
12276 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12277 TAILQ_REMOVE(histedit_cmds, hle, entry);
12278 free(hle);
12282 static const struct got_error *
12283 histedit_load_list(struct got_histedit_list *histedit_cmds,
12284 const char *path, struct got_repository *repo)
12286 const struct got_error *err = NULL;
12287 FILE *f = NULL;
12289 f = fopen(path, "re");
12290 if (f == NULL) {
12291 err = got_error_from_errno2("fopen", path);
12292 goto done;
12295 err = histedit_parse_list(histedit_cmds, f, repo);
12296 done:
12297 if (f && fclose(f) == EOF && err == NULL)
12298 err = got_error_from_errno("fclose");
12299 return err;
12302 static const struct got_error *
12303 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12304 const struct got_error *edit_err, struct got_object_id_queue *commits,
12305 const char *path, const char *branch_name, struct got_repository *repo)
12307 const struct got_error *err = NULL, *prev_err = edit_err;
12308 int resp = ' ';
12310 while (resp != 'c' && resp != 'r' && resp != 'a') {
12311 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12312 "or (a)bort: ", getprogname(), prev_err->msg);
12313 resp = getchar();
12314 if (resp == '\n')
12315 resp = getchar();
12316 if (resp == 'c') {
12317 histedit_free_list(histedit_cmds);
12318 err = histedit_run_editor(histedit_cmds, path, commits,
12319 repo);
12320 if (err) {
12321 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12322 err->code != GOT_ERR_HISTEDIT_CMD)
12323 break;
12324 prev_err = err;
12325 resp = ' ';
12326 continue;
12328 break;
12329 } else if (resp == 'r') {
12330 histedit_free_list(histedit_cmds);
12331 err = histedit_edit_script(histedit_cmds,
12332 commits, branch_name, 0, 0, 0, 0, repo);
12333 if (err) {
12334 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12335 err->code != GOT_ERR_HISTEDIT_CMD)
12336 break;
12337 prev_err = err;
12338 resp = ' ';
12339 continue;
12341 break;
12342 } else if (resp == 'a') {
12343 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12344 break;
12345 } else
12346 printf("invalid response '%c'\n", resp);
12349 return err;
12352 static const struct got_error *
12353 histedit_complete(struct got_worktree *worktree,
12354 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12355 struct got_reference *branch, struct got_repository *repo)
12357 printf("Switching work tree to %s\n",
12358 got_ref_get_symref_target(branch));
12359 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12360 branch, repo);
12363 static const struct got_error *
12364 show_histedit_progress(struct got_commit_object *commit,
12365 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12367 const struct got_error *err;
12368 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12370 err = got_object_id_str(&old_id_str, hle->commit_id);
12371 if (err)
12372 goto done;
12374 if (new_id) {
12375 err = got_object_id_str(&new_id_str, new_id);
12376 if (err)
12377 goto done;
12380 old_id_str[12] = '\0';
12381 if (new_id_str)
12382 new_id_str[12] = '\0';
12384 if (hle->logmsg) {
12385 logmsg = strdup(hle->logmsg);
12386 if (logmsg == NULL) {
12387 err = got_error_from_errno("strdup");
12388 goto done;
12390 trim_logmsg(logmsg, 42);
12391 } else {
12392 err = get_short_logmsg(&logmsg, 42, commit);
12393 if (err)
12394 goto done;
12397 switch (hle->cmd->code) {
12398 case GOT_HISTEDIT_PICK:
12399 case GOT_HISTEDIT_EDIT:
12400 case GOT_HISTEDIT_MESG:
12401 printf("%s -> %s: %s\n", old_id_str,
12402 new_id_str ? new_id_str : "no-op change", logmsg);
12403 break;
12404 case GOT_HISTEDIT_DROP:
12405 case GOT_HISTEDIT_FOLD:
12406 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12407 logmsg);
12408 break;
12409 default:
12410 break;
12412 done:
12413 free(old_id_str);
12414 free(new_id_str);
12415 return err;
12418 static const struct got_error *
12419 histedit_commit(struct got_pathlist_head *merged_paths,
12420 struct got_worktree *worktree, struct got_fileindex *fileindex,
12421 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12422 const char *committer, int allow_conflict, struct got_repository *repo)
12424 const struct got_error *err;
12425 struct got_commit_object *commit;
12426 struct got_object_id *new_commit_id;
12428 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12429 && hle->logmsg == NULL) {
12430 err = histedit_edit_logmsg(hle, repo);
12431 if (err)
12432 return err;
12435 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12436 if (err)
12437 return err;
12439 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12440 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12441 hle->logmsg, allow_conflict, repo);
12442 if (err) {
12443 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12444 goto done;
12445 err = show_histedit_progress(commit, hle, NULL);
12446 } else {
12447 err = show_histedit_progress(commit, hle, new_commit_id);
12448 free(new_commit_id);
12450 done:
12451 got_object_commit_close(commit);
12452 return err;
12455 static const struct got_error *
12456 histedit_skip_commit(struct got_histedit_list_entry *hle,
12457 struct got_worktree *worktree, struct got_repository *repo)
12459 const struct got_error *error;
12460 struct got_commit_object *commit;
12462 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12463 repo);
12464 if (error)
12465 return error;
12467 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12468 if (error)
12469 return error;
12471 error = show_histedit_progress(commit, hle, NULL);
12472 got_object_commit_close(commit);
12473 return error;
12476 static const struct got_error *
12477 check_local_changes(void *arg, unsigned char status,
12478 unsigned char staged_status, const char *path,
12479 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12480 struct got_object_id *commit_id, int dirfd, const char *de_name)
12482 int *have_local_changes = arg;
12484 switch (status) {
12485 case GOT_STATUS_ADD:
12486 case GOT_STATUS_DELETE:
12487 case GOT_STATUS_MODIFY:
12488 case GOT_STATUS_CONFLICT:
12489 *have_local_changes = 1;
12490 return got_error(GOT_ERR_CANCELLED);
12491 default:
12492 break;
12495 switch (staged_status) {
12496 case GOT_STATUS_ADD:
12497 case GOT_STATUS_DELETE:
12498 case GOT_STATUS_MODIFY:
12499 *have_local_changes = 1;
12500 return got_error(GOT_ERR_CANCELLED);
12501 default:
12502 break;
12505 return NULL;
12508 static const struct got_error *
12509 cmd_histedit(int argc, char *argv[])
12511 const struct got_error *error = NULL;
12512 struct got_worktree *worktree = NULL;
12513 struct got_fileindex *fileindex = NULL;
12514 struct got_repository *repo = NULL;
12515 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12516 struct got_reference *branch = NULL;
12517 struct got_reference *tmp_branch = NULL;
12518 struct got_object_id *resume_commit_id = NULL;
12519 struct got_object_id *base_commit_id = NULL;
12520 struct got_object_id *head_commit_id = NULL;
12521 struct got_commit_object *commit = NULL;
12522 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12523 struct got_update_progress_arg upa;
12524 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12525 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12526 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12527 const char *edit_script_path = NULL;
12528 struct got_object_id_queue commits;
12529 struct got_pathlist_head merged_paths;
12530 const struct got_object_id_queue *parent_ids;
12531 struct got_object_qid *pid;
12532 struct got_histedit_list histedit_cmds;
12533 struct got_histedit_list_entry *hle;
12534 int *pack_fds = NULL;
12536 STAILQ_INIT(&commits);
12537 TAILQ_INIT(&histedit_cmds);
12538 TAILQ_INIT(&merged_paths);
12539 memset(&upa, 0, sizeof(upa));
12541 #ifndef PROFILE
12542 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12543 "unveil", NULL) == -1)
12544 err(1, "pledge");
12545 #endif
12547 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12548 switch (ch) {
12549 case 'a':
12550 abort_edit = 1;
12551 break;
12552 case 'C':
12553 allow_conflict = 1;
12554 break;
12555 case 'c':
12556 continue_edit = 1;
12557 break;
12558 case 'd':
12559 drop_only = 1;
12560 break;
12561 case 'e':
12562 edit_only = 1;
12563 break;
12564 case 'F':
12565 edit_script_path = optarg;
12566 break;
12567 case 'f':
12568 fold_only = 1;
12569 break;
12570 case 'l':
12571 list_backups = 1;
12572 break;
12573 case 'm':
12574 edit_logmsg_only = 1;
12575 break;
12576 case 'X':
12577 delete_backups = 1;
12578 break;
12579 default:
12580 usage_histedit();
12581 /* NOTREACHED */
12585 argc -= optind;
12586 argv += optind;
12588 if (abort_edit && allow_conflict)
12589 option_conflict('a', 'C');
12590 if (abort_edit && continue_edit)
12591 option_conflict('a', 'c');
12592 if (edit_script_path && allow_conflict)
12593 option_conflict('F', 'C');
12594 if (edit_script_path && edit_logmsg_only)
12595 option_conflict('F', 'm');
12596 if (abort_edit && edit_logmsg_only)
12597 option_conflict('a', 'm');
12598 if (edit_logmsg_only && allow_conflict)
12599 option_conflict('m', 'C');
12600 if (continue_edit && edit_logmsg_only)
12601 option_conflict('c', 'm');
12602 if (abort_edit && fold_only)
12603 option_conflict('a', 'f');
12604 if (fold_only && allow_conflict)
12605 option_conflict('f', 'C');
12606 if (continue_edit && fold_only)
12607 option_conflict('c', 'f');
12608 if (fold_only && edit_logmsg_only)
12609 option_conflict('f', 'm');
12610 if (edit_script_path && fold_only)
12611 option_conflict('F', 'f');
12612 if (abort_edit && edit_only)
12613 option_conflict('a', 'e');
12614 if (continue_edit && edit_only)
12615 option_conflict('c', 'e');
12616 if (edit_only && edit_logmsg_only)
12617 option_conflict('e', 'm');
12618 if (edit_script_path && edit_only)
12619 option_conflict('F', 'e');
12620 if (fold_only && edit_only)
12621 option_conflict('f', 'e');
12622 if (drop_only && abort_edit)
12623 option_conflict('d', 'a');
12624 if (drop_only && allow_conflict)
12625 option_conflict('d', 'C');
12626 if (drop_only && continue_edit)
12627 option_conflict('d', 'c');
12628 if (drop_only && edit_logmsg_only)
12629 option_conflict('d', 'm');
12630 if (drop_only && edit_only)
12631 option_conflict('d', 'e');
12632 if (drop_only && edit_script_path)
12633 option_conflict('d', 'F');
12634 if (drop_only && fold_only)
12635 option_conflict('d', 'f');
12636 if (list_backups) {
12637 if (abort_edit)
12638 option_conflict('l', 'a');
12639 if (allow_conflict)
12640 option_conflict('l', 'C');
12641 if (continue_edit)
12642 option_conflict('l', 'c');
12643 if (edit_script_path)
12644 option_conflict('l', 'F');
12645 if (edit_logmsg_only)
12646 option_conflict('l', 'm');
12647 if (drop_only)
12648 option_conflict('l', 'd');
12649 if (fold_only)
12650 option_conflict('l', 'f');
12651 if (edit_only)
12652 option_conflict('l', 'e');
12653 if (delete_backups)
12654 option_conflict('l', 'X');
12655 if (argc != 0 && argc != 1)
12656 usage_histedit();
12657 } else if (delete_backups) {
12658 if (abort_edit)
12659 option_conflict('X', 'a');
12660 if (allow_conflict)
12661 option_conflict('X', 'C');
12662 if (continue_edit)
12663 option_conflict('X', 'c');
12664 if (drop_only)
12665 option_conflict('X', 'd');
12666 if (edit_script_path)
12667 option_conflict('X', 'F');
12668 if (edit_logmsg_only)
12669 option_conflict('X', 'm');
12670 if (fold_only)
12671 option_conflict('X', 'f');
12672 if (edit_only)
12673 option_conflict('X', 'e');
12674 if (list_backups)
12675 option_conflict('X', 'l');
12676 if (argc != 0 && argc != 1)
12677 usage_histedit();
12678 } else if (allow_conflict && !continue_edit)
12679 errx(1, "-C option requires -c");
12680 else if (argc != 0)
12681 usage_histedit();
12684 * This command cannot apply unveil(2) in all cases because the
12685 * user may choose to run an editor to edit the histedit script
12686 * and to edit individual commit log messages.
12687 * unveil(2) traverses exec(2); if an editor is used we have to
12688 * apply unveil after edit script and log messages have been written.
12689 * XXX TODO: Make use of unveil(2) where possible.
12692 cwd = getcwd(NULL, 0);
12693 if (cwd == NULL) {
12694 error = got_error_from_errno("getcwd");
12695 goto done;
12698 error = got_repo_pack_fds_open(&pack_fds);
12699 if (error != NULL)
12700 goto done;
12702 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12703 if (error) {
12704 if (list_backups || delete_backups) {
12705 if (error->code != GOT_ERR_NOT_WORKTREE)
12706 goto done;
12707 } else {
12708 if (error->code == GOT_ERR_NOT_WORKTREE)
12709 error = wrap_not_worktree_error(error,
12710 "histedit", cwd);
12711 goto done;
12715 if (list_backups || delete_backups) {
12716 error = got_repo_open(&repo,
12717 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12718 NULL, pack_fds);
12719 if (error != NULL)
12720 goto done;
12721 error = apply_unveil(got_repo_get_path(repo), 0,
12722 worktree ? got_worktree_get_root_path(worktree) : NULL);
12723 if (error)
12724 goto done;
12725 error = process_backup_refs(
12726 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12727 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12728 goto done; /* nothing else to do */
12731 error = get_gitconfig_path(&gitconfig_path);
12732 if (error)
12733 goto done;
12734 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12735 gitconfig_path, pack_fds);
12736 if (error != NULL)
12737 goto done;
12739 if (worktree != NULL && !list_backups && !delete_backups) {
12740 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12741 if (error)
12742 goto done;
12745 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12746 if (error)
12747 goto done;
12748 if (rebase_in_progress) {
12749 error = got_error(GOT_ERR_REBASING);
12750 goto done;
12753 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12754 repo);
12755 if (error)
12756 goto done;
12757 if (merge_in_progress) {
12758 error = got_error(GOT_ERR_MERGE_BUSY);
12759 goto done;
12762 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12763 if (error)
12764 goto done;
12766 if (edit_in_progress && edit_logmsg_only) {
12767 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12768 "histedit operation is in progress in this "
12769 "work tree and must be continued or aborted "
12770 "before the -m option can be used");
12771 goto done;
12773 if (edit_in_progress && drop_only) {
12774 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12775 "histedit operation is in progress in this "
12776 "work tree and must be continued or aborted "
12777 "before the -d option can be used");
12778 goto done;
12780 if (edit_in_progress && fold_only) {
12781 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12782 "histedit operation is in progress in this "
12783 "work tree and must be continued or aborted "
12784 "before the -f option can be used");
12785 goto done;
12787 if (edit_in_progress && edit_only) {
12788 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12789 "histedit operation is in progress in this "
12790 "work tree and must be continued or aborted "
12791 "before the -e option can be used");
12792 goto done;
12795 if (edit_in_progress && abort_edit) {
12796 error = got_worktree_histedit_continue(&resume_commit_id,
12797 &tmp_branch, &branch, &base_commit_id, &fileindex,
12798 worktree, repo);
12799 if (error)
12800 goto done;
12801 printf("Switching work tree to %s\n",
12802 got_ref_get_symref_target(branch));
12803 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12804 branch, base_commit_id, abort_progress, &upa);
12805 if (error)
12806 goto done;
12807 printf("Histedit of %s aborted\n",
12808 got_ref_get_symref_target(branch));
12809 print_merge_progress_stats(&upa);
12810 goto done; /* nothing else to do */
12811 } else if (abort_edit) {
12812 error = got_error(GOT_ERR_NOT_HISTEDIT);
12813 goto done;
12816 error = get_author(&committer, repo, worktree);
12817 if (error)
12818 goto done;
12820 if (continue_edit) {
12821 char *path;
12823 if (!edit_in_progress) {
12824 error = got_error(GOT_ERR_NOT_HISTEDIT);
12825 goto done;
12828 error = got_worktree_get_histedit_script_path(&path, worktree);
12829 if (error)
12830 goto done;
12832 error = histedit_load_list(&histedit_cmds, path, repo);
12833 free(path);
12834 if (error)
12835 goto done;
12837 error = got_worktree_histedit_continue(&resume_commit_id,
12838 &tmp_branch, &branch, &base_commit_id, &fileindex,
12839 worktree, repo);
12840 if (error)
12841 goto done;
12843 error = got_ref_resolve(&head_commit_id, repo, branch);
12844 if (error)
12845 goto done;
12847 error = got_object_open_as_commit(&commit, repo,
12848 head_commit_id);
12849 if (error)
12850 goto done;
12851 parent_ids = got_object_commit_get_parent_ids(commit);
12852 pid = STAILQ_FIRST(parent_ids);
12853 if (pid == NULL) {
12854 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12855 goto done;
12857 error = collect_commits(&commits, head_commit_id, &pid->id,
12858 base_commit_id, got_worktree_get_path_prefix(worktree),
12859 GOT_ERR_HISTEDIT_PATH, repo);
12860 got_object_commit_close(commit);
12861 commit = NULL;
12862 if (error)
12863 goto done;
12864 } else {
12865 if (edit_in_progress) {
12866 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12867 goto done;
12870 error = got_ref_open(&branch, repo,
12871 got_worktree_get_head_ref_name(worktree), 0);
12872 if (error != NULL)
12873 goto done;
12875 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12876 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12877 "will not edit commit history of a branch outside "
12878 "the \"refs/heads/\" reference namespace");
12879 goto done;
12882 error = got_ref_resolve(&head_commit_id, repo, branch);
12883 got_ref_close(branch);
12884 branch = NULL;
12885 if (error)
12886 goto done;
12888 error = got_object_open_as_commit(&commit, repo,
12889 head_commit_id);
12890 if (error)
12891 goto done;
12892 parent_ids = got_object_commit_get_parent_ids(commit);
12893 pid = STAILQ_FIRST(parent_ids);
12894 if (pid == NULL) {
12895 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12896 goto done;
12898 error = collect_commits(&commits, head_commit_id, &pid->id,
12899 got_worktree_get_base_commit_id(worktree),
12900 got_worktree_get_path_prefix(worktree),
12901 GOT_ERR_HISTEDIT_PATH, repo);
12902 got_object_commit_close(commit);
12903 commit = NULL;
12904 if (error)
12905 goto done;
12907 if (STAILQ_EMPTY(&commits)) {
12908 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12909 goto done;
12912 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12913 &base_commit_id, &fileindex, worktree, repo);
12914 if (error)
12915 goto done;
12917 if (edit_script_path) {
12918 error = histedit_load_list(&histedit_cmds,
12919 edit_script_path, repo);
12920 if (error) {
12921 got_worktree_histedit_abort(worktree, fileindex,
12922 repo, branch, base_commit_id,
12923 abort_progress, &upa);
12924 print_merge_progress_stats(&upa);
12925 goto done;
12927 } else {
12928 const char *branch_name;
12929 branch_name = got_ref_get_symref_target(branch);
12930 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12931 branch_name += 11;
12932 error = histedit_edit_script(&histedit_cmds, &commits,
12933 branch_name, edit_logmsg_only, fold_only,
12934 drop_only, edit_only, repo);
12935 if (error) {
12936 got_worktree_histedit_abort(worktree, fileindex,
12937 repo, branch, base_commit_id,
12938 abort_progress, &upa);
12939 print_merge_progress_stats(&upa);
12940 goto done;
12945 error = histedit_save_list(&histedit_cmds, worktree,
12946 repo);
12947 if (error) {
12948 got_worktree_histedit_abort(worktree, fileindex,
12949 repo, branch, base_commit_id,
12950 abort_progress, &upa);
12951 print_merge_progress_stats(&upa);
12952 goto done;
12957 error = histedit_check_script(&histedit_cmds, &commits, repo);
12958 if (error)
12959 goto done;
12961 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12962 if (resume_commit_id) {
12963 if (got_object_id_cmp(hle->commit_id,
12964 resume_commit_id) != 0)
12965 continue;
12967 resume_commit_id = NULL;
12968 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12969 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12970 error = histedit_skip_commit(hle, worktree,
12971 repo);
12972 if (error)
12973 goto done;
12974 } else {
12975 struct got_pathlist_head paths;
12976 int have_changes = 0;
12978 TAILQ_INIT(&paths);
12979 error = got_pathlist_append(&paths, "", NULL);
12980 if (error)
12981 goto done;
12982 error = got_worktree_status(worktree, &paths,
12983 repo, 0, check_local_changes, &have_changes,
12984 check_cancelled, NULL);
12985 got_pathlist_free(&paths,
12986 GOT_PATHLIST_FREE_NONE);
12987 if (error) {
12988 if (error->code != GOT_ERR_CANCELLED)
12989 goto done;
12990 if (sigint_received || sigpipe_received)
12991 goto done;
12993 if (have_changes) {
12994 error = histedit_commit(NULL, worktree,
12995 fileindex, tmp_branch, hle,
12996 committer, allow_conflict, repo);
12997 if (error)
12998 goto done;
12999 } else {
13000 error = got_object_open_as_commit(
13001 &commit, repo, hle->commit_id);
13002 if (error)
13003 goto done;
13004 error = show_histedit_progress(commit,
13005 hle, NULL);
13006 got_object_commit_close(commit);
13007 commit = NULL;
13008 if (error)
13009 goto done;
13012 continue;
13015 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13016 error = histedit_skip_commit(hle, worktree, repo);
13017 if (error)
13018 goto done;
13019 continue;
13021 error = got_object_open_as_commit(&commit, repo,
13022 hle->commit_id);
13023 if (error)
13024 goto done;
13025 parent_ids = got_object_commit_get_parent_ids(commit);
13026 pid = STAILQ_FIRST(parent_ids);
13028 error = got_worktree_histedit_merge_files(&merged_paths,
13029 worktree, fileindex, &pid->id, hle->commit_id, repo,
13030 update_progress, &upa, check_cancelled, NULL);
13031 if (error)
13032 goto done;
13033 got_object_commit_close(commit);
13034 commit = NULL;
13036 print_merge_progress_stats(&upa);
13037 if (upa.conflicts > 0 || upa.missing > 0 ||
13038 upa.not_deleted > 0 || upa.unversioned > 0) {
13039 if (upa.conflicts > 0) {
13040 error = show_rebase_merge_conflict(
13041 hle->commit_id, repo);
13042 if (error)
13043 goto done;
13045 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13046 break;
13049 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13050 char *id_str;
13051 error = got_object_id_str(&id_str, hle->commit_id);
13052 if (error)
13053 goto done;
13054 printf("Stopping histedit for amending commit %s\n",
13055 id_str);
13056 free(id_str);
13057 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13058 error = got_worktree_histedit_postpone(worktree,
13059 fileindex);
13060 goto done;
13061 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13062 error = histedit_skip_commit(hle, worktree, repo);
13063 if (error)
13064 goto done;
13065 continue;
13066 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13067 error = histedit_edit_logmsg(hle, repo);
13068 if (error)
13069 goto done;
13072 error = histedit_commit(&merged_paths, worktree, fileindex,
13073 tmp_branch, hle, committer, allow_conflict, repo);
13074 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13075 if (error)
13076 goto done;
13079 if (upa.conflicts > 0 || upa.missing > 0 ||
13080 upa.not_deleted > 0 || upa.unversioned > 0) {
13081 error = got_worktree_histedit_postpone(worktree, fileindex);
13082 if (error)
13083 goto done;
13084 if (upa.conflicts > 0 && upa.missing == 0 &&
13085 upa.not_deleted == 0 && upa.unversioned == 0) {
13086 error = got_error_msg(GOT_ERR_CONFLICTS,
13087 "conflicts must be resolved before histedit "
13088 "can continue");
13089 } else if (upa.conflicts > 0) {
13090 error = got_error_msg(GOT_ERR_CONFLICTS,
13091 "conflicts must be resolved before histedit "
13092 "can continue; changes destined for some "
13093 "files were not yet merged and should be "
13094 "merged manually if required before the "
13095 "histedit operation is continued");
13096 } else {
13097 error = got_error_msg(GOT_ERR_CONFLICTS,
13098 "changes destined for some files were not "
13099 "yet merged and should be merged manually "
13100 "if required before the histedit operation "
13101 "is continued");
13103 } else
13104 error = histedit_complete(worktree, fileindex, tmp_branch,
13105 branch, repo);
13106 done:
13107 free(cwd);
13108 free(committer);
13109 free(gitconfig_path);
13110 got_object_id_queue_free(&commits);
13111 histedit_free_list(&histedit_cmds);
13112 free(head_commit_id);
13113 free(base_commit_id);
13114 free(resume_commit_id);
13115 if (commit)
13116 got_object_commit_close(commit);
13117 if (branch)
13118 got_ref_close(branch);
13119 if (tmp_branch)
13120 got_ref_close(tmp_branch);
13121 if (worktree)
13122 got_worktree_close(worktree);
13123 if (repo) {
13124 const struct got_error *close_err = got_repo_close(repo);
13125 if (error == NULL)
13126 error = close_err;
13128 if (pack_fds) {
13129 const struct got_error *pack_err =
13130 got_repo_pack_fds_close(pack_fds);
13131 if (error == NULL)
13132 error = pack_err;
13134 return error;
13137 __dead static void
13138 usage_integrate(void)
13140 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13141 exit(1);
13144 static const struct got_error *
13145 cmd_integrate(int argc, char *argv[])
13147 const struct got_error *error = NULL;
13148 struct got_repository *repo = NULL;
13149 struct got_worktree *worktree = NULL;
13150 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13151 const char *branch_arg = NULL;
13152 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13153 struct got_fileindex *fileindex = NULL;
13154 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13155 int ch;
13156 struct got_update_progress_arg upa;
13157 int *pack_fds = NULL;
13159 #ifndef PROFILE
13160 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13161 "unveil", NULL) == -1)
13162 err(1, "pledge");
13163 #endif
13165 while ((ch = getopt(argc, argv, "")) != -1) {
13166 switch (ch) {
13167 default:
13168 usage_integrate();
13169 /* NOTREACHED */
13173 argc -= optind;
13174 argv += optind;
13176 if (argc != 1)
13177 usage_integrate();
13178 branch_arg = argv[0];
13180 cwd = getcwd(NULL, 0);
13181 if (cwd == NULL) {
13182 error = got_error_from_errno("getcwd");
13183 goto done;
13186 error = got_repo_pack_fds_open(&pack_fds);
13187 if (error != NULL)
13188 goto done;
13190 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13191 if (error) {
13192 if (error->code == GOT_ERR_NOT_WORKTREE)
13193 error = wrap_not_worktree_error(error, "integrate",
13194 cwd);
13195 goto done;
13198 error = check_rebase_or_histedit_in_progress(worktree);
13199 if (error)
13200 goto done;
13202 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13203 NULL, pack_fds);
13204 if (error != NULL)
13205 goto done;
13207 error = apply_unveil(got_repo_get_path(repo), 0,
13208 got_worktree_get_root_path(worktree));
13209 if (error)
13210 goto done;
13212 error = check_merge_in_progress(worktree, repo);
13213 if (error)
13214 goto done;
13216 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13217 error = got_error_from_errno("asprintf");
13218 goto done;
13221 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13222 &base_branch_ref, worktree, refname, repo);
13223 if (error)
13224 goto done;
13226 refname = strdup(got_ref_get_name(branch_ref));
13227 if (refname == NULL) {
13228 error = got_error_from_errno("strdup");
13229 got_worktree_integrate_abort(worktree, fileindex, repo,
13230 branch_ref, base_branch_ref);
13231 goto done;
13233 base_refname = strdup(got_ref_get_name(base_branch_ref));
13234 if (base_refname == NULL) {
13235 error = got_error_from_errno("strdup");
13236 got_worktree_integrate_abort(worktree, fileindex, repo,
13237 branch_ref, base_branch_ref);
13238 goto done;
13240 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13241 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13242 got_worktree_integrate_abort(worktree, fileindex, repo,
13243 branch_ref, base_branch_ref);
13244 goto done;
13247 error = got_ref_resolve(&commit_id, repo, branch_ref);
13248 if (error)
13249 goto done;
13251 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13252 if (error)
13253 goto done;
13255 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13256 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13257 "specified branch has already been integrated");
13258 got_worktree_integrate_abort(worktree, fileindex, repo,
13259 branch_ref, base_branch_ref);
13260 goto done;
13263 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13264 if (error) {
13265 if (error->code == GOT_ERR_ANCESTRY)
13266 error = got_error(GOT_ERR_REBASE_REQUIRED);
13267 got_worktree_integrate_abort(worktree, fileindex, repo,
13268 branch_ref, base_branch_ref);
13269 goto done;
13272 memset(&upa, 0, sizeof(upa));
13273 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13274 branch_ref, base_branch_ref, update_progress, &upa,
13275 check_cancelled, NULL);
13276 if (error)
13277 goto done;
13279 printf("Integrated %s into %s\n", refname, base_refname);
13280 print_update_progress_stats(&upa);
13281 done:
13282 if (repo) {
13283 const struct got_error *close_err = got_repo_close(repo);
13284 if (error == NULL)
13285 error = close_err;
13287 if (worktree)
13288 got_worktree_close(worktree);
13289 if (pack_fds) {
13290 const struct got_error *pack_err =
13291 got_repo_pack_fds_close(pack_fds);
13292 if (error == NULL)
13293 error = pack_err;
13295 free(cwd);
13296 free(base_commit_id);
13297 free(commit_id);
13298 free(refname);
13299 free(base_refname);
13300 return error;
13303 __dead static void
13304 usage_merge(void)
13306 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13307 exit(1);
13310 static const struct got_error *
13311 cmd_merge(int argc, char *argv[])
13313 const struct got_error *error = NULL;
13314 struct got_worktree *worktree = NULL;
13315 struct got_repository *repo = NULL;
13316 struct got_fileindex *fileindex = NULL;
13317 char *cwd = NULL, *id_str = NULL, *author = NULL;
13318 char *gitconfig_path = NULL;
13319 struct got_reference *branch = NULL, *wt_branch = NULL;
13320 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13321 struct got_object_id *wt_branch_tip = NULL;
13322 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13323 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13324 struct got_update_progress_arg upa;
13325 struct got_object_id *merge_commit_id = NULL;
13326 char *branch_name = NULL;
13327 int *pack_fds = NULL;
13329 memset(&upa, 0, sizeof(upa));
13331 #ifndef PROFILE
13332 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13333 "unveil", NULL) == -1)
13334 err(1, "pledge");
13335 #endif
13337 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13338 switch (ch) {
13339 case 'a':
13340 abort_merge = 1;
13341 break;
13342 case 'C':
13343 allow_conflict = 1;
13344 break;
13345 case 'c':
13346 continue_merge = 1;
13347 break;
13348 case 'M':
13349 prefer_fast_forward = 0;
13350 break;
13351 case 'n':
13352 interrupt_merge = 1;
13353 break;
13354 default:
13355 usage_merge();
13356 /* NOTREACHED */
13360 argc -= optind;
13361 argv += optind;
13363 if (abort_merge) {
13364 if (continue_merge)
13365 option_conflict('a', 'c');
13366 if (!prefer_fast_forward)
13367 option_conflict('a', 'M');
13368 if (interrupt_merge)
13369 option_conflict('a', 'n');
13370 } else if (continue_merge) {
13371 if (!prefer_fast_forward)
13372 option_conflict('c', 'M');
13373 if (interrupt_merge)
13374 option_conflict('c', 'n');
13376 if (allow_conflict) {
13377 if (!continue_merge)
13378 errx(1, "-C option requires -c");
13380 if (abort_merge || continue_merge) {
13381 if (argc != 0)
13382 usage_merge();
13383 } else if (argc != 1)
13384 usage_merge();
13386 cwd = getcwd(NULL, 0);
13387 if (cwd == NULL) {
13388 error = got_error_from_errno("getcwd");
13389 goto done;
13392 error = got_repo_pack_fds_open(&pack_fds);
13393 if (error != NULL)
13394 goto done;
13396 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13397 if (error) {
13398 if (error->code == GOT_ERR_NOT_WORKTREE)
13399 error = wrap_not_worktree_error(error,
13400 "merge", cwd);
13401 goto done;
13404 error = get_gitconfig_path(&gitconfig_path);
13405 if (error)
13406 goto done;
13407 error = got_repo_open(&repo,
13408 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13409 gitconfig_path, pack_fds);
13410 if (error != NULL)
13411 goto done;
13413 if (worktree != NULL) {
13414 error = worktree_has_logmsg_ref("merge", worktree, repo);
13415 if (error)
13416 goto done;
13419 error = apply_unveil(got_repo_get_path(repo), 0,
13420 worktree ? got_worktree_get_root_path(worktree) : NULL);
13421 if (error)
13422 goto done;
13424 error = check_rebase_or_histedit_in_progress(worktree);
13425 if (error)
13426 goto done;
13428 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13429 repo);
13430 if (error)
13431 goto done;
13433 if (merge_in_progress && !(abort_merge || continue_merge)) {
13434 error = got_error(GOT_ERR_MERGE_BUSY);
13435 goto done;
13438 if (!merge_in_progress && (abort_merge || continue_merge)) {
13439 error = got_error(GOT_ERR_NOT_MERGING);
13440 goto done;
13443 if (abort_merge) {
13444 error = got_worktree_merge_continue(&branch_name,
13445 &branch_tip, &fileindex, worktree, repo);
13446 if (error)
13447 goto done;
13448 error = got_worktree_merge_abort(worktree, fileindex, repo,
13449 abort_progress, &upa);
13450 if (error)
13451 goto done;
13452 printf("Merge of %s aborted\n", branch_name);
13453 goto done; /* nothing else to do */
13456 if (strncmp(got_worktree_get_head_ref_name(worktree),
13457 "refs/heads/", 11) != 0) {
13458 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13459 "work tree's current branch %s is outside the "
13460 "\"refs/heads/\" reference namespace; "
13461 "update -b required",
13462 got_worktree_get_head_ref_name(worktree));
13463 goto done;
13466 error = get_author(&author, repo, worktree);
13467 if (error)
13468 goto done;
13470 error = got_ref_open(&wt_branch, repo,
13471 got_worktree_get_head_ref_name(worktree), 0);
13472 if (error)
13473 goto done;
13474 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13475 if (error)
13476 goto done;
13478 if (continue_merge) {
13479 struct got_object_id *base_commit_id;
13480 base_commit_id = got_worktree_get_base_commit_id(worktree);
13481 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13482 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13483 goto done;
13485 error = got_worktree_merge_continue(&branch_name,
13486 &branch_tip, &fileindex, worktree, repo);
13487 if (error)
13488 goto done;
13489 } else {
13490 error = got_ref_open(&branch, repo, argv[0], 0);
13491 if (error != NULL)
13492 goto done;
13493 branch_name = strdup(got_ref_get_name(branch));
13494 if (branch_name == NULL) {
13495 error = got_error_from_errno("strdup");
13496 goto done;
13498 error = got_ref_resolve(&branch_tip, repo, branch);
13499 if (error)
13500 goto done;
13503 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13504 wt_branch_tip, branch_tip, 0, repo,
13505 check_cancelled, NULL);
13506 if (error && error->code != GOT_ERR_ANCESTRY)
13507 goto done;
13509 if (!continue_merge) {
13510 error = check_path_prefix(wt_branch_tip, branch_tip,
13511 got_worktree_get_path_prefix(worktree),
13512 GOT_ERR_MERGE_PATH, repo);
13513 if (error)
13514 goto done;
13515 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13516 if (error)
13517 goto done;
13518 if (prefer_fast_forward && yca_id &&
13519 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13520 struct got_pathlist_head paths;
13521 if (interrupt_merge) {
13522 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13523 "there are no changes to merge since %s "
13524 "is already based on %s; merge cannot be "
13525 "interrupted for amending; -n",
13526 branch_name, got_ref_get_name(wt_branch));
13527 goto done;
13529 printf("Forwarding %s to %s\n",
13530 got_ref_get_name(wt_branch), branch_name);
13531 error = got_ref_change_ref(wt_branch, branch_tip);
13532 if (error)
13533 goto done;
13534 error = got_ref_write(wt_branch, repo);
13535 if (error)
13536 goto done;
13537 error = got_worktree_set_base_commit_id(worktree, repo,
13538 branch_tip);
13539 if (error)
13540 goto done;
13541 TAILQ_INIT(&paths);
13542 error = got_pathlist_append(&paths, "", NULL);
13543 if (error)
13544 goto done;
13545 error = got_worktree_checkout_files(worktree,
13546 &paths, repo, update_progress, &upa,
13547 check_cancelled, NULL);
13548 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13549 if (error)
13550 goto done;
13551 if (upa.did_something) {
13552 char *id_str;
13553 error = got_object_id_str(&id_str, branch_tip);
13554 if (error)
13555 goto done;
13556 printf("Updated to commit %s\n", id_str);
13557 free(id_str);
13558 } else
13559 printf("Already up-to-date\n");
13560 print_update_progress_stats(&upa);
13561 goto done;
13563 error = got_worktree_merge_write_refs(worktree, branch, repo);
13564 if (error)
13565 goto done;
13567 error = got_worktree_merge_branch(worktree, fileindex,
13568 yca_id, branch_tip, repo, update_progress, &upa,
13569 check_cancelled, NULL);
13570 if (error)
13571 goto done;
13572 print_merge_progress_stats(&upa);
13573 if (!upa.did_something) {
13574 error = got_worktree_merge_abort(worktree, fileindex,
13575 repo, abort_progress, &upa);
13576 if (error)
13577 goto done;
13578 printf("Already up-to-date\n");
13579 goto done;
13583 if (interrupt_merge) {
13584 error = got_worktree_merge_postpone(worktree, fileindex);
13585 if (error)
13586 goto done;
13587 printf("Merge of %s interrupted on request\n", branch_name);
13588 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13589 upa.not_deleted > 0 || upa.unversioned > 0) {
13590 error = got_worktree_merge_postpone(worktree, fileindex);
13591 if (error)
13592 goto done;
13593 if (upa.conflicts > 0 && upa.missing == 0 &&
13594 upa.not_deleted == 0 && upa.unversioned == 0) {
13595 error = got_error_msg(GOT_ERR_CONFLICTS,
13596 "conflicts must be resolved before merging "
13597 "can continue");
13598 } else if (upa.conflicts > 0) {
13599 error = got_error_msg(GOT_ERR_CONFLICTS,
13600 "conflicts must be resolved before merging "
13601 "can continue; changes destined for some "
13602 "files were not yet merged and "
13603 "should be merged manually if required before the "
13604 "merge operation is continued");
13605 } else {
13606 error = got_error_msg(GOT_ERR_CONFLICTS,
13607 "changes destined for some "
13608 "files were not yet merged and should be "
13609 "merged manually if required before the "
13610 "merge operation is continued");
13612 goto done;
13613 } else {
13614 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13615 fileindex, author, NULL, 1, branch_tip, branch_name,
13616 allow_conflict, repo, continue_merge ? print_status : NULL,
13617 NULL);
13618 if (error)
13619 goto done;
13620 error = got_worktree_merge_complete(worktree, fileindex, repo);
13621 if (error)
13622 goto done;
13623 error = got_object_id_str(&id_str, merge_commit_id);
13624 if (error)
13625 goto done;
13626 printf("Merged %s into %s: %s\n", branch_name,
13627 got_worktree_get_head_ref_name(worktree),
13628 id_str);
13631 done:
13632 free(gitconfig_path);
13633 free(id_str);
13634 free(merge_commit_id);
13635 free(author);
13636 free(branch_tip);
13637 free(branch_name);
13638 free(yca_id);
13639 if (branch)
13640 got_ref_close(branch);
13641 if (wt_branch)
13642 got_ref_close(wt_branch);
13643 if (worktree)
13644 got_worktree_close(worktree);
13645 if (repo) {
13646 const struct got_error *close_err = got_repo_close(repo);
13647 if (error == NULL)
13648 error = close_err;
13650 if (pack_fds) {
13651 const struct got_error *pack_err =
13652 got_repo_pack_fds_close(pack_fds);
13653 if (error == NULL)
13654 error = pack_err;
13656 return error;
13659 __dead static void
13660 usage_stage(void)
13662 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13663 "[path ...]\n", getprogname());
13664 exit(1);
13667 static const struct got_error *
13668 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13669 const char *path, struct got_object_id *blob_id,
13670 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13671 int dirfd, const char *de_name)
13673 const struct got_error *err = NULL;
13674 char *id_str = NULL;
13676 if (staged_status != GOT_STATUS_ADD &&
13677 staged_status != GOT_STATUS_MODIFY &&
13678 staged_status != GOT_STATUS_DELETE)
13679 return NULL;
13681 if (staged_status == GOT_STATUS_ADD ||
13682 staged_status == GOT_STATUS_MODIFY)
13683 err = got_object_id_str(&id_str, staged_blob_id);
13684 else
13685 err = got_object_id_str(&id_str, blob_id);
13686 if (err)
13687 return err;
13689 printf("%s %c %s\n", id_str, staged_status, path);
13690 free(id_str);
13691 return NULL;
13694 static const struct got_error *
13695 cmd_stage(int argc, char *argv[])
13697 const struct got_error *error = NULL;
13698 struct got_repository *repo = NULL;
13699 struct got_worktree *worktree = NULL;
13700 char *cwd = NULL;
13701 struct got_pathlist_head paths;
13702 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13703 FILE *patch_script_file = NULL;
13704 const char *patch_script_path = NULL;
13705 struct choose_patch_arg cpa;
13706 int *pack_fds = NULL;
13708 TAILQ_INIT(&paths);
13710 #ifndef PROFILE
13711 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13712 "unveil", NULL) == -1)
13713 err(1, "pledge");
13714 #endif
13716 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13717 switch (ch) {
13718 case 'F':
13719 patch_script_path = optarg;
13720 break;
13721 case 'l':
13722 list_stage = 1;
13723 break;
13724 case 'p':
13725 pflag = 1;
13726 break;
13727 case 'S':
13728 allow_bad_symlinks = 1;
13729 break;
13730 default:
13731 usage_stage();
13732 /* NOTREACHED */
13736 argc -= optind;
13737 argv += optind;
13739 if (list_stage && (pflag || patch_script_path))
13740 errx(1, "-l option cannot be used with other options");
13741 if (patch_script_path && !pflag)
13742 errx(1, "-F option can only be used together with -p option");
13744 cwd = getcwd(NULL, 0);
13745 if (cwd == NULL) {
13746 error = got_error_from_errno("getcwd");
13747 goto done;
13750 error = got_repo_pack_fds_open(&pack_fds);
13751 if (error != NULL)
13752 goto done;
13754 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13755 if (error) {
13756 if (error->code == GOT_ERR_NOT_WORKTREE)
13757 error = wrap_not_worktree_error(error, "stage", cwd);
13758 goto done;
13761 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13762 NULL, pack_fds);
13763 if (error != NULL)
13764 goto done;
13766 if (patch_script_path) {
13767 patch_script_file = fopen(patch_script_path, "re");
13768 if (patch_script_file == NULL) {
13769 error = got_error_from_errno2("fopen",
13770 patch_script_path);
13771 goto done;
13774 error = apply_unveil(got_repo_get_path(repo), 0,
13775 got_worktree_get_root_path(worktree));
13776 if (error)
13777 goto done;
13779 error = check_merge_in_progress(worktree, repo);
13780 if (error)
13781 goto done;
13783 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13784 if (error)
13785 goto done;
13787 if (list_stage)
13788 error = got_worktree_status(worktree, &paths, repo, 0,
13789 print_stage, NULL, check_cancelled, NULL);
13790 else {
13791 cpa.patch_script_file = patch_script_file;
13792 cpa.action = "stage";
13793 error = got_worktree_stage(worktree, &paths,
13794 pflag ? NULL : print_status, NULL,
13795 pflag ? choose_patch : NULL, &cpa,
13796 allow_bad_symlinks, repo);
13798 done:
13799 if (patch_script_file && fclose(patch_script_file) == EOF &&
13800 error == NULL)
13801 error = got_error_from_errno2("fclose", patch_script_path);
13802 if (repo) {
13803 const struct got_error *close_err = got_repo_close(repo);
13804 if (error == NULL)
13805 error = close_err;
13807 if (worktree)
13808 got_worktree_close(worktree);
13809 if (pack_fds) {
13810 const struct got_error *pack_err =
13811 got_repo_pack_fds_close(pack_fds);
13812 if (error == NULL)
13813 error = pack_err;
13815 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13816 free(cwd);
13817 return error;
13820 __dead static void
13821 usage_unstage(void)
13823 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13824 "[path ...]\n", getprogname());
13825 exit(1);
13829 static const struct got_error *
13830 cmd_unstage(int argc, char *argv[])
13832 const struct got_error *error = NULL;
13833 struct got_repository *repo = NULL;
13834 struct got_worktree *worktree = NULL;
13835 char *cwd = NULL;
13836 struct got_pathlist_head paths;
13837 int ch, pflag = 0;
13838 struct got_update_progress_arg upa;
13839 FILE *patch_script_file = NULL;
13840 const char *patch_script_path = NULL;
13841 struct choose_patch_arg cpa;
13842 int *pack_fds = NULL;
13844 TAILQ_INIT(&paths);
13846 #ifndef PROFILE
13847 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13848 "unveil", NULL) == -1)
13849 err(1, "pledge");
13850 #endif
13852 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13853 switch (ch) {
13854 case 'F':
13855 patch_script_path = optarg;
13856 break;
13857 case 'p':
13858 pflag = 1;
13859 break;
13860 default:
13861 usage_unstage();
13862 /* NOTREACHED */
13866 argc -= optind;
13867 argv += optind;
13869 if (patch_script_path && !pflag)
13870 errx(1, "-F option can only be used together with -p option");
13872 cwd = getcwd(NULL, 0);
13873 if (cwd == NULL) {
13874 error = got_error_from_errno("getcwd");
13875 goto done;
13878 error = got_repo_pack_fds_open(&pack_fds);
13879 if (error != NULL)
13880 goto done;
13882 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13883 if (error) {
13884 if (error->code == GOT_ERR_NOT_WORKTREE)
13885 error = wrap_not_worktree_error(error, "unstage", cwd);
13886 goto done;
13889 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13890 NULL, pack_fds);
13891 if (error != NULL)
13892 goto done;
13894 if (patch_script_path) {
13895 patch_script_file = fopen(patch_script_path, "re");
13896 if (patch_script_file == NULL) {
13897 error = got_error_from_errno2("fopen",
13898 patch_script_path);
13899 goto done;
13903 error = apply_unveil(got_repo_get_path(repo), 0,
13904 got_worktree_get_root_path(worktree));
13905 if (error)
13906 goto done;
13908 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13909 if (error)
13910 goto done;
13912 cpa.patch_script_file = patch_script_file;
13913 cpa.action = "unstage";
13914 memset(&upa, 0, sizeof(upa));
13915 error = got_worktree_unstage(worktree, &paths, update_progress,
13916 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13917 if (!error)
13918 print_merge_progress_stats(&upa);
13919 done:
13920 if (patch_script_file && fclose(patch_script_file) == EOF &&
13921 error == NULL)
13922 error = got_error_from_errno2("fclose", patch_script_path);
13923 if (repo) {
13924 const struct got_error *close_err = got_repo_close(repo);
13925 if (error == NULL)
13926 error = close_err;
13928 if (worktree)
13929 got_worktree_close(worktree);
13930 if (pack_fds) {
13931 const struct got_error *pack_err =
13932 got_repo_pack_fds_close(pack_fds);
13933 if (error == NULL)
13934 error = pack_err;
13936 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13937 free(cwd);
13938 return error;
13941 __dead static void
13942 usage_cat(void)
13944 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13945 "arg ...\n", getprogname());
13946 exit(1);
13949 static const struct got_error *
13950 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13952 const struct got_error *err;
13953 struct got_blob_object *blob;
13954 int fd = -1;
13956 fd = got_opentempfd();
13957 if (fd == -1)
13958 return got_error_from_errno("got_opentempfd");
13960 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13961 if (err)
13962 goto done;
13964 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13965 done:
13966 if (fd != -1 && close(fd) == -1 && err == NULL)
13967 err = got_error_from_errno("close");
13968 if (blob)
13969 got_object_blob_close(blob);
13970 return err;
13973 static const struct got_error *
13974 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13976 const struct got_error *err;
13977 struct got_tree_object *tree;
13978 int nentries, i;
13980 err = got_object_open_as_tree(&tree, repo, id);
13981 if (err)
13982 return err;
13984 nentries = got_object_tree_get_nentries(tree);
13985 for (i = 0; i < nentries; i++) {
13986 struct got_tree_entry *te;
13987 char *id_str;
13988 if (sigint_received || sigpipe_received)
13989 break;
13990 te = got_object_tree_get_entry(tree, i);
13991 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13992 if (err)
13993 break;
13994 fprintf(outfile, "%s %.7o %s\n", id_str,
13995 got_tree_entry_get_mode(te),
13996 got_tree_entry_get_name(te));
13997 free(id_str);
14000 got_object_tree_close(tree);
14001 return err;
14004 static const struct got_error *
14005 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14007 const struct got_error *err;
14008 struct got_commit_object *commit;
14009 const struct got_object_id_queue *parent_ids;
14010 struct got_object_qid *pid;
14011 char *id_str = NULL;
14012 const char *logmsg = NULL;
14013 char gmtoff[6];
14015 err = got_object_open_as_commit(&commit, repo, id);
14016 if (err)
14017 return err;
14019 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14020 if (err)
14021 goto done;
14023 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14024 parent_ids = got_object_commit_get_parent_ids(commit);
14025 fprintf(outfile, "numparents %d\n",
14026 got_object_commit_get_nparents(commit));
14027 STAILQ_FOREACH(pid, parent_ids, entry) {
14028 char *pid_str;
14029 err = got_object_id_str(&pid_str, &pid->id);
14030 if (err)
14031 goto done;
14032 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14033 free(pid_str);
14035 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14036 got_object_commit_get_author_gmtoff(commit));
14037 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14038 got_object_commit_get_author(commit),
14039 (long long)got_object_commit_get_author_time(commit),
14040 gmtoff);
14042 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14043 got_object_commit_get_committer_gmtoff(commit));
14044 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14045 got_object_commit_get_committer(commit),
14046 (long long)got_object_commit_get_committer_time(commit),
14047 gmtoff);
14049 logmsg = got_object_commit_get_logmsg_raw(commit);
14050 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14051 fprintf(outfile, "%s", logmsg);
14052 done:
14053 free(id_str);
14054 got_object_commit_close(commit);
14055 return err;
14058 static const struct got_error *
14059 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14061 const struct got_error *err;
14062 struct got_tag_object *tag;
14063 char *id_str = NULL;
14064 const char *tagmsg = NULL;
14065 char gmtoff[6];
14067 err = got_object_open_as_tag(&tag, repo, id);
14068 if (err)
14069 return err;
14071 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14072 if (err)
14073 goto done;
14075 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14077 switch (got_object_tag_get_object_type(tag)) {
14078 case GOT_OBJ_TYPE_BLOB:
14079 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14080 GOT_OBJ_LABEL_BLOB);
14081 break;
14082 case GOT_OBJ_TYPE_TREE:
14083 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14084 GOT_OBJ_LABEL_TREE);
14085 break;
14086 case GOT_OBJ_TYPE_COMMIT:
14087 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14088 GOT_OBJ_LABEL_COMMIT);
14089 break;
14090 case GOT_OBJ_TYPE_TAG:
14091 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14092 GOT_OBJ_LABEL_TAG);
14093 break;
14094 default:
14095 break;
14098 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14099 got_object_tag_get_name(tag));
14101 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14102 got_object_tag_get_tagger_gmtoff(tag));
14103 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14104 got_object_tag_get_tagger(tag),
14105 (long long)got_object_tag_get_tagger_time(tag),
14106 gmtoff);
14108 tagmsg = got_object_tag_get_message(tag);
14109 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14110 fprintf(outfile, "%s", tagmsg);
14111 done:
14112 free(id_str);
14113 got_object_tag_close(tag);
14114 return err;
14117 static const struct got_error *
14118 cmd_cat(int argc, char *argv[])
14120 const struct got_error *error;
14121 struct got_repository *repo = NULL;
14122 struct got_worktree *worktree = NULL;
14123 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14124 char *keyword_idstr = NULL;
14125 const char *commit_id_str = NULL;
14126 struct got_object_id *id = NULL, *commit_id = NULL;
14127 struct got_commit_object *commit = NULL;
14128 int ch, obj_type, i, force_path = 0;
14129 struct got_reflist_head refs;
14130 int *pack_fds = NULL;
14132 TAILQ_INIT(&refs);
14134 #ifndef PROFILE
14135 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14136 NULL) == -1)
14137 err(1, "pledge");
14138 #endif
14140 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14141 switch (ch) {
14142 case 'c':
14143 commit_id_str = optarg;
14144 break;
14145 case 'P':
14146 force_path = 1;
14147 break;
14148 case 'r':
14149 repo_path = realpath(optarg, NULL);
14150 if (repo_path == NULL)
14151 return got_error_from_errno2("realpath",
14152 optarg);
14153 got_path_strip_trailing_slashes(repo_path);
14154 break;
14155 default:
14156 usage_cat();
14157 /* NOTREACHED */
14161 argc -= optind;
14162 argv += optind;
14164 cwd = getcwd(NULL, 0);
14165 if (cwd == NULL) {
14166 error = got_error_from_errno("getcwd");
14167 goto done;
14170 error = got_repo_pack_fds_open(&pack_fds);
14171 if (error != NULL)
14172 goto done;
14174 if (repo_path == NULL) {
14175 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14176 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14177 goto done;
14178 if (worktree) {
14179 repo_path = strdup(
14180 got_worktree_get_repo_path(worktree));
14181 if (repo_path == NULL) {
14182 error = got_error_from_errno("strdup");
14183 goto done;
14186 if (commit_id_str == NULL) {
14187 /* Release work tree lock. */
14188 got_worktree_close(worktree);
14189 worktree = NULL;
14194 if (repo_path == NULL) {
14195 repo_path = strdup(cwd);
14196 if (repo_path == NULL)
14197 return got_error_from_errno("strdup");
14200 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14201 free(repo_path);
14202 if (error != NULL)
14203 goto done;
14205 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14206 if (error)
14207 goto done;
14209 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14210 if (error)
14211 goto done;
14213 if (commit_id_str != NULL) {
14214 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14215 repo, worktree);
14216 if (error != NULL)
14217 goto done;
14218 if (keyword_idstr != NULL)
14219 commit_id_str = keyword_idstr;
14220 if (worktree != NULL) {
14221 got_worktree_close(worktree);
14222 worktree = NULL;
14224 } else
14225 commit_id_str = GOT_REF_HEAD;
14226 error = got_repo_match_object_id(&commit_id, NULL,
14227 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14228 if (error)
14229 goto done;
14231 error = got_object_open_as_commit(&commit, repo, commit_id);
14232 if (error)
14233 goto done;
14235 for (i = 0; i < argc; i++) {
14236 if (force_path) {
14237 error = got_object_id_by_path(&id, repo, commit,
14238 argv[i]);
14239 if (error)
14240 break;
14241 } else {
14242 error = got_repo_match_object_id(&id, &label, argv[i],
14243 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14244 repo);
14245 if (error) {
14246 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14247 error->code != GOT_ERR_NOT_REF)
14248 break;
14249 error = got_object_id_by_path(&id, repo,
14250 commit, argv[i]);
14251 if (error)
14252 break;
14256 error = got_object_get_type(&obj_type, repo, id);
14257 if (error)
14258 break;
14260 switch (obj_type) {
14261 case GOT_OBJ_TYPE_BLOB:
14262 error = cat_blob(id, repo, stdout);
14263 break;
14264 case GOT_OBJ_TYPE_TREE:
14265 error = cat_tree(id, repo, stdout);
14266 break;
14267 case GOT_OBJ_TYPE_COMMIT:
14268 error = cat_commit(id, repo, stdout);
14269 break;
14270 case GOT_OBJ_TYPE_TAG:
14271 error = cat_tag(id, repo, stdout);
14272 break;
14273 default:
14274 error = got_error(GOT_ERR_OBJ_TYPE);
14275 break;
14277 if (error)
14278 break;
14279 free(label);
14280 label = NULL;
14281 free(id);
14282 id = NULL;
14284 done:
14285 free(label);
14286 free(id);
14287 free(commit_id);
14288 free(keyword_idstr);
14289 if (commit)
14290 got_object_commit_close(commit);
14291 if (worktree)
14292 got_worktree_close(worktree);
14293 if (repo) {
14294 const struct got_error *close_err = got_repo_close(repo);
14295 if (error == NULL)
14296 error = close_err;
14298 if (pack_fds) {
14299 const struct got_error *pack_err =
14300 got_repo_pack_fds_close(pack_fds);
14301 if (error == NULL)
14302 error = pack_err;
14305 got_ref_list_free(&refs);
14306 return error;
14309 __dead static void
14310 usage_info(void)
14312 fprintf(stderr, "usage: %s info [path ...]\n",
14313 getprogname());
14314 exit(1);
14317 static const struct got_error *
14318 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14319 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14320 struct got_object_id *commit_id)
14322 const struct got_error *err = NULL;
14323 char *id_str = NULL;
14324 char datebuf[128];
14325 struct tm mytm, *tm;
14326 struct got_pathlist_head *paths = arg;
14327 struct got_pathlist_entry *pe;
14330 * Clear error indication from any of the path arguments which
14331 * would cause this file index entry to be displayed.
14333 TAILQ_FOREACH(pe, paths, entry) {
14334 if (got_path_cmp(path, pe->path, strlen(path),
14335 pe->path_len) == 0 ||
14336 got_path_is_child(path, pe->path, pe->path_len))
14337 pe->data = NULL; /* no error */
14340 printf(GOT_COMMIT_SEP_STR);
14341 if (S_ISLNK(mode))
14342 printf("symlink: %s\n", path);
14343 else if (S_ISREG(mode)) {
14344 printf("file: %s\n", path);
14345 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14346 } else if (S_ISDIR(mode))
14347 printf("directory: %s\n", path);
14348 else
14349 printf("something: %s\n", path);
14351 tm = localtime_r(&mtime, &mytm);
14352 if (tm == NULL)
14353 return NULL;
14354 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14355 return got_error(GOT_ERR_NO_SPACE);
14356 printf("timestamp: %s\n", datebuf);
14358 if (blob_id) {
14359 err = got_object_id_str(&id_str, blob_id);
14360 if (err)
14361 return err;
14362 printf("based on blob: %s\n", id_str);
14363 free(id_str);
14366 if (staged_blob_id) {
14367 err = got_object_id_str(&id_str, staged_blob_id);
14368 if (err)
14369 return err;
14370 printf("based on staged blob: %s\n", id_str);
14371 free(id_str);
14374 if (commit_id) {
14375 err = got_object_id_str(&id_str, commit_id);
14376 if (err)
14377 return err;
14378 printf("based on commit: %s\n", id_str);
14379 free(id_str);
14382 return NULL;
14385 static const struct got_error *
14386 cmd_info(int argc, char *argv[])
14388 const struct got_error *error = NULL;
14389 struct got_worktree *worktree = NULL;
14390 char *cwd = NULL, *id_str = NULL;
14391 struct got_pathlist_head paths;
14392 char *uuidstr = NULL;
14393 int ch, show_files = 0;
14395 TAILQ_INIT(&paths);
14397 #ifndef PROFILE
14398 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14399 NULL) == -1)
14400 err(1, "pledge");
14401 #endif
14403 while ((ch = getopt(argc, argv, "")) != -1) {
14404 switch (ch) {
14405 default:
14406 usage_info();
14407 /* NOTREACHED */
14411 argc -= optind;
14412 argv += optind;
14414 cwd = getcwd(NULL, 0);
14415 if (cwd == NULL) {
14416 error = got_error_from_errno("getcwd");
14417 goto done;
14420 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14421 if (error) {
14422 if (error->code == GOT_ERR_NOT_WORKTREE)
14423 error = wrap_not_worktree_error(error, "info", cwd);
14424 goto done;
14427 #ifndef PROFILE
14428 /* Remove "wpath cpath proc exec sendfd" promises. */
14429 if (pledge("stdio rpath flock unveil", NULL) == -1)
14430 err(1, "pledge");
14431 #endif
14432 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14433 if (error)
14434 goto done;
14436 if (argc >= 1) {
14437 error = get_worktree_paths_from_argv(&paths, argc, argv,
14438 worktree);
14439 if (error)
14440 goto done;
14441 show_files = 1;
14444 error = got_object_id_str(&id_str,
14445 got_worktree_get_base_commit_id(worktree));
14446 if (error)
14447 goto done;
14449 error = got_worktree_get_uuid(&uuidstr, worktree);
14450 if (error)
14451 goto done;
14453 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14454 printf("work tree base commit: %s\n", id_str);
14455 printf("work tree path prefix: %s\n",
14456 got_worktree_get_path_prefix(worktree));
14457 printf("work tree branch reference: %s\n",
14458 got_worktree_get_head_ref_name(worktree));
14459 printf("work tree UUID: %s\n", uuidstr);
14460 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14462 if (show_files) {
14463 struct got_pathlist_entry *pe;
14464 TAILQ_FOREACH(pe, &paths, entry) {
14465 if (pe->path_len == 0)
14466 continue;
14468 * Assume this path will fail. This will be corrected
14469 * in print_path_info() in case the path does suceeed.
14471 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14473 error = got_worktree_path_info(worktree, &paths,
14474 print_path_info, &paths, check_cancelled, NULL);
14475 if (error)
14476 goto done;
14477 TAILQ_FOREACH(pe, &paths, entry) {
14478 if (pe->data != NULL) {
14479 const struct got_error *perr;
14481 perr = pe->data;
14482 error = got_error_fmt(perr->code, "%s",
14483 pe->path);
14484 break;
14488 done:
14489 if (worktree)
14490 got_worktree_close(worktree);
14491 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14492 free(cwd);
14493 free(id_str);
14494 free(uuidstr);
14495 return error;