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 "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.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>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fflush(stdout);
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/usr/bin/vi");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_import(void)
352 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
353 "[-r repository-path] directory\n", getprogname());
354 exit(1);
357 static int
358 spawn_editor(const char *editor, const char *file)
360 pid_t pid;
361 sig_t sighup, sigint, sigquit;
362 int st = -1;
364 sighup = signal(SIGHUP, SIG_IGN);
365 sigint = signal(SIGINT, SIG_IGN);
366 sigquit = signal(SIGQUIT, SIG_IGN);
368 switch (pid = fork()) {
369 case -1:
370 goto doneediting;
371 case 0:
372 execl(editor, editor, file, (char *)NULL);
373 _exit(127);
376 while (waitpid(pid, &st, 0) == -1)
377 if (errno != EINTR)
378 break;
380 doneediting:
381 (void)signal(SIGHUP, sighup);
382 (void)signal(SIGINT, sigint);
383 (void)signal(SIGQUIT, sigquit);
385 if (!WIFEXITED(st)) {
386 errno = EINTR;
387 return -1;
390 return WEXITSTATUS(st);
393 static const struct got_error *
394 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
400 *logmsg = NULL;
401 *len = 0;
403 if (fseeko(fp, 0L, SEEK_SET) == -1)
404 return got_error_from_errno("fseeko");
406 *logmsg = malloc(filesize + 1);
407 if (*logmsg == NULL)
408 return got_error_from_errno("malloc");
409 (*logmsg)[0] = '\0';
411 while (getline(&line, &linesize, fp) != -1) {
412 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t logmsg_len;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (require_modification) {
458 struct timespec timeout;
460 timeout.tv_sec = 0;
461 timeout.tv_nsec = 1;
462 nanosleep(&timeout, NULL);
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno2("stat", logmsg_path);
468 if (require_modification && st.st_size == st2.st_size &&
469 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 fp = fopen(logmsg_path, "re");
474 if (fp == NULL) {
475 err = got_error_from_errno("fopen");
476 goto done;
479 /* strip comments and leading/trailing newlines */
480 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
481 if (err)
482 goto done;
483 if (logmsg_len == 0) {
484 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
485 "commit message cannot be empty, aborting");
486 goto done;
488 done:
489 if (fp && fclose(fp) == EOF && err == NULL)
490 err = got_error_from_errno("fclose");
491 if (err) {
492 free(*logmsg);
493 *logmsg = NULL;
495 return err;
498 static const struct got_error *
499 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
500 const char *path_dir, const char *branch_name)
502 char *initial_content = NULL;
503 const struct got_error *err = NULL;
504 int initial_content_len;
505 int fd = -1;
507 initial_content_len = asprintf(&initial_content,
508 "\n# %s to be imported to branch %s\n", path_dir,
509 branch_name);
510 if (initial_content_len == -1)
511 return got_error_from_errno("asprintf");
513 err = got_opentemp_named_fd(logmsg_path, &fd,
514 GOT_TMPDIR_STR "/got-importmsg", "");
515 if (err)
516 goto done;
518 if (write(fd, initial_content, initial_content_len) == -1) {
519 err = got_error_from_errno2("write", *logmsg_path);
520 goto done;
522 if (close(fd) == -1) {
523 err = got_error_from_errno2("close", *logmsg_path);
524 goto done;
526 fd = -1;
528 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
529 initial_content_len, 1);
530 done:
531 if (fd != -1 && close(fd) == -1 && err == NULL)
532 err = got_error_from_errno2("close", *logmsg_path);
533 free(initial_content);
534 if (err) {
535 free(*logmsg_path);
536 *logmsg_path = NULL;
538 return err;
541 static const struct got_error *
542 import_progress(void *arg, const char *path)
544 printf("A %s\n", path);
545 return NULL;
548 static const struct got_error *
549 valid_author(const char *author)
551 const char *email = author;
553 /*
554 * Git' expects the author (or committer) to be in the form
555 * "name <email>", which are mostly free form (see the
556 * "committer" description in git-fast-import(1)). We're only
557 * doing this to avoid git's object parser breaking on commits
558 * we create.
559 */
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (author != email && *author == '<' && *(author - 1) != ' ')
564 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
565 "between author name and email required", email);
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const char *
711 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 if (worktree)
717 worktree_conf = got_worktree_get_gotconfig(worktree);
718 repo_conf = got_repo_get_gotconfig(repo);
720 /*
721 * Priority of potential author information sources, from most
722 * significant to least significant:
723 * 1) work tree's .got/got.conf file
724 * 2) repository's got.conf file
725 */
727 if (worktree_conf)
728 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
729 if (got_signer_id == NULL)
730 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
732 return got_signer_id;
735 static const struct got_error *
736 get_gitconfig_path(char **gitconfig_path)
738 const char *homedir = getenv("HOME");
740 *gitconfig_path = NULL;
741 if (homedir) {
742 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
743 return got_error_from_errno("asprintf");
746 return NULL;
749 static const struct got_error *
750 cmd_import(int argc, char *argv[])
752 const struct got_error *error = NULL;
753 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
754 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
755 const char *branch_name = NULL;
756 char *id_str = NULL, *logmsg_path = NULL;
757 char refname[PATH_MAX] = "refs/heads/";
758 struct got_repository *repo = NULL;
759 struct got_reference *branch_ref = NULL, *head_ref = NULL;
760 struct got_object_id *new_commit_id = NULL;
761 int ch, n = 0;
762 struct got_pathlist_head ignores;
763 struct got_pathlist_entry *pe;
764 int preserve_logmsg = 0;
765 int *pack_fds = NULL;
767 TAILQ_INIT(&ignores);
769 #ifndef PROFILE
770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
771 "unveil",
772 NULL) == -1)
773 err(1, "pledge");
774 #endif
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 if (argc != 1)
814 usage_import();
816 if (repo_path == NULL) {
817 repo_path = getcwd(NULL, 0);
818 if (repo_path == NULL)
819 return got_error_from_errno("getcwd");
821 got_path_strip_trailing_slashes(repo_path);
822 error = get_gitconfig_path(&gitconfig_path);
823 if (error)
824 goto done;
825 error = got_repo_pack_fds_open(&pack_fds);
826 if (error != NULL)
827 goto done;
828 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
829 if (error)
830 goto done;
832 error = get_author(&author, repo, NULL);
833 if (error)
834 return error;
836 /*
837 * Don't let the user create a branch name with a leading '-'.
838 * While technically a valid reference name, this case is usually
839 * an unintended typo.
840 */
841 if (branch_name && branch_name[0] == '-')
842 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
844 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
845 if (error && error->code != GOT_ERR_NOT_REF)
846 goto done;
848 if (branch_name)
849 n = strlcat(refname, branch_name, sizeof(refname));
850 else if (head_ref && got_ref_is_symbolic(head_ref))
851 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
852 sizeof(refname));
853 else
854 n = strlcat(refname, "main", sizeof(refname));
855 if (n >= sizeof(refname)) {
856 error = got_error(GOT_ERR_NO_SPACE);
857 goto done;
860 error = got_ref_open(&branch_ref, repo, refname, 0);
861 if (error) {
862 if (error->code != GOT_ERR_NOT_REF)
863 goto done;
864 } else {
865 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
866 "import target branch already exists");
867 goto done;
870 path_dir = realpath(argv[0], NULL);
871 if (path_dir == NULL) {
872 error = got_error_from_errno2("realpath", argv[0]);
873 goto done;
875 got_path_strip_trailing_slashes(path_dir);
877 /*
878 * unveil(2) traverses exec(2); if an editor is used we have
879 * to apply unveil after the log message has been written.
880 */
881 if (logmsg == NULL || *logmsg == '\0') {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes;
2291 struct got_remote_repo *remote = NULL;
2292 int nremotes;
2293 char *id_str = NULL;
2294 struct got_repository *repo = NULL;
2295 struct got_worktree *worktree = NULL;
2296 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2297 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2298 char *head_refname = NULL;
2299 struct got_pathlist_entry *pe;
2300 struct got_reflist_head remote_refs;
2301 struct got_reflist_entry *re;
2302 struct got_object_id *pack_hash = NULL;
2303 int i, ch, fetchfd = -1, fetchstatus;
2304 pid_t fetchpid = -1;
2305 struct got_fetch_progress_arg fpa;
2306 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2307 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2308 int *pack_fds = NULL, have_bflag = 0;
2309 const char *remote_head = NULL, *worktree_branch = NULL;
2311 TAILQ_INIT(&refs);
2312 TAILQ_INIT(&symrefs);
2313 TAILQ_INIT(&remote_refs);
2314 TAILQ_INIT(&wanted_branches);
2315 TAILQ_INIT(&wanted_refs);
2317 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2318 switch (ch) {
2319 case 'a':
2320 fetch_all_branches = 1;
2321 break;
2322 case 'b':
2323 error = got_pathlist_append(&wanted_branches,
2324 optarg, NULL);
2325 if (error)
2326 return error;
2327 have_bflag = 1;
2328 break;
2329 case 'd':
2330 delete_refs = 1;
2331 break;
2332 case 'l':
2333 list_refs_only = 1;
2334 break;
2335 case 'q':
2336 verbosity = -1;
2337 break;
2338 case 'R':
2339 error = got_pathlist_append(&wanted_refs,
2340 optarg, NULL);
2341 if (error)
2342 return error;
2343 break;
2344 case 'r':
2345 repo_path = realpath(optarg, NULL);
2346 if (repo_path == NULL)
2347 return got_error_from_errno2("realpath",
2348 optarg);
2349 got_path_strip_trailing_slashes(repo_path);
2350 break;
2351 case 't':
2352 replace_tags = 1;
2353 break;
2354 case 'v':
2355 if (verbosity < 0)
2356 verbosity = 0;
2357 else if (verbosity < 3)
2358 verbosity++;
2359 break;
2360 case 'X':
2361 delete_remote = 1;
2362 break;
2363 default:
2364 usage_fetch();
2365 break;
2368 argc -= optind;
2369 argv += optind;
2371 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2372 option_conflict('a', 'b');
2373 if (list_refs_only) {
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('l', 'b');
2376 if (fetch_all_branches)
2377 option_conflict('l', 'a');
2378 if (delete_refs)
2379 option_conflict('l', 'd');
2380 if (delete_remote)
2381 option_conflict('l', 'X');
2383 if (delete_remote) {
2384 if (fetch_all_branches)
2385 option_conflict('X', 'a');
2386 if (!TAILQ_EMPTY(&wanted_branches))
2387 option_conflict('X', 'b');
2388 if (delete_refs)
2389 option_conflict('X', 'd');
2390 if (replace_tags)
2391 option_conflict('X', 't');
2392 if (!TAILQ_EMPTY(&wanted_refs))
2393 option_conflict('X', 'R');
2396 if (argc == 0) {
2397 if (delete_remote)
2398 errx(1, "-X option requires a remote name");
2399 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2400 } else if (argc == 1)
2401 remote_name = argv[0];
2402 else
2403 usage_fetch();
2405 cwd = getcwd(NULL, 0);
2406 if (cwd == NULL) {
2407 error = got_error_from_errno("getcwd");
2408 goto done;
2411 error = got_repo_pack_fds_open(&pack_fds);
2412 if (error != NULL)
2413 goto done;
2415 if (repo_path == NULL) {
2416 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2417 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2418 goto done;
2419 else
2420 error = NULL;
2421 if (worktree) {
2422 repo_path =
2423 strdup(got_worktree_get_repo_path(worktree));
2424 if (repo_path == NULL)
2425 error = got_error_from_errno("strdup");
2426 if (error)
2427 goto done;
2428 } else {
2429 repo_path = strdup(cwd);
2430 if (repo_path == NULL) {
2431 error = got_error_from_errno("strdup");
2432 goto done;
2437 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2438 if (error)
2439 goto done;
2441 if (delete_remote) {
2442 error = delete_refs_for_remote(repo, remote_name);
2443 goto done; /* nothing else to do */
2446 if (worktree) {
2447 worktree_conf = got_worktree_get_gotconfig(worktree);
2448 if (worktree_conf) {
2449 got_gotconfig_get_remotes(&nremotes, &remotes,
2450 worktree_conf);
2451 for (i = 0; i < nremotes; i++) {
2452 if (strcmp(remotes[i].name, remote_name) == 0) {
2453 error = got_repo_remote_repo_dup(&remote,
2454 &remotes[i]);
2455 if (error)
2456 goto done;
2457 break;
2462 if (remote == NULL) {
2463 repo_conf = got_repo_get_gotconfig(repo);
2464 if (repo_conf) {
2465 got_gotconfig_get_remotes(&nremotes, &remotes,
2466 repo_conf);
2467 for (i = 0; i < nremotes; i++) {
2468 if (strcmp(remotes[i].name, remote_name) == 0) {
2469 error = got_repo_remote_repo_dup(&remote,
2470 &remotes[i]);
2471 if (error)
2472 goto done;
2473 break;
2478 if (remote == NULL) {
2479 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2480 for (i = 0; i < nremotes; i++) {
2481 if (strcmp(remotes[i].name, remote_name) == 0) {
2482 error = got_repo_remote_repo_dup(&remote,
2483 &remotes[i]);
2484 if (error)
2485 goto done;
2486 break;
2490 if (remote == NULL) {
2491 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2492 goto done;
2495 if (TAILQ_EMPTY(&wanted_branches)) {
2496 if (!fetch_all_branches)
2497 fetch_all_branches = remote->fetch_all_branches;
2498 for (i = 0; i < remote->nfetch_branches; i++) {
2499 error = got_pathlist_append(&wanted_branches,
2500 remote->fetch_branches[i], NULL);
2501 if (error)
2502 goto done;
2505 if (TAILQ_EMPTY(&wanted_refs)) {
2506 for (i = 0; i < remote->nfetch_refs; i++) {
2507 error = got_pathlist_append(&wanted_refs,
2508 remote->fetch_refs[i], NULL);
2509 if (error)
2510 goto done;
2514 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2515 &repo_name, remote->fetch_url);
2516 if (error)
2517 goto done;
2519 if (strcmp(proto, "git") == 0) {
2520 #ifndef PROFILE
2521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2522 "sendfd dns inet unveil", NULL) == -1)
2523 err(1, "pledge");
2524 #endif
2525 } else if (strcmp(proto, "git+ssh") == 0 ||
2526 strcmp(proto, "ssh") == 0) {
2527 #ifndef PROFILE
2528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2529 "sendfd unveil", NULL) == -1)
2530 err(1, "pledge");
2531 #endif
2532 } else if (strcmp(proto, "http") == 0 ||
2533 strcmp(proto, "git+http") == 0) {
2534 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2535 goto done;
2536 } else {
2537 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2538 goto done;
2541 error = got_dial_apply_unveil(proto);
2542 if (error)
2543 goto done;
2545 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2546 if (error)
2547 goto done;
2549 if (worktree) {
2550 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2551 if (head_refname == NULL) {
2552 error = got_error_from_errno("strdup");
2553 goto done;
2556 /* Release work tree lock. */
2557 got_worktree_close(worktree);
2558 worktree = NULL;
2561 if (verbosity >= 0) {
2562 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2563 remote->name, proto, host,
2564 port ? ":" : "", port ? port : "",
2565 *server_path == '/' ? "" : "/", server_path);
2568 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2569 server_path, verbosity);
2570 if (error)
2571 goto done;
2573 if (!have_bflag) {
2575 * If set, get this remote's HEAD ref target so
2576 * if it has changed on the server we can fetch it.
2578 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2579 got_ref_cmp_by_name, repo);
2580 if (error)
2581 goto done;
2583 TAILQ_FOREACH(re, &remote_refs, entry) {
2584 const char *remote_refname, *remote_target;
2585 size_t remote_name_len;
2587 if (!got_ref_is_symbolic(re->ref))
2588 continue;
2590 remote_name_len = strlen(remote->name);
2591 remote_refname = got_ref_get_name(re->ref);
2593 /* we only want refs/remotes/$remote->name/HEAD */
2594 if (strncmp(remote_refname + 13, remote->name,
2595 remote_name_len) != 0)
2596 continue;
2598 if (strcmp(remote_refname + remote_name_len + 14,
2599 GOT_REF_HEAD) != 0)
2600 continue;
2603 * Take the name itself because we already
2604 * only match with refs/heads/ in fetch_pack().
2606 remote_target = got_ref_get_symref_target(re->ref);
2607 remote_head = remote_target + remote_name_len + 14;
2608 break;
2611 if (head_refname &&
2612 strncmp(head_refname, "refs/heads/", 11) == 0)
2613 worktree_branch = head_refname;
2616 fpa.last_scaled_size[0] = '\0';
2617 fpa.last_p_indexed = -1;
2618 fpa.last_p_resolved = -1;
2619 fpa.verbosity = verbosity;
2620 fpa.repo = repo;
2621 fpa.create_configs = 0;
2622 fpa.configs_created = 0;
2623 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2625 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2626 remote->mirror_references, fetch_all_branches, &wanted_branches,
2627 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2628 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2629 if (error)
2630 goto done;
2632 if (list_refs_only) {
2633 error = list_remote_refs(&symrefs, &refs);
2634 goto done;
2637 if (pack_hash == NULL) {
2638 if (verbosity >= 0)
2639 printf("Already up-to-date\n");
2640 } else if (verbosity >= 0) {
2641 error = got_object_id_str(&id_str, pack_hash);
2642 if (error)
2643 goto done;
2644 printf("\nFetched %s.pack\n", id_str);
2645 free(id_str);
2646 id_str = NULL;
2649 /* Update references provided with the pack file. */
2650 TAILQ_FOREACH(pe, &refs, entry) {
2651 const char *refname = pe->path;
2652 struct got_object_id *id = pe->data;
2653 struct got_reference *ref;
2654 char *remote_refname;
2656 if (is_wanted_ref(&wanted_refs, refname) &&
2657 !remote->mirror_references) {
2658 error = update_wanted_ref(refname, id,
2659 remote->name, verbosity, repo);
2660 if (error)
2661 goto done;
2662 continue;
2665 if (remote->mirror_references ||
2666 strncmp("refs/tags/", refname, 10) == 0) {
2667 error = got_ref_open(&ref, repo, refname, 1);
2668 if (error) {
2669 if (error->code != GOT_ERR_NOT_REF)
2670 goto done;
2671 error = create_ref(refname, id, verbosity,
2672 repo);
2673 if (error)
2674 goto done;
2675 } else {
2676 error = update_ref(ref, id, replace_tags,
2677 verbosity, repo);
2678 unlock_err = got_ref_unlock(ref);
2679 if (unlock_err && error == NULL)
2680 error = unlock_err;
2681 got_ref_close(ref);
2682 if (error)
2683 goto done;
2685 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2686 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2687 remote_name, refname + 11) == -1) {
2688 error = got_error_from_errno("asprintf");
2689 goto done;
2692 error = got_ref_open(&ref, repo, remote_refname, 1);
2693 if (error) {
2694 if (error->code != GOT_ERR_NOT_REF)
2695 goto done;
2696 error = create_ref(remote_refname, id,
2697 verbosity, repo);
2698 if (error)
2699 goto done;
2700 } else {
2701 error = update_ref(ref, id, replace_tags,
2702 verbosity, repo);
2703 unlock_err = got_ref_unlock(ref);
2704 if (unlock_err && error == NULL)
2705 error = unlock_err;
2706 got_ref_close(ref);
2707 if (error)
2708 goto done;
2711 /* Also create a local branch if none exists yet. */
2712 error = got_ref_open(&ref, repo, refname, 1);
2713 if (error) {
2714 if (error->code != GOT_ERR_NOT_REF)
2715 goto done;
2716 error = create_ref(refname, id, verbosity,
2717 repo);
2718 if (error)
2719 goto done;
2720 } else {
2721 unlock_err = got_ref_unlock(ref);
2722 if (unlock_err && error == NULL)
2723 error = unlock_err;
2724 got_ref_close(ref);
2728 if (delete_refs) {
2729 error = delete_missing_refs(&refs, &symrefs, remote,
2730 verbosity, repo);
2731 if (error)
2732 goto done;
2735 if (!remote->mirror_references) {
2736 /* Update remote HEAD reference if the server provided one. */
2737 TAILQ_FOREACH(pe, &symrefs, entry) {
2738 struct got_reference *target_ref;
2739 const char *refname = pe->path;
2740 const char *target = pe->data;
2741 char *remote_refname = NULL, *remote_target = NULL;
2743 if (strcmp(refname, GOT_REF_HEAD) != 0)
2744 continue;
2746 if (strncmp("refs/heads/", target, 11) != 0)
2747 continue;
2749 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2750 remote->name, refname) == -1) {
2751 error = got_error_from_errno("asprintf");
2752 goto done;
2754 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2755 remote->name, target + 11) == -1) {
2756 error = got_error_from_errno("asprintf");
2757 free(remote_refname);
2758 goto done;
2761 error = got_ref_open(&target_ref, repo, remote_target,
2762 0);
2763 if (error) {
2764 free(remote_refname);
2765 free(remote_target);
2766 if (error->code == GOT_ERR_NOT_REF) {
2767 error = NULL;
2768 continue;
2770 goto done;
2772 error = update_symref(remote_refname, target_ref,
2773 verbosity, repo);
2774 free(remote_refname);
2775 free(remote_target);
2776 got_ref_close(target_ref);
2777 if (error)
2778 goto done;
2781 done:
2782 if (fetchpid > 0) {
2783 if (kill(fetchpid, SIGTERM) == -1)
2784 error = got_error_from_errno("kill");
2785 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2786 error = got_error_from_errno("waitpid");
2788 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2789 error = got_error_from_errno("close");
2790 if (repo) {
2791 const struct got_error *close_err = got_repo_close(repo);
2792 if (error == NULL)
2793 error = close_err;
2795 if (worktree)
2796 got_worktree_close(worktree);
2797 if (pack_fds) {
2798 const struct got_error *pack_err =
2799 got_repo_pack_fds_close(pack_fds);
2800 if (error == NULL)
2801 error = pack_err;
2803 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2804 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2805 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2806 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2807 got_ref_list_free(&remote_refs);
2808 got_repo_free_remote_repo_data(remote);
2809 free(remote);
2810 free(head_refname);
2811 free(id_str);
2812 free(cwd);
2813 free(repo_path);
2814 free(pack_hash);
2815 free(proto);
2816 free(host);
2817 free(port);
2818 free(server_path);
2819 free(repo_name);
2820 return error;
2824 __dead static void
2825 usage_checkout(void)
2827 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2828 "[-p path-prefix] repository-path [work-tree-path]\n",
2829 getprogname());
2830 exit(1);
2833 static void
2834 show_worktree_base_ref_warning(void)
2836 fprintf(stderr, "%s: warning: could not create a reference "
2837 "to the work tree's base commit; the commit could be "
2838 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2839 "repository writable and running 'got update' will prevent this\n",
2840 getprogname());
2843 struct got_checkout_progress_arg {
2844 const char *worktree_path;
2845 int had_base_commit_ref_error;
2846 int verbosity;
2849 static const struct got_error *
2850 checkout_progress(void *arg, unsigned char status, const char *path)
2852 struct got_checkout_progress_arg *a = arg;
2854 /* Base commit bump happens silently. */
2855 if (status == GOT_STATUS_BUMP_BASE)
2856 return NULL;
2858 if (status == GOT_STATUS_BASE_REF_ERR) {
2859 a->had_base_commit_ref_error = 1;
2860 return NULL;
2863 while (path[0] == '/')
2864 path++;
2866 if (a->verbosity >= 0)
2867 printf("%c %s/%s\n", status, a->worktree_path, path);
2869 return NULL;
2872 static const struct got_error *
2873 check_cancelled(void *arg)
2875 if (sigint_received || sigpipe_received)
2876 return got_error(GOT_ERR_CANCELLED);
2877 return NULL;
2880 static const struct got_error *
2881 check_linear_ancestry(struct got_object_id *commit_id,
2882 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2883 struct got_repository *repo)
2885 const struct got_error *err = NULL;
2886 struct got_object_id *yca_id;
2888 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2889 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2890 if (err)
2891 return err;
2893 if (yca_id == NULL)
2894 return got_error(GOT_ERR_ANCESTRY);
2897 * Require a straight line of history between the target commit
2898 * and the work tree's base commit.
2900 * Non-linear situations such as this require a rebase:
2902 * (commit) D F (base_commit)
2903 * \ /
2904 * C E
2905 * \ /
2906 * B (yca)
2907 * |
2908 * A
2910 * 'got update' only handles linear cases:
2911 * Update forwards in time: A (base/yca) - B - C - D (commit)
2912 * Update backwards in time: D (base) - C - B - A (commit/yca)
2914 if (allow_forwards_in_time_only) {
2915 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2916 return got_error(GOT_ERR_ANCESTRY);
2917 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2918 got_object_id_cmp(base_commit_id, yca_id) != 0)
2919 return got_error(GOT_ERR_ANCESTRY);
2921 free(yca_id);
2922 return NULL;
2925 static const struct got_error *
2926 check_same_branch(struct got_object_id *commit_id,
2927 struct got_reference *head_ref, struct got_repository *repo)
2929 const struct got_error *err = NULL;
2930 struct got_commit_graph *graph = NULL;
2931 struct got_object_id *head_commit_id = NULL;
2933 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2934 if (err)
2935 goto done;
2937 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2938 goto done;
2940 err = got_commit_graph_open(&graph, "/", 1);
2941 if (err)
2942 goto done;
2944 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2945 check_cancelled, NULL);
2946 if (err)
2947 goto done;
2949 for (;;) {
2950 struct got_object_id id;
2952 err = got_commit_graph_iter_next(&id, graph, repo,
2953 check_cancelled, NULL);
2954 if (err) {
2955 if (err->code == GOT_ERR_ITER_COMPLETED)
2956 err = got_error(GOT_ERR_ANCESTRY);
2957 break;
2960 if (got_object_id_cmp(&id, commit_id) == 0)
2961 break;
2963 done:
2964 if (graph)
2965 got_commit_graph_close(graph);
2966 free(head_commit_id);
2967 return err;
2970 static const struct got_error *
2971 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2973 static char msg[512];
2974 const char *branch_name;
2976 if (got_ref_is_symbolic(ref))
2977 branch_name = got_ref_get_symref_target(ref);
2978 else
2979 branch_name = got_ref_get_name(ref);
2981 if (strncmp("refs/heads/", branch_name, 11) == 0)
2982 branch_name += 11;
2984 snprintf(msg, sizeof(msg),
2985 "target commit is not contained in branch '%s'; "
2986 "the branch to use must be specified with -b; "
2987 "if necessary a new branch can be created for "
2988 "this commit with 'got branch -c %s BRANCH_NAME'",
2989 branch_name, commit_id_str);
2991 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2994 static const struct got_error *
2995 cmd_checkout(int argc, char *argv[])
2997 const struct got_error *close_err, *error = NULL;
2998 struct got_repository *repo = NULL;
2999 struct got_reference *head_ref = NULL, *ref = NULL;
3000 struct got_worktree *worktree = NULL;
3001 char *repo_path = NULL;
3002 char *worktree_path = NULL;
3003 const char *path_prefix = "";
3004 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3005 char *commit_id_str = NULL, *keyword_idstr = NULL;
3006 struct got_object_id *commit_id = NULL;
3007 char *cwd = NULL;
3008 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3009 struct got_pathlist_head paths;
3010 struct got_checkout_progress_arg cpa;
3011 int *pack_fds = NULL;
3013 TAILQ_INIT(&paths);
3015 #ifndef PROFILE
3016 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3017 "unveil", NULL) == -1)
3018 err(1, "pledge");
3019 #endif
3021 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3022 switch (ch) {
3023 case 'b':
3024 branch_name = optarg;
3025 break;
3026 case 'c':
3027 commit_id_str = strdup(optarg);
3028 if (commit_id_str == NULL)
3029 return got_error_from_errno("strdup");
3030 break;
3031 case 'E':
3032 allow_nonempty = 1;
3033 break;
3034 case 'p':
3035 path_prefix = optarg;
3036 break;
3037 case 'q':
3038 verbosity = -1;
3039 break;
3040 default:
3041 usage_checkout();
3042 /* NOTREACHED */
3046 argc -= optind;
3047 argv += optind;
3049 if (argc == 1) {
3050 char *base, *dotgit;
3051 const char *path;
3052 repo_path = realpath(argv[0], NULL);
3053 if (repo_path == NULL)
3054 return got_error_from_errno2("realpath", argv[0]);
3055 cwd = getcwd(NULL, 0);
3056 if (cwd == NULL) {
3057 error = got_error_from_errno("getcwd");
3058 goto done;
3060 if (path_prefix[0])
3061 path = path_prefix;
3062 else
3063 path = repo_path;
3064 error = got_path_basename(&base, path);
3065 if (error)
3066 goto done;
3067 dotgit = strstr(base, ".git");
3068 if (dotgit)
3069 *dotgit = '\0';
3070 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3071 error = got_error_from_errno("asprintf");
3072 free(base);
3073 goto done;
3075 free(base);
3076 } else if (argc == 2) {
3077 repo_path = realpath(argv[0], NULL);
3078 if (repo_path == NULL) {
3079 error = got_error_from_errno2("realpath", argv[0]);
3080 goto done;
3082 worktree_path = realpath(argv[1], NULL);
3083 if (worktree_path == NULL) {
3084 if (errno != ENOENT) {
3085 error = got_error_from_errno2("realpath",
3086 argv[1]);
3087 goto done;
3089 worktree_path = strdup(argv[1]);
3090 if (worktree_path == NULL) {
3091 error = got_error_from_errno("strdup");
3092 goto done;
3095 } else
3096 usage_checkout();
3098 got_path_strip_trailing_slashes(repo_path);
3099 got_path_strip_trailing_slashes(worktree_path);
3101 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3102 got_path_is_child(repo_path, worktree_path,
3103 strlen(worktree_path))) {
3104 error = got_error_fmt(GOT_ERR_BAD_PATH,
3105 "work tree and repository paths may not overlap: %s",
3106 worktree_path);
3107 goto done;
3110 error = got_repo_pack_fds_open(&pack_fds);
3111 if (error != NULL)
3112 goto done;
3114 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3115 if (error != NULL)
3116 goto done;
3118 /* Pre-create work tree path for unveil(2) */
3119 error = got_path_mkdir(worktree_path);
3120 if (error) {
3121 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3122 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3123 goto done;
3124 if (!allow_nonempty &&
3125 !got_path_dir_is_empty(worktree_path)) {
3126 error = got_error_path(worktree_path,
3127 GOT_ERR_DIR_NOT_EMPTY);
3128 goto done;
3132 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3133 if (error)
3134 goto done;
3136 error = got_ref_open(&head_ref, repo, branch_name, 0);
3137 if (error != NULL)
3138 goto done;
3140 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3141 GOT_WORKTREE_GOT_DIR, repo);
3142 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3143 goto done;
3145 error = got_worktree_open(&worktree, worktree_path,
3146 GOT_WORKTREE_GOT_DIR);
3147 if (error != NULL)
3148 goto done;
3150 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3151 path_prefix);
3152 if (error != NULL)
3153 goto done;
3154 if (!same_path_prefix) {
3155 error = got_error(GOT_ERR_PATH_PREFIX);
3156 goto done;
3159 if (commit_id_str) {
3160 struct got_reflist_head refs;
3161 TAILQ_INIT(&refs);
3162 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3163 NULL);
3164 if (error)
3165 goto done;
3167 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3168 repo, worktree);
3169 if (error != NULL)
3170 goto done;
3171 if (keyword_idstr != NULL) {
3172 free(commit_id_str);
3173 commit_id_str = keyword_idstr;
3176 error = got_repo_match_object_id(&commit_id, NULL,
3177 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3178 got_ref_list_free(&refs);
3179 if (error)
3180 goto done;
3181 error = check_linear_ancestry(commit_id,
3182 got_worktree_get_base_commit_id(worktree), 0, repo);
3183 if (error != NULL) {
3184 if (error->code == GOT_ERR_ANCESTRY) {
3185 error = checkout_ancestry_error(
3186 head_ref, commit_id_str);
3188 goto done;
3190 error = check_same_branch(commit_id, head_ref, repo);
3191 if (error) {
3192 if (error->code == GOT_ERR_ANCESTRY) {
3193 error = checkout_ancestry_error(
3194 head_ref, commit_id_str);
3196 goto done;
3198 error = got_worktree_set_base_commit_id(worktree, repo,
3199 commit_id);
3200 if (error)
3201 goto done;
3202 /* Expand potentially abbreviated commit ID string. */
3203 free(commit_id_str);
3204 error = got_object_id_str(&commit_id_str, commit_id);
3205 if (error)
3206 goto done;
3207 } else {
3208 commit_id = got_object_id_dup(
3209 got_worktree_get_base_commit_id(worktree));
3210 if (commit_id == NULL) {
3211 error = got_error_from_errno("got_object_id_dup");
3212 goto done;
3214 error = got_object_id_str(&commit_id_str, commit_id);
3215 if (error)
3216 goto done;
3219 error = got_pathlist_append(&paths, "", NULL);
3220 if (error)
3221 goto done;
3222 cpa.worktree_path = worktree_path;
3223 cpa.had_base_commit_ref_error = 0;
3224 cpa.verbosity = verbosity;
3225 error = got_worktree_checkout_files(worktree, &paths, repo,
3226 checkout_progress, &cpa, check_cancelled, NULL);
3227 if (error != NULL)
3228 goto done;
3230 if (got_ref_is_symbolic(head_ref)) {
3231 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3232 if (error)
3233 goto done;
3234 refname = got_ref_get_name(ref);
3235 } else
3236 refname = got_ref_get_name(head_ref);
3237 printf("Checked out %s: %s\n", refname, commit_id_str);
3238 printf("Now shut up and hack\n");
3239 if (cpa.had_base_commit_ref_error)
3240 show_worktree_base_ref_warning();
3241 done:
3242 if (pack_fds) {
3243 const struct got_error *pack_err =
3244 got_repo_pack_fds_close(pack_fds);
3245 if (error == NULL)
3246 error = pack_err;
3248 if (head_ref)
3249 got_ref_close(head_ref);
3250 if (ref)
3251 got_ref_close(ref);
3252 if (repo) {
3253 close_err = got_repo_close(repo);
3254 if (error == NULL)
3255 error = close_err;
3257 if (worktree != NULL) {
3258 close_err = got_worktree_close(worktree);
3259 if (error == NULL)
3260 error = close_err;
3262 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3263 free(commit_id_str);
3264 free(commit_id);
3265 free(repo_path);
3266 free(worktree_path);
3267 free(cwd);
3268 return error;
3271 struct got_update_progress_arg {
3272 int did_something;
3273 int conflicts;
3274 int obstructed;
3275 int not_updated;
3276 int missing;
3277 int not_deleted;
3278 int unversioned;
3279 int verbosity;
3282 static void
3283 print_update_progress_stats(struct got_update_progress_arg *upa)
3285 if (!upa->did_something)
3286 return;
3288 if (upa->conflicts > 0)
3289 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3290 if (upa->obstructed > 0)
3291 printf("File paths obstructed by a non-regular file: %d\n",
3292 upa->obstructed);
3293 if (upa->not_updated > 0)
3294 printf("Files not updated because of existing merge "
3295 "conflicts: %d\n", upa->not_updated);
3299 * The meaning of some status codes differs between merge-style operations and
3300 * update operations. For example, the ! status code means "file was missing"
3301 * if changes were merged into the work tree, and "missing file was restored"
3302 * if the work tree was updated. This function should be used by any operation
3303 * which merges changes into the work tree without updating the work tree.
3305 static void
3306 print_merge_progress_stats(struct got_update_progress_arg *upa)
3308 if (!upa->did_something)
3309 return;
3311 if (upa->conflicts > 0)
3312 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3313 if (upa->obstructed > 0)
3314 printf("File paths obstructed by a non-regular file: %d\n",
3315 upa->obstructed);
3316 if (upa->missing > 0)
3317 printf("Files which had incoming changes but could not be "
3318 "found in the work tree: %d\n", upa->missing);
3319 if (upa->not_deleted > 0)
3320 printf("Files not deleted due to differences in deleted "
3321 "content: %d\n", upa->not_deleted);
3322 if (upa->unversioned > 0)
3323 printf("Files not merged because an unversioned file was "
3324 "found in the work tree: %d\n", upa->unversioned);
3327 __dead static void
3328 usage_update(void)
3330 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3331 "[path ...]\n", getprogname());
3332 exit(1);
3335 static const struct got_error *
3336 update_progress(void *arg, unsigned char status, const char *path)
3338 struct got_update_progress_arg *upa = arg;
3340 if (status == GOT_STATUS_EXISTS ||
3341 status == GOT_STATUS_BASE_REF_ERR)
3342 return NULL;
3344 upa->did_something = 1;
3346 /* Base commit bump happens silently. */
3347 if (status == GOT_STATUS_BUMP_BASE)
3348 return NULL;
3350 if (status == GOT_STATUS_CONFLICT)
3351 upa->conflicts++;
3352 if (status == GOT_STATUS_OBSTRUCTED)
3353 upa->obstructed++;
3354 if (status == GOT_STATUS_CANNOT_UPDATE)
3355 upa->not_updated++;
3356 if (status == GOT_STATUS_MISSING)
3357 upa->missing++;
3358 if (status == GOT_STATUS_CANNOT_DELETE)
3359 upa->not_deleted++;
3360 if (status == GOT_STATUS_UNVERSIONED)
3361 upa->unversioned++;
3363 while (path[0] == '/')
3364 path++;
3365 if (upa->verbosity >= 0)
3366 printf("%c %s\n", status, path);
3368 return NULL;
3371 static const struct got_error *
3372 switch_head_ref(struct got_reference *head_ref,
3373 struct got_object_id *commit_id, struct got_worktree *worktree,
3374 struct got_repository *repo)
3376 const struct got_error *err = NULL;
3377 char *base_id_str;
3378 int ref_has_moved = 0;
3380 /* Trivial case: switching between two different references. */
3381 if (strcmp(got_ref_get_name(head_ref),
3382 got_worktree_get_head_ref_name(worktree)) != 0) {
3383 printf("Switching work tree from %s to %s\n",
3384 got_worktree_get_head_ref_name(worktree),
3385 got_ref_get_name(head_ref));
3386 return got_worktree_set_head_ref(worktree, head_ref);
3389 err = check_linear_ancestry(commit_id,
3390 got_worktree_get_base_commit_id(worktree), 0, repo);
3391 if (err) {
3392 if (err->code != GOT_ERR_ANCESTRY)
3393 return err;
3394 ref_has_moved = 1;
3396 if (!ref_has_moved)
3397 return NULL;
3399 /* Switching to a rebased branch with the same reference name. */
3400 err = got_object_id_str(&base_id_str,
3401 got_worktree_get_base_commit_id(worktree));
3402 if (err)
3403 return err;
3404 printf("Reference %s now points at a different branch\n",
3405 got_worktree_get_head_ref_name(worktree));
3406 printf("Switching work tree from %s to %s\n", base_id_str,
3407 got_worktree_get_head_ref_name(worktree));
3408 return NULL;
3411 static const struct got_error *
3412 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3414 const struct got_error *err;
3415 int in_progress;
3417 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3418 if (err)
3419 return err;
3420 if (in_progress)
3421 return got_error(GOT_ERR_REBASING);
3423 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3424 if (err)
3425 return err;
3426 if (in_progress)
3427 return got_error(GOT_ERR_HISTEDIT_BUSY);
3429 return NULL;
3432 static const struct got_error *
3433 check_merge_in_progress(struct got_worktree *worktree,
3434 struct got_repository *repo)
3436 const struct got_error *err;
3437 int in_progress;
3439 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3440 if (err)
3441 return err;
3442 if (in_progress)
3443 return got_error(GOT_ERR_MERGE_BUSY);
3445 return NULL;
3448 static const struct got_error *
3449 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3450 char *argv[], struct got_worktree *worktree)
3452 const struct got_error *err = NULL;
3453 char *path;
3454 struct got_pathlist_entry *new;
3455 int i;
3457 if (argc == 0) {
3458 path = strdup("");
3459 if (path == NULL)
3460 return got_error_from_errno("strdup");
3461 return got_pathlist_append(paths, path, NULL);
3464 for (i = 0; i < argc; i++) {
3465 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3466 if (err)
3467 break;
3468 err = got_pathlist_insert(&new, paths, path, NULL);
3469 if (err || new == NULL /* duplicate */) {
3470 free(path);
3471 if (err)
3472 break;
3476 return err;
3479 static const struct got_error *
3480 wrap_not_worktree_error(const struct got_error *orig_err,
3481 const char *cmdname, const char *path)
3483 const struct got_error *err;
3484 struct got_repository *repo;
3485 static char msg[512];
3486 int *pack_fds = NULL;
3488 err = got_repo_pack_fds_open(&pack_fds);
3489 if (err)
3490 return err;
3492 err = got_repo_open(&repo, path, NULL, pack_fds);
3493 if (err)
3494 return orig_err;
3496 snprintf(msg, sizeof(msg),
3497 "'got %s' needs a work tree in addition to a git repository\n"
3498 "Work trees can be checked out from this Git repository with "
3499 "'got checkout'.\n"
3500 "The got(1) manual page contains more information.", cmdname);
3501 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3502 if (repo) {
3503 const struct got_error *close_err = got_repo_close(repo);
3504 if (err == NULL)
3505 err = close_err;
3507 if (pack_fds) {
3508 const struct got_error *pack_err =
3509 got_repo_pack_fds_close(pack_fds);
3510 if (err == NULL)
3511 err = pack_err;
3513 return err;
3516 static const struct got_error *
3517 cmd_update(int argc, char *argv[])
3519 const struct got_error *close_err, *error = NULL;
3520 struct got_repository *repo = NULL;
3521 struct got_worktree *worktree = NULL;
3522 char *worktree_path = NULL;
3523 struct got_object_id *commit_id = NULL;
3524 char *commit_id_str = NULL;
3525 const char *branch_name = NULL;
3526 struct got_reference *head_ref = NULL;
3527 struct got_pathlist_head paths;
3528 struct got_pathlist_entry *pe;
3529 int ch, verbosity = 0;
3530 struct got_update_progress_arg upa;
3531 int *pack_fds = NULL;
3533 TAILQ_INIT(&paths);
3535 #ifndef PROFILE
3536 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3537 "unveil", NULL) == -1)
3538 err(1, "pledge");
3539 #endif
3541 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3542 switch (ch) {
3543 case 'b':
3544 branch_name = optarg;
3545 break;
3546 case 'c':
3547 commit_id_str = strdup(optarg);
3548 if (commit_id_str == NULL)
3549 return got_error_from_errno("strdup");
3550 break;
3551 case 'q':
3552 verbosity = -1;
3553 break;
3554 default:
3555 usage_update();
3556 /* NOTREACHED */
3560 argc -= optind;
3561 argv += optind;
3563 worktree_path = getcwd(NULL, 0);
3564 if (worktree_path == NULL) {
3565 error = got_error_from_errno("getcwd");
3566 goto done;
3569 error = got_repo_pack_fds_open(&pack_fds);
3570 if (error != NULL)
3571 goto done;
3573 error = got_worktree_open(&worktree, worktree_path,
3574 GOT_WORKTREE_GOT_DIR);
3575 if (error) {
3576 if (error->code == GOT_ERR_NOT_WORKTREE)
3577 error = wrap_not_worktree_error(error, "update",
3578 worktree_path);
3579 goto done;
3582 error = check_rebase_or_histedit_in_progress(worktree);
3583 if (error)
3584 goto done;
3586 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3587 NULL, pack_fds);
3588 if (error != NULL)
3589 goto done;
3591 error = apply_unveil(got_repo_get_path(repo), 0,
3592 got_worktree_get_root_path(worktree));
3593 if (error)
3594 goto done;
3596 error = check_merge_in_progress(worktree, repo);
3597 if (error)
3598 goto done;
3600 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3601 if (error)
3602 goto done;
3604 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3605 got_worktree_get_head_ref_name(worktree), 0);
3606 if (error != NULL)
3607 goto done;
3608 if (commit_id_str == NULL) {
3609 error = got_ref_resolve(&commit_id, repo, head_ref);
3610 if (error != NULL)
3611 goto done;
3612 error = got_object_id_str(&commit_id_str, commit_id);
3613 if (error != NULL)
3614 goto done;
3615 } else {
3616 struct got_reflist_head refs;
3617 char *keyword_idstr = NULL;
3619 TAILQ_INIT(&refs);
3621 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3622 NULL);
3623 if (error)
3624 goto done;
3626 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3627 repo, worktree);
3628 if (error != NULL)
3629 goto done;
3630 if (keyword_idstr != NULL) {
3631 free(commit_id_str);
3632 commit_id_str = keyword_idstr;
3635 error = got_repo_match_object_id(&commit_id, NULL,
3636 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3637 got_ref_list_free(&refs);
3638 free(commit_id_str);
3639 commit_id_str = NULL;
3640 if (error)
3641 goto done;
3642 error = got_object_id_str(&commit_id_str, commit_id);
3643 if (error)
3644 goto done;
3647 if (branch_name) {
3648 struct got_object_id *head_commit_id;
3649 TAILQ_FOREACH(pe, &paths, entry) {
3650 if (pe->path_len == 0)
3651 continue;
3652 error = got_error_msg(GOT_ERR_BAD_PATH,
3653 "switching between branches requires that "
3654 "the entire work tree gets updated");
3655 goto done;
3657 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3658 if (error)
3659 goto done;
3660 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3661 repo);
3662 free(head_commit_id);
3663 if (error != NULL)
3664 goto done;
3665 error = check_same_branch(commit_id, head_ref, repo);
3666 if (error)
3667 goto done;
3668 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3669 if (error)
3670 goto done;
3671 } else {
3672 error = check_linear_ancestry(commit_id,
3673 got_worktree_get_base_commit_id(worktree), 0, repo);
3674 if (error != NULL) {
3675 if (error->code == GOT_ERR_ANCESTRY)
3676 error = got_error(GOT_ERR_BRANCH_MOVED);
3677 goto done;
3679 error = check_same_branch(commit_id, head_ref, repo);
3680 if (error)
3681 goto done;
3684 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3685 commit_id) != 0) {
3686 error = got_worktree_set_base_commit_id(worktree, repo,
3687 commit_id);
3688 if (error)
3689 goto done;
3692 memset(&upa, 0, sizeof(upa));
3693 upa.verbosity = verbosity;
3694 error = got_worktree_checkout_files(worktree, &paths, repo,
3695 update_progress, &upa, check_cancelled, NULL);
3696 if (error != NULL)
3697 goto done;
3699 if (upa.did_something) {
3700 printf("Updated to %s: %s\n",
3701 got_worktree_get_head_ref_name(worktree), commit_id_str);
3702 } else
3703 printf("Already up-to-date\n");
3705 print_update_progress_stats(&upa);
3706 done:
3707 if (pack_fds) {
3708 const struct got_error *pack_err =
3709 got_repo_pack_fds_close(pack_fds);
3710 if (error == NULL)
3711 error = pack_err;
3713 if (repo) {
3714 close_err = got_repo_close(repo);
3715 if (error == NULL)
3716 error = close_err;
3718 if (worktree != NULL) {
3719 close_err = got_worktree_close(worktree);
3720 if (error == NULL)
3721 error = close_err;
3723 if (head_ref != NULL)
3724 got_ref_close(head_ref);
3725 free(worktree_path);
3726 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3727 free(commit_id);
3728 free(commit_id_str);
3729 return error;
3732 static const struct got_error *
3733 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3734 const char *path, int diff_context, int ignore_whitespace,
3735 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3736 struct got_repository *repo, FILE *outfile)
3738 const struct got_error *err = NULL;
3739 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3740 FILE *f1 = NULL, *f2 = NULL;
3741 int fd1 = -1, fd2 = -1;
3743 fd1 = got_opentempfd();
3744 if (fd1 == -1)
3745 return got_error_from_errno("got_opentempfd");
3746 fd2 = got_opentempfd();
3747 if (fd2 == -1) {
3748 err = got_error_from_errno("got_opentempfd");
3749 goto done;
3752 if (blob_id1) {
3753 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3754 fd1);
3755 if (err)
3756 goto done;
3759 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3760 if (err)
3761 goto done;
3763 f1 = got_opentemp();
3764 if (f1 == NULL) {
3765 err = got_error_from_errno("got_opentemp");
3766 goto done;
3768 f2 = got_opentemp();
3769 if (f2 == NULL) {
3770 err = got_error_from_errno("got_opentemp");
3771 goto done;
3774 while (path[0] == '/')
3775 path++;
3776 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3777 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3778 force_text_diff, dsa, outfile);
3779 done:
3780 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3781 err = got_error_from_errno("close");
3782 if (blob1)
3783 got_object_blob_close(blob1);
3784 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3785 err = got_error_from_errno("close");
3786 if (blob2)
3787 got_object_blob_close(blob2);
3788 if (f1 && fclose(f1) == EOF && err == NULL)
3789 err = got_error_from_errno("fclose");
3790 if (f2 && fclose(f2) == EOF && err == NULL)
3791 err = got_error_from_errno("fclose");
3792 return err;
3795 static const struct got_error *
3796 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3797 const char *path, int diff_context, int ignore_whitespace,
3798 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3799 struct got_repository *repo, FILE *outfile)
3801 const struct got_error *err = NULL;
3802 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3803 struct got_diff_blob_output_unidiff_arg arg;
3804 FILE *f1 = NULL, *f2 = NULL;
3805 int fd1 = -1, fd2 = -1;
3807 if (tree_id1) {
3808 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3809 if (err)
3810 goto done;
3811 fd1 = got_opentempfd();
3812 if (fd1 == -1) {
3813 err = got_error_from_errno("got_opentempfd");
3814 goto done;
3818 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3819 if (err)
3820 goto done;
3822 f1 = got_opentemp();
3823 if (f1 == NULL) {
3824 err = got_error_from_errno("got_opentemp");
3825 goto done;
3828 f2 = got_opentemp();
3829 if (f2 == NULL) {
3830 err = got_error_from_errno("got_opentemp");
3831 goto done;
3833 fd2 = got_opentempfd();
3834 if (fd2 == -1) {
3835 err = got_error_from_errno("got_opentempfd");
3836 goto done;
3838 arg.diff_context = diff_context;
3839 arg.ignore_whitespace = ignore_whitespace;
3840 arg.force_text_diff = force_text_diff;
3841 arg.diffstat = dsa;
3842 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3843 arg.outfile = outfile;
3844 arg.lines = NULL;
3845 arg.nlines = 0;
3846 while (path[0] == '/')
3847 path++;
3848 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3849 got_diff_blob_output_unidiff, &arg, 1);
3850 done:
3851 if (tree1)
3852 got_object_tree_close(tree1);
3853 if (tree2)
3854 got_object_tree_close(tree2);
3855 if (f1 && fclose(f1) == EOF && err == NULL)
3856 err = got_error_from_errno("fclose");
3857 if (f2 && fclose(f2) == EOF && err == NULL)
3858 err = got_error_from_errno("fclose");
3859 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3860 err = got_error_from_errno("close");
3861 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3862 err = got_error_from_errno("close");
3863 return err;
3866 static const struct got_error *
3867 get_changed_paths(struct got_pathlist_head *paths,
3868 struct got_commit_object *commit, struct got_repository *repo,
3869 struct got_diffstat_cb_arg *dsa)
3871 const struct got_error *err = NULL;
3872 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3873 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3874 struct got_object_qid *qid;
3875 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3876 FILE *f1 = NULL, *f2 = NULL;
3877 int fd1 = -1, fd2 = -1;
3879 if (dsa) {
3880 cb = got_diff_tree_compute_diffstat;
3882 f1 = got_opentemp();
3883 if (f1 == NULL) {
3884 err = got_error_from_errno("got_opentemp");
3885 goto done;
3887 f2 = got_opentemp();
3888 if (f2 == NULL) {
3889 err = got_error_from_errno("got_opentemp");
3890 goto done;
3892 fd1 = got_opentempfd();
3893 if (fd1 == -1) {
3894 err = got_error_from_errno("got_opentempfd");
3895 goto done;
3897 fd2 = got_opentempfd();
3898 if (fd2 == -1) {
3899 err = got_error_from_errno("got_opentempfd");
3900 goto done;
3904 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3905 if (qid != NULL) {
3906 struct got_commit_object *pcommit;
3907 err = got_object_open_as_commit(&pcommit, repo,
3908 &qid->id);
3909 if (err)
3910 return err;
3912 tree_id1 = got_object_id_dup(
3913 got_object_commit_get_tree_id(pcommit));
3914 if (tree_id1 == NULL) {
3915 got_object_commit_close(pcommit);
3916 return got_error_from_errno("got_object_id_dup");
3918 got_object_commit_close(pcommit);
3922 if (tree_id1) {
3923 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3924 if (err)
3925 goto done;
3928 tree_id2 = got_object_commit_get_tree_id(commit);
3929 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3930 if (err)
3931 goto done;
3933 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3934 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3935 done:
3936 if (tree1)
3937 got_object_tree_close(tree1);
3938 if (tree2)
3939 got_object_tree_close(tree2);
3940 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3941 err = got_error_from_errno("close");
3942 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3943 err = got_error_from_errno("close");
3944 if (f1 && fclose(f1) == EOF && err == NULL)
3945 err = got_error_from_errno("fclose");
3946 if (f2 && fclose(f2) == EOF && err == NULL)
3947 err = got_error_from_errno("fclose");
3948 free(tree_id1);
3949 return err;
3952 static const struct got_error *
3953 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3954 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3955 struct got_repository *repo, FILE *outfile)
3957 const struct got_error *err = NULL;
3958 struct got_commit_object *pcommit = NULL;
3959 char *id_str1 = NULL, *id_str2 = NULL;
3960 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3961 struct got_object_qid *qid;
3963 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3964 if (qid != NULL) {
3965 err = got_object_open_as_commit(&pcommit, repo,
3966 &qid->id);
3967 if (err)
3968 return err;
3969 err = got_object_id_str(&id_str1, &qid->id);
3970 if (err)
3971 goto done;
3974 err = got_object_id_str(&id_str2, id);
3975 if (err)
3976 goto done;
3978 if (path && path[0] != '\0') {
3979 int obj_type;
3980 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3981 if (err)
3982 goto done;
3983 if (pcommit) {
3984 err = got_object_id_by_path(&obj_id1, repo,
3985 pcommit, path);
3986 if (err) {
3987 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3988 free(obj_id2);
3989 goto done;
3993 err = got_object_get_type(&obj_type, repo, obj_id2);
3994 if (err) {
3995 free(obj_id2);
3996 goto done;
3998 fprintf(outfile,
3999 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4000 fprintf(outfile, "commit - %s\n",
4001 id_str1 ? id_str1 : "/dev/null");
4002 fprintf(outfile, "commit + %s\n", id_str2);
4003 switch (obj_type) {
4004 case GOT_OBJ_TYPE_BLOB:
4005 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4006 0, 0, dsa, repo, outfile);
4007 break;
4008 case GOT_OBJ_TYPE_TREE:
4009 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4010 0, 0, dsa, repo, outfile);
4011 break;
4012 default:
4013 err = got_error(GOT_ERR_OBJ_TYPE);
4014 break;
4016 free(obj_id1);
4017 free(obj_id2);
4018 } else {
4019 obj_id2 = got_object_commit_get_tree_id(commit);
4020 if (pcommit)
4021 obj_id1 = got_object_commit_get_tree_id(pcommit);
4022 fprintf(outfile,
4023 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4024 fprintf(outfile, "commit - %s\n",
4025 id_str1 ? id_str1 : "/dev/null");
4026 fprintf(outfile, "commit + %s\n", id_str2);
4027 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4028 dsa, repo, outfile);
4030 done:
4031 free(id_str1);
4032 free(id_str2);
4033 if (pcommit)
4034 got_object_commit_close(pcommit);
4035 return err;
4038 static char *
4039 get_datestr(time_t *time, char *datebuf)
4041 struct tm mytm, *tm;
4042 char *p, *s;
4044 tm = gmtime_r(time, &mytm);
4045 if (tm == NULL)
4046 return NULL;
4047 s = asctime_r(tm, datebuf);
4048 if (s == NULL)
4049 return NULL;
4050 p = strchr(s, '\n');
4051 if (p)
4052 *p = '\0';
4053 return s;
4056 static const struct got_error *
4057 match_commit(int *have_match, struct got_object_id *id,
4058 struct got_commit_object *commit, regex_t *regex)
4060 const struct got_error *err = NULL;
4061 regmatch_t regmatch;
4062 char *id_str = NULL, *logmsg = NULL;
4064 *have_match = 0;
4066 err = got_object_id_str(&id_str, id);
4067 if (err)
4068 return err;
4070 err = got_object_commit_get_logmsg(&logmsg, commit);
4071 if (err)
4072 goto done;
4074 if (regexec(regex, got_object_commit_get_author(commit), 1,
4075 &regmatch, 0) == 0 ||
4076 regexec(regex, got_object_commit_get_committer(commit), 1,
4077 &regmatch, 0) == 0 ||
4078 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4079 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4080 *have_match = 1;
4081 done:
4082 free(id_str);
4083 free(logmsg);
4084 return err;
4087 static void
4088 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4089 regex_t *regex)
4091 regmatch_t regmatch;
4092 struct got_pathlist_entry *pe;
4094 *have_match = 0;
4096 TAILQ_FOREACH(pe, changed_paths, entry) {
4097 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4098 *have_match = 1;
4099 break;
4104 static const struct got_error *
4105 match_patch(int *have_match, struct got_commit_object *commit,
4106 struct got_object_id *id, const char *path, int diff_context,
4107 struct got_repository *repo, regex_t *regex, FILE *f)
4109 const struct got_error *err = NULL;
4110 char *line = NULL;
4111 size_t linesize = 0;
4112 regmatch_t regmatch;
4114 *have_match = 0;
4116 err = got_opentemp_truncate(f);
4117 if (err)
4118 return err;
4120 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4121 if (err)
4122 goto done;
4124 if (fseeko(f, 0L, SEEK_SET) == -1) {
4125 err = got_error_from_errno("fseeko");
4126 goto done;
4129 while (getline(&line, &linesize, f) != -1) {
4130 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4131 *have_match = 1;
4132 break;
4135 done:
4136 free(line);
4137 return err;
4140 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4142 static const struct got_error*
4143 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4144 struct got_object_id *id, struct got_repository *repo,
4145 int local_only)
4147 static const struct got_error *err = NULL;
4148 struct got_reflist_entry *re;
4149 char *s;
4150 const char *name;
4152 *refs_str = NULL;
4154 TAILQ_FOREACH(re, refs, entry) {
4155 struct got_tag_object *tag = NULL;
4156 struct got_object_id *ref_id;
4157 int cmp;
4159 name = got_ref_get_name(re->ref);
4160 if (strcmp(name, GOT_REF_HEAD) == 0)
4161 continue;
4162 if (strncmp(name, "refs/", 5) == 0)
4163 name += 5;
4164 if (strncmp(name, "got/", 4) == 0)
4165 continue;
4166 if (strncmp(name, "heads/", 6) == 0)
4167 name += 6;
4168 if (strncmp(name, "remotes/", 8) == 0) {
4169 if (local_only)
4170 continue;
4171 name += 8;
4172 s = strstr(name, "/" GOT_REF_HEAD);
4173 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4174 continue;
4176 err = got_ref_resolve(&ref_id, repo, re->ref);
4177 if (err)
4178 break;
4179 if (strncmp(name, "tags/", 5) == 0) {
4180 err = got_object_open_as_tag(&tag, repo, ref_id);
4181 if (err) {
4182 if (err->code != GOT_ERR_OBJ_TYPE) {
4183 free(ref_id);
4184 break;
4186 /* Ref points at something other than a tag. */
4187 err = NULL;
4188 tag = NULL;
4191 cmp = got_object_id_cmp(tag ?
4192 got_object_tag_get_object_id(tag) : ref_id, id);
4193 free(ref_id);
4194 if (tag)
4195 got_object_tag_close(tag);
4196 if (cmp != 0)
4197 continue;
4198 s = *refs_str;
4199 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4200 s ? ", " : "", name) == -1) {
4201 err = got_error_from_errno("asprintf");
4202 free(s);
4203 *refs_str = NULL;
4204 break;
4206 free(s);
4209 return err;
4212 static const struct got_error *
4213 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4214 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4216 const struct got_error *err = NULL;
4217 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4218 char *comma, *s, *nl;
4219 struct got_reflist_head *refs;
4220 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4221 struct tm tm;
4222 time_t committer_time;
4224 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4225 if (refs) {
4226 err = build_refs_str(&ref_str, refs, id, repo, 1);
4227 if (err)
4228 return err;
4230 /* Display the first matching ref only. */
4231 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4232 *comma = '\0';
4235 if (ref_str == NULL) {
4236 err = got_object_id_str(&id_str, id);
4237 if (err)
4238 return err;
4241 committer_time = got_object_commit_get_committer_time(commit);
4242 if (gmtime_r(&committer_time, &tm) == NULL) {
4243 err = got_error_from_errno("gmtime_r");
4244 goto done;
4246 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4247 err = got_error(GOT_ERR_NO_SPACE);
4248 goto done;
4251 err = got_object_commit_get_logmsg(&logmsg0, commit);
4252 if (err)
4253 goto done;
4255 s = logmsg0;
4256 while (isspace((unsigned char)s[0]))
4257 s++;
4259 nl = strchr(s, '\n');
4260 if (nl) {
4261 *nl = '\0';
4264 if (ref_str)
4265 printf("%s%-7s %s\n", datebuf, ref_str, s);
4266 else
4267 printf("%s%.7s %s\n", datebuf, id_str, s);
4269 if (fflush(stdout) != 0 && err == NULL)
4270 err = got_error_from_errno("fflush");
4271 done:
4272 free(id_str);
4273 free(ref_str);
4274 free(logmsg0);
4275 return err;
4278 static const struct got_error *
4279 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4281 struct got_pathlist_entry *pe;
4283 if (header != NULL)
4284 printf("%s\n", header);
4286 TAILQ_FOREACH(pe, dsa->paths, entry) {
4287 struct got_diff_changed_path *cp = pe->data;
4288 int pad = dsa->max_path_len - pe->path_len + 1;
4290 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4291 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4293 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4294 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4295 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4297 if (fflush(stdout) != 0)
4298 return got_error_from_errno("fflush");
4300 return NULL;
4303 static const struct got_error *
4304 printfile(FILE *f)
4306 char buf[8192];
4307 size_t r;
4309 if (fseeko(f, 0L, SEEK_SET) == -1)
4310 return got_error_from_errno("fseek");
4312 for (;;) {
4313 r = fread(buf, 1, sizeof(buf), f);
4314 if (r == 0) {
4315 if (ferror(f))
4316 return got_error_from_errno("fread");
4317 if (feof(f))
4318 break;
4320 if (fwrite(buf, 1, r, stdout) != r)
4321 return got_ferror(stdout, GOT_ERR_IO);
4324 return NULL;
4327 static const struct got_error *
4328 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4329 struct got_repository *repo, const char *path,
4330 struct got_pathlist_head *changed_paths,
4331 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4332 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4333 const char *prefix)
4335 const struct got_error *err = NULL;
4336 FILE *f = NULL;
4337 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4338 char datebuf[26];
4339 time_t committer_time;
4340 const char *author, *committer;
4341 char *refs_str = NULL;
4343 err = got_object_id_str(&id_str, id);
4344 if (err)
4345 return err;
4347 if (custom_refs_str == NULL) {
4348 struct got_reflist_head *refs;
4349 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4350 if (refs) {
4351 err = build_refs_str(&refs_str, refs, id, repo, 0);
4352 if (err)
4353 goto done;
4357 printf(GOT_COMMIT_SEP_STR);
4358 if (custom_refs_str)
4359 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4360 custom_refs_str);
4361 else
4362 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4363 refs_str ? " (" : "", refs_str ? refs_str : "",
4364 refs_str ? ")" : "");
4365 free(id_str);
4366 id_str = NULL;
4367 free(refs_str);
4368 refs_str = NULL;
4369 printf("from: %s\n", got_object_commit_get_author(commit));
4370 author = got_object_commit_get_author(commit);
4371 committer = got_object_commit_get_committer(commit);
4372 if (strcmp(author, committer) != 0)
4373 printf("via: %s\n", committer);
4374 committer_time = got_object_commit_get_committer_time(commit);
4375 datestr = get_datestr(&committer_time, datebuf);
4376 if (datestr)
4377 printf("date: %s UTC\n", datestr);
4378 if (got_object_commit_get_nparents(commit) > 1) {
4379 const struct got_object_id_queue *parent_ids;
4380 struct got_object_qid *qid;
4381 int n = 1;
4382 parent_ids = got_object_commit_get_parent_ids(commit);
4383 STAILQ_FOREACH(qid, parent_ids, entry) {
4384 err = got_object_id_str(&id_str, &qid->id);
4385 if (err)
4386 goto done;
4387 printf("parent %d: %s\n", n++, id_str);
4388 free(id_str);
4389 id_str = NULL;
4393 err = got_object_commit_get_logmsg(&logmsg0, commit);
4394 if (err)
4395 goto done;
4397 logmsg = logmsg0;
4398 do {
4399 line = strsep(&logmsg, "\n");
4400 if (line)
4401 printf(" %s\n", line);
4402 } while (line);
4403 free(logmsg0);
4405 if (changed_paths && diffstat == NULL) {
4406 struct got_pathlist_entry *pe;
4408 TAILQ_FOREACH(pe, changed_paths, entry) {
4409 struct got_diff_changed_path *cp = pe->data;
4411 printf(" %c %s\n", cp->status, pe->path);
4413 printf("\n");
4415 if (show_patch) {
4416 if (diffstat) {
4417 f = got_opentemp();
4418 if (f == NULL) {
4419 err = got_error_from_errno("got_opentemp");
4420 goto done;
4424 err = print_patch(commit, id, path, diff_context, diffstat,
4425 repo, diffstat == NULL ? stdout : f);
4426 if (err)
4427 goto done;
4429 if (diffstat) {
4430 err = print_diffstat(diffstat, NULL);
4431 if (err)
4432 goto done;
4433 if (show_patch) {
4434 err = printfile(f);
4435 if (err)
4436 goto done;
4439 if (show_patch)
4440 printf("\n");
4442 if (fflush(stdout) != 0 && err == NULL)
4443 err = got_error_from_errno("fflush");
4444 done:
4445 if (f && fclose(f) == EOF && err == NULL)
4446 err = got_error_from_errno("fclose");
4447 free(id_str);
4448 free(refs_str);
4449 return err;
4452 static const struct got_error *
4453 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4454 struct got_repository *repo, const char *path, int show_changed_paths,
4455 int show_diffstat, int show_patch, const char *search_pattern,
4456 int diff_context, int limit, int log_branches, int reverse_display_order,
4457 struct got_reflist_object_id_map *refs_idmap, int one_line,
4458 FILE *tmpfile)
4460 const struct got_error *err;
4461 struct got_commit_graph *graph;
4462 regex_t regex;
4463 int have_match;
4464 struct got_object_id_queue reversed_commits;
4465 struct got_object_qid *qid;
4466 struct got_commit_object *commit;
4467 struct got_pathlist_head changed_paths;
4469 STAILQ_INIT(&reversed_commits);
4470 TAILQ_INIT(&changed_paths);
4472 if (search_pattern && regcomp(&regex, search_pattern,
4473 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4474 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4476 err = got_commit_graph_open(&graph, path, !log_branches);
4477 if (err)
4478 return err;
4479 err = got_commit_graph_iter_start(graph, root_id, repo,
4480 check_cancelled, NULL);
4481 if (err)
4482 goto done;
4483 for (;;) {
4484 struct got_object_id id;
4485 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4486 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4488 if (sigint_received || sigpipe_received)
4489 break;
4491 err = got_commit_graph_iter_next(&id, graph, repo,
4492 check_cancelled, NULL);
4493 if (err) {
4494 if (err->code == GOT_ERR_ITER_COMPLETED)
4495 err = NULL;
4496 break;
4499 err = got_object_open_as_commit(&commit, repo, &id);
4500 if (err)
4501 break;
4503 if (((show_changed_paths && !show_diffstat) ||
4504 (show_diffstat && !show_patch))
4505 && !reverse_display_order) {
4506 err = get_changed_paths(&changed_paths, commit, repo,
4507 show_diffstat ? &dsa : NULL);
4508 if (err)
4509 break;
4512 if (search_pattern) {
4513 err = match_commit(&have_match, &id, commit, &regex);
4514 if (err) {
4515 got_object_commit_close(commit);
4516 break;
4518 if (have_match == 0 && show_changed_paths)
4519 match_changed_paths(&have_match,
4520 &changed_paths, &regex);
4521 if (have_match == 0 && show_patch) {
4522 err = match_patch(&have_match, commit, &id,
4523 path, diff_context, repo, &regex, tmpfile);
4524 if (err)
4525 break;
4527 if (have_match == 0) {
4528 got_object_commit_close(commit);
4529 got_pathlist_free(&changed_paths,
4530 GOT_PATHLIST_FREE_ALL);
4531 continue;
4535 if (reverse_display_order) {
4536 err = got_object_qid_alloc(&qid, &id);
4537 if (err)
4538 break;
4539 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4540 got_object_commit_close(commit);
4541 } else {
4542 if (one_line)
4543 err = print_commit_oneline(commit, &id,
4544 repo, refs_idmap);
4545 else
4546 err = print_commit(commit, &id, repo, path,
4547 (show_changed_paths || show_diffstat) ?
4548 &changed_paths : NULL,
4549 show_diffstat ? &dsa : NULL, show_patch,
4550 diff_context, refs_idmap, NULL, NULL);
4551 got_object_commit_close(commit);
4552 if (err)
4553 break;
4555 if ((limit && --limit == 0) ||
4556 (end_id && got_object_id_cmp(&id, end_id) == 0))
4557 break;
4559 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4561 if (reverse_display_order) {
4562 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4563 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4564 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4566 err = got_object_open_as_commit(&commit, repo,
4567 &qid->id);
4568 if (err)
4569 break;
4570 if ((show_changed_paths && !show_diffstat) ||
4571 (show_diffstat && !show_patch)) {
4572 err = get_changed_paths(&changed_paths, commit,
4573 repo, show_diffstat ? &dsa : NULL);
4574 if (err)
4575 break;
4577 if (one_line)
4578 err = print_commit_oneline(commit, &qid->id,
4579 repo, refs_idmap);
4580 else
4581 err = print_commit(commit, &qid->id, repo, path,
4582 (show_changed_paths || show_diffstat) ?
4583 &changed_paths : NULL,
4584 show_diffstat ? &dsa : NULL, show_patch,
4585 diff_context, refs_idmap, NULL, NULL);
4586 got_object_commit_close(commit);
4587 if (err)
4588 break;
4589 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4592 done:
4593 while (!STAILQ_EMPTY(&reversed_commits)) {
4594 qid = STAILQ_FIRST(&reversed_commits);
4595 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4596 got_object_qid_free(qid);
4598 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4599 if (search_pattern)
4600 regfree(&regex);
4601 got_commit_graph_close(graph);
4602 return err;
4605 __dead static void
4606 usage_log(void)
4608 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4609 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4610 "[path]\n", getprogname());
4611 exit(1);
4614 static int
4615 get_default_log_limit(void)
4617 const char *got_default_log_limit;
4618 long long n;
4619 const char *errstr;
4621 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4622 if (got_default_log_limit == NULL)
4623 return 0;
4624 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4625 if (errstr != NULL)
4626 return 0;
4627 return n;
4630 static const struct got_error *
4631 cmd_log(int argc, char *argv[])
4633 const struct got_error *error;
4634 struct got_repository *repo = NULL;
4635 struct got_worktree *worktree = NULL;
4636 struct got_object_id *start_id = NULL, *end_id = NULL;
4637 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4638 char *keyword_idstr = NULL;
4639 const char *start_commit = NULL, *end_commit = NULL;
4640 const char *search_pattern = NULL;
4641 int diff_context = -1, ch;
4642 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4643 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4644 const char *errstr;
4645 struct got_reflist_head refs;
4646 struct got_reflist_object_id_map *refs_idmap = NULL;
4647 FILE *tmpfile = NULL;
4648 int *pack_fds = NULL;
4650 TAILQ_INIT(&refs);
4652 #ifndef PROFILE
4653 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4654 NULL)
4655 == -1)
4656 err(1, "pledge");
4657 #endif
4659 limit = get_default_log_limit();
4661 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4662 switch (ch) {
4663 case 'b':
4664 log_branches = 1;
4665 break;
4666 case 'C':
4667 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4668 &errstr);
4669 if (errstr != NULL)
4670 errx(1, "number of context lines is %s: %s",
4671 errstr, optarg);
4672 break;
4673 case 'c':
4674 start_commit = optarg;
4675 break;
4676 case 'd':
4677 show_diffstat = 1;
4678 break;
4679 case 'l':
4680 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4681 if (errstr != NULL)
4682 errx(1, "number of commits is %s: %s",
4683 errstr, optarg);
4684 break;
4685 case 'P':
4686 show_changed_paths = 1;
4687 break;
4688 case 'p':
4689 show_patch = 1;
4690 break;
4691 case 'R':
4692 reverse_display_order = 1;
4693 break;
4694 case 'r':
4695 repo_path = realpath(optarg, NULL);
4696 if (repo_path == NULL)
4697 return got_error_from_errno2("realpath",
4698 optarg);
4699 got_path_strip_trailing_slashes(repo_path);
4700 break;
4701 case 'S':
4702 search_pattern = optarg;
4703 break;
4704 case 's':
4705 one_line = 1;
4706 break;
4707 case 'x':
4708 end_commit = optarg;
4709 break;
4710 default:
4711 usage_log();
4712 /* NOTREACHED */
4716 argc -= optind;
4717 argv += optind;
4719 if (diff_context == -1)
4720 diff_context = 3;
4721 else if (!show_patch)
4722 errx(1, "-C requires -p");
4724 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4725 errx(1, "cannot use -s with -d, -p or -P");
4727 cwd = getcwd(NULL, 0);
4728 if (cwd == NULL) {
4729 error = got_error_from_errno("getcwd");
4730 goto done;
4733 error = got_repo_pack_fds_open(&pack_fds);
4734 if (error != NULL)
4735 goto done;
4737 if (repo_path == NULL) {
4738 error = got_worktree_open(&worktree, cwd,
4739 GOT_WORKTREE_GOT_DIR);
4740 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4741 goto done;
4742 error = NULL;
4745 if (argc == 1) {
4746 if (worktree) {
4747 error = got_worktree_resolve_path(&path, worktree,
4748 argv[0]);
4749 if (error)
4750 goto done;
4751 } else {
4752 path = strdup(argv[0]);
4753 if (path == NULL) {
4754 error = got_error_from_errno("strdup");
4755 goto done;
4758 } else if (argc != 0)
4759 usage_log();
4761 if (repo_path == NULL) {
4762 repo_path = worktree ?
4763 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4765 if (repo_path == NULL) {
4766 error = got_error_from_errno("strdup");
4767 goto done;
4770 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4771 if (error != NULL)
4772 goto done;
4774 error = apply_unveil(got_repo_get_path(repo), 1,
4775 worktree ? got_worktree_get_root_path(worktree) : NULL);
4776 if (error)
4777 goto done;
4779 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4780 if (error)
4781 goto done;
4783 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4784 if (error)
4785 goto done;
4787 if (start_commit == NULL) {
4788 struct got_reference *head_ref;
4789 struct got_commit_object *commit = NULL;
4790 error = got_ref_open(&head_ref, repo,
4791 worktree ? got_worktree_get_head_ref_name(worktree)
4792 : GOT_REF_HEAD, 0);
4793 if (error != NULL)
4794 goto done;
4795 error = got_ref_resolve(&start_id, repo, head_ref);
4796 got_ref_close(head_ref);
4797 if (error != NULL)
4798 goto done;
4799 error = got_object_open_as_commit(&commit, repo,
4800 start_id);
4801 if (error != NULL)
4802 goto done;
4803 got_object_commit_close(commit);
4804 } else {
4805 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4806 repo, worktree);
4807 if (error != NULL)
4808 goto done;
4809 if (keyword_idstr != NULL)
4810 start_commit = keyword_idstr;
4812 error = got_repo_match_object_id(&start_id, NULL,
4813 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4814 if (error != NULL)
4815 goto done;
4817 if (end_commit != NULL) {
4818 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4819 repo, worktree);
4820 if (error != NULL)
4821 goto done;
4822 if (keyword_idstr != NULL)
4823 end_commit = keyword_idstr;
4825 error = got_repo_match_object_id(&end_id, NULL,
4826 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4827 if (error != NULL)
4828 goto done;
4831 if (worktree) {
4833 * If a path was specified on the command line it was resolved
4834 * to a path in the work tree above. Prepend the work tree's
4835 * path prefix to obtain the corresponding in-repository path.
4837 if (path) {
4838 const char *prefix;
4839 prefix = got_worktree_get_path_prefix(worktree);
4840 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4841 (path[0] != '\0') ? "/" : "", path) == -1) {
4842 error = got_error_from_errno("asprintf");
4843 goto done;
4846 } else
4847 error = got_repo_map_path(&in_repo_path, repo,
4848 path ? path : "");
4849 if (error != NULL)
4850 goto done;
4851 if (in_repo_path) {
4852 free(path);
4853 path = in_repo_path;
4856 if (worktree) {
4857 /* Release work tree lock. */
4858 got_worktree_close(worktree);
4859 worktree = NULL;
4862 if (search_pattern && show_patch) {
4863 tmpfile = got_opentemp();
4864 if (tmpfile == NULL) {
4865 error = got_error_from_errno("got_opentemp");
4866 goto done;
4870 error = print_commits(start_id, end_id, repo, path ? path : "",
4871 show_changed_paths, show_diffstat, show_patch, search_pattern,
4872 diff_context, limit, log_branches, reverse_display_order,
4873 refs_idmap, one_line, tmpfile);
4874 done:
4875 free(path);
4876 free(repo_path);
4877 free(cwd);
4878 free(start_id);
4879 free(end_id);
4880 free(keyword_idstr);
4881 if (worktree)
4882 got_worktree_close(worktree);
4883 if (repo) {
4884 const struct got_error *close_err = got_repo_close(repo);
4885 if (error == NULL)
4886 error = close_err;
4888 if (pack_fds) {
4889 const struct got_error *pack_err =
4890 got_repo_pack_fds_close(pack_fds);
4891 if (error == NULL)
4892 error = pack_err;
4894 if (refs_idmap)
4895 got_reflist_object_id_map_free(refs_idmap);
4896 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4897 error = got_error_from_errno("fclose");
4898 got_ref_list_free(&refs);
4899 return error;
4902 __dead static void
4903 usage_diff(void)
4905 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4906 "[-r repository-path] [object1 object2 | path ...]\n",
4907 getprogname());
4908 exit(1);
4911 struct print_diff_arg {
4912 struct got_repository *repo;
4913 struct got_worktree *worktree;
4914 struct got_diffstat_cb_arg *diffstat;
4915 int diff_context;
4916 const char *id_str;
4917 int header_shown;
4918 int diff_staged;
4919 enum got_diff_algorithm diff_algo;
4920 int ignore_whitespace;
4921 int force_text_diff;
4922 FILE *f1;
4923 FILE *f2;
4924 FILE *outfile;
4928 * Create a file which contains the target path of a symlink so we can feed
4929 * it as content to the diff engine.
4931 static const struct got_error *
4932 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4933 const char *abspath)
4935 const struct got_error *err = NULL;
4936 char target_path[PATH_MAX];
4937 ssize_t target_len, outlen;
4939 *fd = -1;
4941 if (dirfd != -1) {
4942 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4943 if (target_len == -1)
4944 return got_error_from_errno2("readlinkat", abspath);
4945 } else {
4946 target_len = readlink(abspath, target_path, PATH_MAX);
4947 if (target_len == -1)
4948 return got_error_from_errno2("readlink", abspath);
4951 *fd = got_opentempfd();
4952 if (*fd == -1)
4953 return got_error_from_errno("got_opentempfd");
4955 outlen = write(*fd, target_path, target_len);
4956 if (outlen == -1) {
4957 err = got_error_from_errno("got_opentempfd");
4958 goto done;
4961 if (lseek(*fd, 0, SEEK_SET) == -1) {
4962 err = got_error_from_errno2("lseek", abspath);
4963 goto done;
4965 done:
4966 if (err) {
4967 close(*fd);
4968 *fd = -1;
4970 return err;
4973 static const struct got_error *
4974 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4975 const char *path, struct got_object_id *blob_id,
4976 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4977 int dirfd, const char *de_name)
4979 struct print_diff_arg *a = arg;
4980 const struct got_error *err = NULL;
4981 struct got_blob_object *blob1 = NULL;
4982 int fd = -1, fd1 = -1, fd2 = -1;
4983 FILE *f2 = NULL;
4984 char *abspath = NULL, *label1 = NULL;
4985 struct stat sb;
4986 off_t size1 = 0;
4987 int f2_exists = 0;
4989 memset(&sb, 0, sizeof(sb));
4991 if (a->diff_staged) {
4992 if (staged_status != GOT_STATUS_MODIFY &&
4993 staged_status != GOT_STATUS_ADD &&
4994 staged_status != GOT_STATUS_DELETE)
4995 return NULL;
4996 } else {
4997 if (staged_status == GOT_STATUS_DELETE)
4998 return NULL;
4999 if (status == GOT_STATUS_NONEXISTENT)
5000 return got_error_set_errno(ENOENT, path);
5001 if (status != GOT_STATUS_MODIFY &&
5002 status != GOT_STATUS_ADD &&
5003 status != GOT_STATUS_DELETE &&
5004 status != GOT_STATUS_CONFLICT)
5005 return NULL;
5008 err = got_opentemp_truncate(a->f1);
5009 if (err)
5010 return got_error_from_errno("got_opentemp_truncate");
5011 err = got_opentemp_truncate(a->f2);
5012 if (err)
5013 return got_error_from_errno("got_opentemp_truncate");
5015 if (!a->header_shown) {
5016 if (fprintf(a->outfile, "diff %s%s\n",
5017 a->diff_staged ? "-s " : "",
5018 got_worktree_get_root_path(a->worktree)) < 0) {
5019 err = got_error_from_errno("fprintf");
5020 goto done;
5022 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5023 err = got_error_from_errno("fprintf");
5024 goto done;
5026 if (fprintf(a->outfile, "path + %s%s\n",
5027 got_worktree_get_root_path(a->worktree),
5028 a->diff_staged ? " (staged changes)" : "") < 0) {
5029 err = got_error_from_errno("fprintf");
5030 goto done;
5032 a->header_shown = 1;
5035 if (a->diff_staged) {
5036 const char *label1 = NULL, *label2 = NULL;
5037 switch (staged_status) {
5038 case GOT_STATUS_MODIFY:
5039 label1 = path;
5040 label2 = path;
5041 break;
5042 case GOT_STATUS_ADD:
5043 label2 = path;
5044 break;
5045 case GOT_STATUS_DELETE:
5046 label1 = path;
5047 break;
5048 default:
5049 return got_error(GOT_ERR_FILE_STATUS);
5051 fd1 = got_opentempfd();
5052 if (fd1 == -1) {
5053 err = got_error_from_errno("got_opentempfd");
5054 goto done;
5056 fd2 = got_opentempfd();
5057 if (fd2 == -1) {
5058 err = got_error_from_errno("got_opentempfd");
5059 goto done;
5061 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5062 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5063 a->diff_algo, a->diff_context, a->ignore_whitespace,
5064 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5065 goto done;
5068 fd1 = got_opentempfd();
5069 if (fd1 == -1) {
5070 err = got_error_from_errno("got_opentempfd");
5071 goto done;
5074 if (staged_status == GOT_STATUS_ADD ||
5075 staged_status == GOT_STATUS_MODIFY) {
5076 char *id_str;
5077 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5078 8192, fd1);
5079 if (err)
5080 goto done;
5081 err = got_object_id_str(&id_str, staged_blob_id);
5082 if (err)
5083 goto done;
5084 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5085 err = got_error_from_errno("asprintf");
5086 free(id_str);
5087 goto done;
5089 free(id_str);
5090 } else if (status != GOT_STATUS_ADD) {
5091 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5092 fd1);
5093 if (err)
5094 goto done;
5097 if (status != GOT_STATUS_DELETE) {
5098 if (asprintf(&abspath, "%s/%s",
5099 got_worktree_get_root_path(a->worktree), path) == -1) {
5100 err = got_error_from_errno("asprintf");
5101 goto done;
5104 if (dirfd != -1) {
5105 fd = openat(dirfd, de_name,
5106 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5107 if (fd == -1) {
5108 if (!got_err_open_nofollow_on_symlink()) {
5109 err = got_error_from_errno2("openat",
5110 abspath);
5111 goto done;
5113 err = get_symlink_target_file(&fd, dirfd,
5114 de_name, abspath);
5115 if (err)
5116 goto done;
5118 } else {
5119 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5120 if (fd == -1) {
5121 if (!got_err_open_nofollow_on_symlink()) {
5122 err = got_error_from_errno2("open",
5123 abspath);
5124 goto done;
5126 err = get_symlink_target_file(&fd, dirfd,
5127 de_name, abspath);
5128 if (err)
5129 goto done;
5132 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5133 err = got_error_from_errno2("fstatat", abspath);
5134 goto done;
5136 f2 = fdopen(fd, "r");
5137 if (f2 == NULL) {
5138 err = got_error_from_errno2("fdopen", abspath);
5139 goto done;
5141 fd = -1;
5142 f2_exists = 1;
5145 if (blob1) {
5146 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5147 a->f1, blob1);
5148 if (err)
5149 goto done;
5152 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5153 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5154 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5155 done:
5156 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5157 err = got_error_from_errno("close");
5158 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5159 err = got_error_from_errno("close");
5160 if (blob1)
5161 got_object_blob_close(blob1);
5162 if (fd != -1 && close(fd) == -1 && err == NULL)
5163 err = got_error_from_errno("close");
5164 if (f2 && fclose(f2) == EOF && err == NULL)
5165 err = got_error_from_errno("fclose");
5166 free(abspath);
5167 return err;
5170 static const struct got_error *
5171 cmd_diff(int argc, char *argv[])
5173 const struct got_error *error;
5174 struct got_repository *repo = NULL;
5175 struct got_worktree *worktree = NULL;
5176 char *cwd = NULL, *repo_path = NULL;
5177 const char *commit_args[2] = { NULL, NULL };
5178 int ncommit_args = 0;
5179 struct got_object_id *ids[2] = { NULL, NULL };
5180 char *labels[2] = { NULL, NULL };
5181 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5182 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5183 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5184 const char *errstr;
5185 struct got_reflist_head refs;
5186 struct got_pathlist_head diffstat_paths, paths;
5187 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5188 int fd1 = -1, fd2 = -1;
5189 int *pack_fds = NULL;
5190 struct got_diffstat_cb_arg dsa;
5192 memset(&dsa, 0, sizeof(dsa));
5194 TAILQ_INIT(&refs);
5195 TAILQ_INIT(&paths);
5196 TAILQ_INIT(&diffstat_paths);
5198 #ifndef PROFILE
5199 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5200 NULL) == -1)
5201 err(1, "pledge");
5202 #endif
5204 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5205 switch (ch) {
5206 case 'a':
5207 force_text_diff = 1;
5208 break;
5209 case 'C':
5210 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5211 &errstr);
5212 if (errstr != NULL)
5213 errx(1, "number of context lines is %s: %s",
5214 errstr, optarg);
5215 break;
5216 case 'c':
5217 if (ncommit_args >= 2)
5218 errx(1, "too many -c options used");
5219 commit_args[ncommit_args++] = optarg;
5220 break;
5221 case 'd':
5222 show_diffstat = 1;
5223 break;
5224 case 'P':
5225 force_path = 1;
5226 break;
5227 case 'r':
5228 repo_path = realpath(optarg, NULL);
5229 if (repo_path == NULL)
5230 return got_error_from_errno2("realpath",
5231 optarg);
5232 got_path_strip_trailing_slashes(repo_path);
5233 rflag = 1;
5234 break;
5235 case 's':
5236 diff_staged = 1;
5237 break;
5238 case 'w':
5239 ignore_whitespace = 1;
5240 break;
5241 default:
5242 usage_diff();
5243 /* NOTREACHED */
5247 argc -= optind;
5248 argv += optind;
5250 cwd = getcwd(NULL, 0);
5251 if (cwd == NULL) {
5252 error = got_error_from_errno("getcwd");
5253 goto done;
5256 error = got_repo_pack_fds_open(&pack_fds);
5257 if (error != NULL)
5258 goto done;
5260 if (repo_path == NULL) {
5261 error = got_worktree_open(&worktree, cwd,
5262 GOT_WORKTREE_GOT_DIR);
5263 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5264 goto done;
5265 else
5266 error = NULL;
5267 if (worktree) {
5268 repo_path =
5269 strdup(got_worktree_get_repo_path(worktree));
5270 if (repo_path == NULL) {
5271 error = got_error_from_errno("strdup");
5272 goto done;
5274 } else {
5275 repo_path = strdup(cwd);
5276 if (repo_path == NULL) {
5277 error = got_error_from_errno("strdup");
5278 goto done;
5283 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5284 free(repo_path);
5285 if (error != NULL)
5286 goto done;
5288 if (show_diffstat) {
5289 dsa.paths = &diffstat_paths;
5290 dsa.force_text = force_text_diff;
5291 dsa.ignore_ws = ignore_whitespace;
5292 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5295 if (rflag || worktree == NULL || ncommit_args > 0) {
5296 if (force_path) {
5297 error = got_error_msg(GOT_ERR_NOT_IMPL,
5298 "-P option can only be used when diffing "
5299 "a work tree");
5300 goto done;
5302 if (diff_staged) {
5303 error = got_error_msg(GOT_ERR_NOT_IMPL,
5304 "-s option can only be used when diffing "
5305 "a work tree");
5306 goto done;
5310 error = apply_unveil(got_repo_get_path(repo), 1,
5311 worktree ? got_worktree_get_root_path(worktree) : NULL);
5312 if (error)
5313 goto done;
5315 if ((!force_path && argc == 2) || ncommit_args > 0) {
5316 int obj_type = (ncommit_args > 0 ?
5317 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5318 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5319 NULL);
5320 if (error)
5321 goto done;
5322 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5323 const char *arg;
5324 char *keyword_idstr = NULL;
5326 if (ncommit_args > 0)
5327 arg = commit_args[i];
5328 else
5329 arg = argv[i];
5331 error = got_keyword_to_idstr(&keyword_idstr, arg,
5332 repo, worktree);
5333 if (error != NULL)
5334 goto done;
5335 if (keyword_idstr != NULL)
5336 arg = keyword_idstr;
5338 error = got_repo_match_object_id(&ids[i], &labels[i],
5339 arg, obj_type, &refs, repo);
5340 free(keyword_idstr);
5341 if (error) {
5342 if (error->code != GOT_ERR_NOT_REF &&
5343 error->code != GOT_ERR_NO_OBJ)
5344 goto done;
5345 if (ncommit_args > 0)
5346 goto done;
5347 error = NULL;
5348 break;
5353 f1 = got_opentemp();
5354 if (f1 == NULL) {
5355 error = got_error_from_errno("got_opentemp");
5356 goto done;
5359 f2 = got_opentemp();
5360 if (f2 == NULL) {
5361 error = got_error_from_errno("got_opentemp");
5362 goto done;
5365 outfile = got_opentemp();
5366 if (outfile == NULL) {
5367 error = got_error_from_errno("got_opentemp");
5368 goto done;
5371 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5372 struct print_diff_arg arg;
5373 char *id_str;
5375 if (worktree == NULL) {
5376 if (argc == 2 && ids[0] == NULL) {
5377 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5378 goto done;
5379 } else if (argc == 2 && ids[1] == NULL) {
5380 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5381 goto done;
5382 } else if (argc > 0) {
5383 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5384 "%s", "specified paths cannot be resolved");
5385 goto done;
5386 } else {
5387 error = got_error(GOT_ERR_NOT_WORKTREE);
5388 goto done;
5392 error = get_worktree_paths_from_argv(&paths, argc, argv,
5393 worktree);
5394 if (error)
5395 goto done;
5397 error = got_object_id_str(&id_str,
5398 got_worktree_get_base_commit_id(worktree));
5399 if (error)
5400 goto done;
5401 arg.repo = repo;
5402 arg.worktree = worktree;
5403 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5404 arg.diff_context = diff_context;
5405 arg.id_str = id_str;
5406 arg.header_shown = 0;
5407 arg.diff_staged = diff_staged;
5408 arg.ignore_whitespace = ignore_whitespace;
5409 arg.force_text_diff = force_text_diff;
5410 arg.diffstat = show_diffstat ? &dsa : NULL;
5411 arg.f1 = f1;
5412 arg.f2 = f2;
5413 arg.outfile = outfile;
5415 error = got_worktree_status(worktree, &paths, repo, 0,
5416 print_diff, &arg, check_cancelled, NULL);
5417 free(id_str);
5418 if (error)
5419 goto done;
5421 if (show_diffstat && dsa.nfiles > 0) {
5422 char *header;
5424 if (asprintf(&header, "diffstat %s%s",
5425 diff_staged ? "-s " : "",
5426 got_worktree_get_root_path(worktree)) == -1) {
5427 error = got_error_from_errno("asprintf");
5428 goto done;
5431 error = print_diffstat(&dsa, header);
5432 free(header);
5433 if (error)
5434 goto done;
5437 error = printfile(outfile);
5438 goto done;
5441 if (ncommit_args == 1) {
5442 struct got_commit_object *commit;
5443 error = got_object_open_as_commit(&commit, repo, ids[0]);
5444 if (error)
5445 goto done;
5447 labels[1] = labels[0];
5448 ids[1] = ids[0];
5449 if (got_object_commit_get_nparents(commit) > 0) {
5450 const struct got_object_id_queue *pids;
5451 struct got_object_qid *pid;
5452 pids = got_object_commit_get_parent_ids(commit);
5453 pid = STAILQ_FIRST(pids);
5454 ids[0] = got_object_id_dup(&pid->id);
5455 if (ids[0] == NULL) {
5456 error = got_error_from_errno(
5457 "got_object_id_dup");
5458 got_object_commit_close(commit);
5459 goto done;
5461 error = got_object_id_str(&labels[0], ids[0]);
5462 if (error) {
5463 got_object_commit_close(commit);
5464 goto done;
5466 } else {
5467 ids[0] = NULL;
5468 labels[0] = strdup("/dev/null");
5469 if (labels[0] == NULL) {
5470 error = got_error_from_errno("strdup");
5471 got_object_commit_close(commit);
5472 goto done;
5476 got_object_commit_close(commit);
5479 if (ncommit_args == 0 && argc > 2) {
5480 error = got_error_msg(GOT_ERR_BAD_PATH,
5481 "path arguments cannot be used when diffing two objects");
5482 goto done;
5485 if (ids[0]) {
5486 error = got_object_get_type(&type1, repo, ids[0]);
5487 if (error)
5488 goto done;
5491 error = got_object_get_type(&type2, repo, ids[1]);
5492 if (error)
5493 goto done;
5494 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5495 error = got_error(GOT_ERR_OBJ_TYPE);
5496 goto done;
5498 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5499 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5500 "path arguments cannot be used when diffing blobs");
5501 goto done;
5504 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5505 char *in_repo_path;
5506 struct got_pathlist_entry *new;
5507 if (worktree) {
5508 const char *prefix;
5509 char *p;
5510 error = got_worktree_resolve_path(&p, worktree,
5511 argv[i]);
5512 if (error)
5513 goto done;
5514 prefix = got_worktree_get_path_prefix(worktree);
5515 while (prefix[0] == '/')
5516 prefix++;
5517 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5518 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5519 p) == -1) {
5520 error = got_error_from_errno("asprintf");
5521 free(p);
5522 goto done;
5524 free(p);
5525 } else {
5526 char *mapped_path, *s;
5527 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5528 if (error)
5529 goto done;
5530 s = mapped_path;
5531 while (s[0] == '/')
5532 s++;
5533 in_repo_path = strdup(s);
5534 if (in_repo_path == NULL) {
5535 error = got_error_from_errno("asprintf");
5536 free(mapped_path);
5537 goto done;
5539 free(mapped_path);
5542 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5543 if (error || new == NULL /* duplicate */)
5544 free(in_repo_path);
5545 if (error)
5546 goto done;
5549 if (worktree) {
5550 /* Release work tree lock. */
5551 got_worktree_close(worktree);
5552 worktree = NULL;
5555 fd1 = got_opentempfd();
5556 if (fd1 == -1) {
5557 error = got_error_from_errno("got_opentempfd");
5558 goto done;
5561 fd2 = got_opentempfd();
5562 if (fd2 == -1) {
5563 error = got_error_from_errno("got_opentempfd");
5564 goto done;
5567 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5568 case GOT_OBJ_TYPE_BLOB:
5569 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5570 fd1, fd2, ids[0], ids[1], NULL, NULL,
5571 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5572 ignore_whitespace, force_text_diff,
5573 show_diffstat ? &dsa : NULL, repo, outfile);
5574 break;
5575 case GOT_OBJ_TYPE_TREE:
5576 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5577 ids[0], ids[1], &paths, "", "",
5578 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5579 ignore_whitespace, force_text_diff,
5580 show_diffstat ? &dsa : NULL, repo, outfile);
5581 break;
5582 case GOT_OBJ_TYPE_COMMIT:
5583 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5584 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5585 fd1, fd2, ids[0], ids[1], &paths,
5586 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5587 ignore_whitespace, force_text_diff,
5588 show_diffstat ? &dsa : NULL, repo, outfile);
5589 break;
5590 default:
5591 error = got_error(GOT_ERR_OBJ_TYPE);
5593 if (error)
5594 goto done;
5596 if (show_diffstat && dsa.nfiles > 0) {
5597 char *header = NULL;
5599 if (asprintf(&header, "diffstat %s %s",
5600 labels[0], labels[1]) == -1) {
5601 error = got_error_from_errno("asprintf");
5602 goto done;
5605 error = print_diffstat(&dsa, header);
5606 free(header);
5607 if (error)
5608 goto done;
5611 error = printfile(outfile);
5613 done:
5614 free(labels[0]);
5615 free(labels[1]);
5616 free(ids[0]);
5617 free(ids[1]);
5618 if (worktree)
5619 got_worktree_close(worktree);
5620 if (repo) {
5621 const struct got_error *close_err = got_repo_close(repo);
5622 if (error == NULL)
5623 error = close_err;
5625 if (pack_fds) {
5626 const struct got_error *pack_err =
5627 got_repo_pack_fds_close(pack_fds);
5628 if (error == NULL)
5629 error = pack_err;
5631 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5632 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5633 got_ref_list_free(&refs);
5634 if (outfile && fclose(outfile) == EOF && error == NULL)
5635 error = got_error_from_errno("fclose");
5636 if (f1 && fclose(f1) == EOF && error == NULL)
5637 error = got_error_from_errno("fclose");
5638 if (f2 && fclose(f2) == EOF && error == NULL)
5639 error = got_error_from_errno("fclose");
5640 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5641 error = got_error_from_errno("close");
5642 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5643 error = got_error_from_errno("close");
5644 return error;
5647 __dead static void
5648 usage_blame(void)
5650 fprintf(stderr,
5651 "usage: %s blame [-c commit] [-r repository-path] path\n",
5652 getprogname());
5653 exit(1);
5656 struct blame_line {
5657 int annotated;
5658 char *id_str;
5659 char *committer;
5660 char datebuf[11]; /* YYYY-MM-DD + NUL */
5663 struct blame_cb_args {
5664 struct blame_line *lines;
5665 int nlines;
5666 int nlines_prec;
5667 int lineno_cur;
5668 off_t *line_offsets;
5669 FILE *f;
5670 struct got_repository *repo;
5673 static const struct got_error *
5674 blame_cb(void *arg, int nlines, int lineno,
5675 struct got_commit_object *commit, struct got_object_id *id)
5677 const struct got_error *err = NULL;
5678 struct blame_cb_args *a = arg;
5679 struct blame_line *bline;
5680 char *line = NULL;
5681 size_t linesize = 0;
5682 off_t offset;
5683 struct tm tm;
5684 time_t committer_time;
5686 if (nlines != a->nlines ||
5687 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5688 return got_error(GOT_ERR_RANGE);
5690 if (sigint_received)
5691 return got_error(GOT_ERR_ITER_COMPLETED);
5693 if (lineno == -1)
5694 return NULL; /* no change in this commit */
5696 /* Annotate this line. */
5697 bline = &a->lines[lineno - 1];
5698 if (bline->annotated)
5699 return NULL;
5700 err = got_object_id_str(&bline->id_str, id);
5701 if (err)
5702 return err;
5704 bline->committer = strdup(got_object_commit_get_committer(commit));
5705 if (bline->committer == NULL) {
5706 err = got_error_from_errno("strdup");
5707 goto done;
5710 committer_time = got_object_commit_get_committer_time(commit);
5711 if (gmtime_r(&committer_time, &tm) == NULL)
5712 return got_error_from_errno("gmtime_r");
5713 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5714 &tm) == 0) {
5715 err = got_error(GOT_ERR_NO_SPACE);
5716 goto done;
5718 bline->annotated = 1;
5720 /* Print lines annotated so far. */
5721 bline = &a->lines[a->lineno_cur - 1];
5722 if (!bline->annotated)
5723 goto done;
5725 offset = a->line_offsets[a->lineno_cur - 1];
5726 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5727 err = got_error_from_errno("fseeko");
5728 goto done;
5731 while (a->lineno_cur <= a->nlines && bline->annotated) {
5732 char *smallerthan, *at, *nl, *committer;
5733 size_t len;
5735 if (getline(&line, &linesize, a->f) == -1) {
5736 if (ferror(a->f))
5737 err = got_error_from_errno("getline");
5738 break;
5741 committer = bline->committer;
5742 smallerthan = strchr(committer, '<');
5743 if (smallerthan && smallerthan[1] != '\0')
5744 committer = smallerthan + 1;
5745 at = strchr(committer, '@');
5746 if (at)
5747 *at = '\0';
5748 len = strlen(committer);
5749 if (len >= 9)
5750 committer[8] = '\0';
5752 nl = strchr(line, '\n');
5753 if (nl)
5754 *nl = '\0';
5755 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5756 bline->id_str, bline->datebuf, committer, line);
5758 a->lineno_cur++;
5759 bline = &a->lines[a->lineno_cur - 1];
5761 done:
5762 free(line);
5763 return err;
5766 static const struct got_error *
5767 cmd_blame(int argc, char *argv[])
5769 const struct got_error *error;
5770 struct got_repository *repo = NULL;
5771 struct got_worktree *worktree = NULL;
5772 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5773 char *link_target = NULL;
5774 struct got_object_id *obj_id = NULL;
5775 struct got_object_id *commit_id = NULL;
5776 struct got_commit_object *commit = NULL;
5777 struct got_blob_object *blob = NULL;
5778 char *commit_id_str = NULL, *keyword_idstr = NULL;
5779 struct blame_cb_args bca;
5780 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5781 off_t filesize;
5782 int *pack_fds = NULL;
5783 FILE *f1 = NULL, *f2 = NULL;
5785 fd1 = got_opentempfd();
5786 if (fd1 == -1)
5787 return got_error_from_errno("got_opentempfd");
5789 memset(&bca, 0, sizeof(bca));
5791 #ifndef PROFILE
5792 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5793 NULL) == -1)
5794 err(1, "pledge");
5795 #endif
5797 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5798 switch (ch) {
5799 case 'c':
5800 commit_id_str = optarg;
5801 break;
5802 case 'r':
5803 repo_path = realpath(optarg, NULL);
5804 if (repo_path == NULL)
5805 return got_error_from_errno2("realpath",
5806 optarg);
5807 got_path_strip_trailing_slashes(repo_path);
5808 break;
5809 default:
5810 usage_blame();
5811 /* NOTREACHED */
5815 argc -= optind;
5816 argv += optind;
5818 if (argc == 1)
5819 path = argv[0];
5820 else
5821 usage_blame();
5823 cwd = getcwd(NULL, 0);
5824 if (cwd == NULL) {
5825 error = got_error_from_errno("getcwd");
5826 goto done;
5829 error = got_repo_pack_fds_open(&pack_fds);
5830 if (error != NULL)
5831 goto done;
5833 if (repo_path == NULL) {
5834 error = got_worktree_open(&worktree, cwd,
5835 GOT_WORKTREE_GOT_DIR);
5836 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5837 goto done;
5838 else
5839 error = NULL;
5840 if (worktree) {
5841 repo_path =
5842 strdup(got_worktree_get_repo_path(worktree));
5843 if (repo_path == NULL) {
5844 error = got_error_from_errno("strdup");
5845 if (error)
5846 goto done;
5848 } else {
5849 repo_path = strdup(cwd);
5850 if (repo_path == NULL) {
5851 error = got_error_from_errno("strdup");
5852 goto done;
5857 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5858 if (error != NULL)
5859 goto done;
5861 if (worktree) {
5862 const char *prefix = got_worktree_get_path_prefix(worktree);
5863 char *p;
5865 error = got_worktree_resolve_path(&p, worktree, path);
5866 if (error)
5867 goto done;
5868 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5869 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5870 p) == -1) {
5871 error = got_error_from_errno("asprintf");
5872 free(p);
5873 goto done;
5875 free(p);
5876 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5877 } else {
5878 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5879 if (error)
5880 goto done;
5881 error = got_repo_map_path(&in_repo_path, repo, path);
5883 if (error)
5884 goto done;
5886 if (commit_id_str == NULL) {
5887 struct got_reference *head_ref;
5888 error = got_ref_open(&head_ref, repo, worktree ?
5889 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5890 if (error != NULL)
5891 goto done;
5892 error = got_ref_resolve(&commit_id, repo, head_ref);
5893 got_ref_close(head_ref);
5894 if (error != NULL)
5895 goto done;
5896 } else {
5897 struct got_reflist_head refs;
5899 TAILQ_INIT(&refs);
5900 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5901 NULL);
5902 if (error)
5903 goto done;
5905 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5906 repo, worktree);
5907 if (error != NULL)
5908 goto done;
5909 if (keyword_idstr != NULL)
5910 commit_id_str = keyword_idstr;
5912 error = got_repo_match_object_id(&commit_id, NULL,
5913 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5914 got_ref_list_free(&refs);
5915 if (error)
5916 goto done;
5919 if (worktree) {
5920 /* Release work tree lock. */
5921 got_worktree_close(worktree);
5922 worktree = NULL;
5925 error = got_object_open_as_commit(&commit, repo, commit_id);
5926 if (error)
5927 goto done;
5929 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5930 commit, repo);
5931 if (error)
5932 goto done;
5934 error = got_object_id_by_path(&obj_id, repo, commit,
5935 link_target ? link_target : in_repo_path);
5936 if (error)
5937 goto done;
5939 error = got_object_get_type(&obj_type, repo, obj_id);
5940 if (error)
5941 goto done;
5943 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5944 error = got_error_path(link_target ? link_target : in_repo_path,
5945 GOT_ERR_OBJ_TYPE);
5946 goto done;
5949 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5950 if (error)
5951 goto done;
5952 bca.f = got_opentemp();
5953 if (bca.f == NULL) {
5954 error = got_error_from_errno("got_opentemp");
5955 goto done;
5957 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5958 &bca.line_offsets, bca.f, blob);
5959 if (error || bca.nlines == 0)
5960 goto done;
5962 /* Don't include \n at EOF in the blame line count. */
5963 if (bca.line_offsets[bca.nlines - 1] == filesize)
5964 bca.nlines--;
5966 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5967 if (bca.lines == NULL) {
5968 error = got_error_from_errno("calloc");
5969 goto done;
5971 bca.lineno_cur = 1;
5972 bca.nlines_prec = 0;
5973 i = bca.nlines;
5974 while (i > 0) {
5975 i /= 10;
5976 bca.nlines_prec++;
5978 bca.repo = repo;
5980 fd2 = got_opentempfd();
5981 if (fd2 == -1) {
5982 error = got_error_from_errno("got_opentempfd");
5983 goto done;
5985 fd3 = got_opentempfd();
5986 if (fd3 == -1) {
5987 error = got_error_from_errno("got_opentempfd");
5988 goto done;
5990 f1 = got_opentemp();
5991 if (f1 == NULL) {
5992 error = got_error_from_errno("got_opentemp");
5993 goto done;
5995 f2 = got_opentemp();
5996 if (f2 == NULL) {
5997 error = got_error_from_errno("got_opentemp");
5998 goto done;
6000 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6001 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6002 check_cancelled, NULL, fd2, fd3, f1, f2);
6003 done:
6004 free(keyword_idstr);
6005 free(in_repo_path);
6006 free(link_target);
6007 free(repo_path);
6008 free(cwd);
6009 free(commit_id);
6010 free(obj_id);
6011 if (commit)
6012 got_object_commit_close(commit);
6014 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6015 error = got_error_from_errno("close");
6016 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6017 error = got_error_from_errno("close");
6018 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6019 error = got_error_from_errno("close");
6020 if (f1 && fclose(f1) == EOF && error == NULL)
6021 error = got_error_from_errno("fclose");
6022 if (f2 && fclose(f2) == EOF && error == NULL)
6023 error = got_error_from_errno("fclose");
6025 if (blob)
6026 got_object_blob_close(blob);
6027 if (worktree)
6028 got_worktree_close(worktree);
6029 if (repo) {
6030 const struct got_error *close_err = got_repo_close(repo);
6031 if (error == NULL)
6032 error = close_err;
6034 if (pack_fds) {
6035 const struct got_error *pack_err =
6036 got_repo_pack_fds_close(pack_fds);
6037 if (error == NULL)
6038 error = pack_err;
6040 if (bca.lines) {
6041 for (i = 0; i < bca.nlines; i++) {
6042 struct blame_line *bline = &bca.lines[i];
6043 free(bline->id_str);
6044 free(bline->committer);
6046 free(bca.lines);
6048 free(bca.line_offsets);
6049 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6050 error = got_error_from_errno("fclose");
6051 return error;
6054 __dead static void
6055 usage_tree(void)
6057 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6058 "[path]\n", getprogname());
6059 exit(1);
6062 static const struct got_error *
6063 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6064 const char *root_path, struct got_repository *repo)
6066 const struct got_error *err = NULL;
6067 int is_root_path = (strcmp(path, root_path) == 0);
6068 const char *modestr = "";
6069 mode_t mode = got_tree_entry_get_mode(te);
6070 char *link_target = NULL;
6072 path += strlen(root_path);
6073 while (path[0] == '/')
6074 path++;
6076 if (got_object_tree_entry_is_submodule(te))
6077 modestr = "$";
6078 else if (S_ISLNK(mode)) {
6079 int i;
6081 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6082 if (err)
6083 return err;
6084 for (i = 0; link_target[i] != '\0'; i++) {
6085 if (!isprint((unsigned char)link_target[i]))
6086 link_target[i] = '?';
6089 modestr = "@";
6091 else if (S_ISDIR(mode))
6092 modestr = "/";
6093 else if (mode & S_IXUSR)
6094 modestr = "*";
6096 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6097 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6098 link_target ? " -> ": "", link_target ? link_target : "");
6100 free(link_target);
6101 return NULL;
6104 static const struct got_error *
6105 print_tree(const char *path, struct got_commit_object *commit,
6106 int show_ids, int recurse, const char *root_path,
6107 struct got_repository *repo)
6109 const struct got_error *err = NULL;
6110 struct got_object_id *tree_id = NULL;
6111 struct got_tree_object *tree = NULL;
6112 int nentries, i;
6114 err = got_object_id_by_path(&tree_id, repo, commit, path);
6115 if (err)
6116 goto done;
6118 err = got_object_open_as_tree(&tree, repo, tree_id);
6119 if (err)
6120 goto done;
6121 nentries = got_object_tree_get_nentries(tree);
6122 for (i = 0; i < nentries; i++) {
6123 struct got_tree_entry *te;
6124 char *id = NULL;
6126 if (sigint_received || sigpipe_received)
6127 break;
6129 te = got_object_tree_get_entry(tree, i);
6130 if (show_ids) {
6131 char *id_str;
6132 err = got_object_id_str(&id_str,
6133 got_tree_entry_get_id(te));
6134 if (err)
6135 goto done;
6136 if (asprintf(&id, "%s ", id_str) == -1) {
6137 err = got_error_from_errno("asprintf");
6138 free(id_str);
6139 goto done;
6141 free(id_str);
6143 err = print_entry(te, id, path, root_path, repo);
6144 free(id);
6145 if (err)
6146 goto done;
6148 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6149 char *child_path;
6150 if (asprintf(&child_path, "%s%s%s", path,
6151 path[0] == '/' && path[1] == '\0' ? "" : "/",
6152 got_tree_entry_get_name(te)) == -1) {
6153 err = got_error_from_errno("asprintf");
6154 goto done;
6156 err = print_tree(child_path, commit, show_ids, 1,
6157 root_path, repo);
6158 free(child_path);
6159 if (err)
6160 goto done;
6163 done:
6164 if (tree)
6165 got_object_tree_close(tree);
6166 free(tree_id);
6167 return err;
6170 static const struct got_error *
6171 cmd_tree(int argc, char *argv[])
6173 const struct got_error *error;
6174 struct got_repository *repo = NULL;
6175 struct got_worktree *worktree = NULL;
6176 const char *path, *refname = NULL;
6177 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6178 struct got_object_id *commit_id = NULL;
6179 struct got_commit_object *commit = NULL;
6180 char *commit_id_str = NULL, *keyword_idstr = NULL;
6181 int show_ids = 0, recurse = 0;
6182 int ch;
6183 int *pack_fds = NULL;
6185 #ifndef PROFILE
6186 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6187 NULL) == -1)
6188 err(1, "pledge");
6189 #endif
6191 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6192 switch (ch) {
6193 case 'c':
6194 commit_id_str = optarg;
6195 break;
6196 case 'i':
6197 show_ids = 1;
6198 break;
6199 case 'R':
6200 recurse = 1;
6201 break;
6202 case 'r':
6203 repo_path = realpath(optarg, NULL);
6204 if (repo_path == NULL)
6205 return got_error_from_errno2("realpath",
6206 optarg);
6207 got_path_strip_trailing_slashes(repo_path);
6208 break;
6209 default:
6210 usage_tree();
6211 /* NOTREACHED */
6215 argc -= optind;
6216 argv += optind;
6218 if (argc == 1)
6219 path = argv[0];
6220 else if (argc > 1)
6221 usage_tree();
6222 else
6223 path = NULL;
6225 cwd = getcwd(NULL, 0);
6226 if (cwd == NULL) {
6227 error = got_error_from_errno("getcwd");
6228 goto done;
6231 error = got_repo_pack_fds_open(&pack_fds);
6232 if (error != NULL)
6233 goto done;
6235 if (repo_path == NULL) {
6236 error = got_worktree_open(&worktree, cwd,
6237 GOT_WORKTREE_GOT_DIR);
6238 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6239 goto done;
6240 else
6241 error = NULL;
6242 if (worktree) {
6243 repo_path =
6244 strdup(got_worktree_get_repo_path(worktree));
6245 if (repo_path == NULL)
6246 error = got_error_from_errno("strdup");
6247 if (error)
6248 goto done;
6249 } else {
6250 repo_path = strdup(cwd);
6251 if (repo_path == NULL) {
6252 error = got_error_from_errno("strdup");
6253 goto done;
6258 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6259 if (error != NULL)
6260 goto done;
6262 if (worktree) {
6263 const char *prefix = got_worktree_get_path_prefix(worktree);
6264 char *p;
6266 if (path == NULL || got_path_is_root_dir(path))
6267 path = "";
6268 error = got_worktree_resolve_path(&p, worktree, path);
6269 if (error)
6270 goto done;
6271 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6272 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6273 p) == -1) {
6274 error = got_error_from_errno("asprintf");
6275 free(p);
6276 goto done;
6278 free(p);
6279 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6280 if (error)
6281 goto done;
6282 } else {
6283 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6284 if (error)
6285 goto done;
6286 if (path == NULL)
6287 path = "/";
6288 error = got_repo_map_path(&in_repo_path, repo, path);
6289 if (error != NULL)
6290 goto done;
6293 if (commit_id_str == NULL) {
6294 struct got_reference *head_ref;
6295 if (worktree)
6296 refname = got_worktree_get_head_ref_name(worktree);
6297 else
6298 refname = GOT_REF_HEAD;
6299 error = got_ref_open(&head_ref, repo, refname, 0);
6300 if (error != NULL)
6301 goto done;
6302 error = got_ref_resolve(&commit_id, repo, head_ref);
6303 got_ref_close(head_ref);
6304 if (error != NULL)
6305 goto done;
6306 } else {
6307 struct got_reflist_head refs;
6309 TAILQ_INIT(&refs);
6310 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6311 NULL);
6312 if (error)
6313 goto done;
6315 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6316 repo, worktree);
6317 if (error != NULL)
6318 goto done;
6319 if (keyword_idstr != NULL)
6320 commit_id_str = keyword_idstr;
6322 error = got_repo_match_object_id(&commit_id, NULL,
6323 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6324 got_ref_list_free(&refs);
6325 if (error)
6326 goto done;
6329 if (worktree) {
6330 /* Release work tree lock. */
6331 got_worktree_close(worktree);
6332 worktree = NULL;
6335 error = got_object_open_as_commit(&commit, repo, commit_id);
6336 if (error)
6337 goto done;
6339 error = print_tree(in_repo_path, commit, show_ids, recurse,
6340 in_repo_path, repo);
6341 done:
6342 free(keyword_idstr);
6343 free(in_repo_path);
6344 free(repo_path);
6345 free(cwd);
6346 free(commit_id);
6347 if (commit)
6348 got_object_commit_close(commit);
6349 if (worktree)
6350 got_worktree_close(worktree);
6351 if (repo) {
6352 const struct got_error *close_err = got_repo_close(repo);
6353 if (error == NULL)
6354 error = close_err;
6356 if (pack_fds) {
6357 const struct got_error *pack_err =
6358 got_repo_pack_fds_close(pack_fds);
6359 if (error == NULL)
6360 error = pack_err;
6362 return error;
6365 __dead static void
6366 usage_status(void)
6368 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6369 "[-s status-codes] [path ...]\n", getprogname());
6370 exit(1);
6373 struct got_status_arg {
6374 char *status_codes;
6375 int suppress;
6378 static const struct got_error *
6379 print_status(void *arg, unsigned char status, unsigned char staged_status,
6380 const char *path, struct got_object_id *blob_id,
6381 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6382 int dirfd, const char *de_name)
6384 struct got_status_arg *st = arg;
6386 if (status == staged_status && (status == GOT_STATUS_DELETE))
6387 status = GOT_STATUS_NO_CHANGE;
6388 if (st != NULL && st->status_codes) {
6389 size_t ncodes = strlen(st->status_codes);
6390 int i, j = 0;
6392 for (i = 0; i < ncodes ; i++) {
6393 if (st->suppress) {
6394 if (status == st->status_codes[i] ||
6395 staged_status == st->status_codes[i]) {
6396 j++;
6397 continue;
6399 } else {
6400 if (status == st->status_codes[i] ||
6401 staged_status == st->status_codes[i])
6402 break;
6406 if (st->suppress && j == 0)
6407 goto print;
6409 if (i == ncodes)
6410 return NULL;
6412 print:
6413 printf("%c%c %s\n", status, staged_status, path);
6414 return NULL;
6417 static const struct got_error *
6418 cmd_status(int argc, char *argv[])
6420 const struct got_error *close_err, *error = NULL;
6421 struct got_repository *repo = NULL;
6422 struct got_worktree *worktree = NULL;
6423 struct got_status_arg st;
6424 char *cwd = NULL;
6425 struct got_pathlist_head paths;
6426 int ch, i, no_ignores = 0;
6427 int *pack_fds = NULL;
6429 TAILQ_INIT(&paths);
6431 memset(&st, 0, sizeof(st));
6432 st.status_codes = NULL;
6433 st.suppress = 0;
6435 #ifndef PROFILE
6436 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6437 NULL) == -1)
6438 err(1, "pledge");
6439 #endif
6441 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6442 switch (ch) {
6443 case 'I':
6444 no_ignores = 1;
6445 break;
6446 case 'S':
6447 if (st.status_codes != NULL && st.suppress == 0)
6448 option_conflict('S', 's');
6449 st.suppress = 1;
6450 /* fallthrough */
6451 case 's':
6452 for (i = 0; optarg[i] != '\0'; i++) {
6453 switch (optarg[i]) {
6454 case GOT_STATUS_MODIFY:
6455 case GOT_STATUS_ADD:
6456 case GOT_STATUS_DELETE:
6457 case GOT_STATUS_CONFLICT:
6458 case GOT_STATUS_MISSING:
6459 case GOT_STATUS_OBSTRUCTED:
6460 case GOT_STATUS_UNVERSIONED:
6461 case GOT_STATUS_MODE_CHANGE:
6462 case GOT_STATUS_NONEXISTENT:
6463 break;
6464 default:
6465 errx(1, "invalid status code '%c'",
6466 optarg[i]);
6469 if (ch == 's' && st.suppress)
6470 option_conflict('s', 'S');
6471 st.status_codes = optarg;
6472 break;
6473 default:
6474 usage_status();
6475 /* NOTREACHED */
6479 argc -= optind;
6480 argv += optind;
6482 cwd = getcwd(NULL, 0);
6483 if (cwd == NULL) {
6484 error = got_error_from_errno("getcwd");
6485 goto done;
6488 error = got_repo_pack_fds_open(&pack_fds);
6489 if (error != NULL)
6490 goto done;
6492 error = got_worktree_open(&worktree, cwd,
6493 GOT_WORKTREE_GOT_DIR);
6494 if (error) {
6495 if (error->code == GOT_ERR_NOT_WORKTREE)
6496 error = wrap_not_worktree_error(error, "status", cwd);
6497 goto done;
6500 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6501 NULL, pack_fds);
6502 if (error != NULL)
6503 goto done;
6505 error = apply_unveil(got_repo_get_path(repo), 1,
6506 got_worktree_get_root_path(worktree));
6507 if (error)
6508 goto done;
6510 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6511 if (error)
6512 goto done;
6514 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6515 print_status, &st, check_cancelled, NULL);
6516 done:
6517 if (pack_fds) {
6518 const struct got_error *pack_err =
6519 got_repo_pack_fds_close(pack_fds);
6520 if (error == NULL)
6521 error = pack_err;
6523 if (repo) {
6524 close_err = got_repo_close(repo);
6525 if (error == NULL)
6526 error = close_err;
6528 if (worktree != NULL) {
6529 close_err = got_worktree_close(worktree);
6530 if (error == NULL)
6531 error = close_err;
6534 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6535 free(cwd);
6536 return error;
6539 __dead static void
6540 usage_ref(void)
6542 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6543 "[-s reference] [name]\n", getprogname());
6544 exit(1);
6547 static const struct got_error *
6548 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6550 static const struct got_error *err = NULL;
6551 struct got_reflist_head refs;
6552 struct got_reflist_entry *re;
6554 TAILQ_INIT(&refs);
6555 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6556 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6557 repo);
6558 if (err)
6559 return err;
6561 TAILQ_FOREACH(re, &refs, entry) {
6562 char *refstr;
6563 refstr = got_ref_to_str(re->ref);
6564 if (refstr == NULL) {
6565 err = got_error_from_errno("got_ref_to_str");
6566 break;
6568 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6569 free(refstr);
6572 got_ref_list_free(&refs);
6573 return err;
6576 static const struct got_error *
6577 delete_ref_by_name(struct got_repository *repo, const char *refname)
6579 const struct got_error *err;
6580 struct got_reference *ref;
6582 err = got_ref_open(&ref, repo, refname, 0);
6583 if (err)
6584 return err;
6586 err = delete_ref(repo, ref);
6587 got_ref_close(ref);
6588 return err;
6591 static const struct got_error *
6592 add_ref(struct got_repository *repo, const char *refname, const char *target)
6594 const struct got_error *err = NULL;
6595 struct got_object_id *id = NULL;
6596 struct got_reference *ref = NULL;
6597 struct got_reflist_head refs;
6600 * Don't let the user create a reference name with a leading '-'.
6601 * While technically a valid reference name, this case is usually
6602 * an unintended typo.
6604 if (refname[0] == '-')
6605 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6607 TAILQ_INIT(&refs);
6608 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6609 if (err)
6610 goto done;
6611 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6612 &refs, repo);
6613 got_ref_list_free(&refs);
6614 if (err)
6615 goto done;
6617 err = got_ref_alloc(&ref, refname, id);
6618 if (err)
6619 goto done;
6621 err = got_ref_write(ref, repo);
6622 done:
6623 if (ref)
6624 got_ref_close(ref);
6625 free(id);
6626 return err;
6629 static const struct got_error *
6630 add_symref(struct got_repository *repo, const char *refname, const char *target)
6632 const struct got_error *err = NULL;
6633 struct got_reference *ref = NULL;
6634 struct got_reference *target_ref = NULL;
6637 * Don't let the user create a reference name with a leading '-'.
6638 * While technically a valid reference name, this case is usually
6639 * an unintended typo.
6641 if (refname[0] == '-')
6642 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6644 err = got_ref_open(&target_ref, repo, target, 0);
6645 if (err)
6646 return err;
6648 err = got_ref_alloc_symref(&ref, refname, target_ref);
6649 if (err)
6650 goto done;
6652 err = got_ref_write(ref, repo);
6653 done:
6654 if (target_ref)
6655 got_ref_close(target_ref);
6656 if (ref)
6657 got_ref_close(ref);
6658 return err;
6661 static const struct got_error *
6662 cmd_ref(int argc, char *argv[])
6664 const struct got_error *error = NULL;
6665 struct got_repository *repo = NULL;
6666 struct got_worktree *worktree = NULL;
6667 char *cwd = NULL, *repo_path = NULL;
6668 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6669 const char *obj_arg = NULL, *symref_target= NULL;
6670 char *refname = NULL, *keyword_idstr = NULL;
6671 int *pack_fds = NULL;
6673 #ifndef PROFILE
6674 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6675 "sendfd unveil", NULL) == -1)
6676 err(1, "pledge");
6677 #endif
6679 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6680 switch (ch) {
6681 case 'c':
6682 obj_arg = optarg;
6683 break;
6684 case 'd':
6685 do_delete = 1;
6686 break;
6687 case 'l':
6688 do_list = 1;
6689 break;
6690 case 'r':
6691 repo_path = realpath(optarg, NULL);
6692 if (repo_path == NULL)
6693 return got_error_from_errno2("realpath",
6694 optarg);
6695 got_path_strip_trailing_slashes(repo_path);
6696 break;
6697 case 's':
6698 symref_target = optarg;
6699 break;
6700 case 't':
6701 sort_by_time = 1;
6702 break;
6703 default:
6704 usage_ref();
6705 /* NOTREACHED */
6709 if (obj_arg && do_list)
6710 option_conflict('c', 'l');
6711 if (obj_arg && do_delete)
6712 option_conflict('c', 'd');
6713 if (obj_arg && symref_target)
6714 option_conflict('c', 's');
6715 if (symref_target && do_delete)
6716 option_conflict('s', 'd');
6717 if (symref_target && do_list)
6718 option_conflict('s', 'l');
6719 if (do_delete && do_list)
6720 option_conflict('d', 'l');
6721 if (sort_by_time && !do_list)
6722 errx(1, "-t option requires -l option");
6724 argc -= optind;
6725 argv += optind;
6727 if (do_list) {
6728 if (argc != 0 && argc != 1)
6729 usage_ref();
6730 if (argc == 1) {
6731 refname = strdup(argv[0]);
6732 if (refname == NULL) {
6733 error = got_error_from_errno("strdup");
6734 goto done;
6737 } else {
6738 if (argc != 1)
6739 usage_ref();
6740 refname = strdup(argv[0]);
6741 if (refname == NULL) {
6742 error = got_error_from_errno("strdup");
6743 goto done;
6747 if (refname)
6748 got_path_strip_trailing_slashes(refname);
6750 cwd = getcwd(NULL, 0);
6751 if (cwd == NULL) {
6752 error = got_error_from_errno("getcwd");
6753 goto done;
6756 error = got_repo_pack_fds_open(&pack_fds);
6757 if (error != NULL)
6758 goto done;
6760 if (repo_path == NULL) {
6761 error = got_worktree_open(&worktree, cwd,
6762 GOT_WORKTREE_GOT_DIR);
6763 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6764 goto done;
6765 else
6766 error = NULL;
6767 if (worktree) {
6768 repo_path =
6769 strdup(got_worktree_get_repo_path(worktree));
6770 if (repo_path == NULL)
6771 error = got_error_from_errno("strdup");
6772 if (error)
6773 goto done;
6774 } else {
6775 repo_path = strdup(cwd);
6776 if (repo_path == NULL) {
6777 error = got_error_from_errno("strdup");
6778 goto done;
6783 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6784 if (error != NULL)
6785 goto done;
6787 #ifndef PROFILE
6788 if (do_list) {
6789 /* Remove "cpath" promise. */
6790 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6791 NULL) == -1)
6792 err(1, "pledge");
6794 #endif
6796 error = apply_unveil(got_repo_get_path(repo), do_list,
6797 worktree ? got_worktree_get_root_path(worktree) : NULL);
6798 if (error)
6799 goto done;
6801 if (do_list)
6802 error = list_refs(repo, refname, sort_by_time);
6803 else if (do_delete)
6804 error = delete_ref_by_name(repo, refname);
6805 else if (symref_target)
6806 error = add_symref(repo, refname, symref_target);
6807 else {
6808 if (obj_arg == NULL)
6809 usage_ref();
6811 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6812 repo, worktree);
6813 if (error != NULL)
6814 goto done;
6815 if (keyword_idstr != NULL)
6816 obj_arg = keyword_idstr;
6818 error = add_ref(repo, refname, obj_arg);
6820 done:
6821 free(refname);
6822 if (repo) {
6823 const struct got_error *close_err = got_repo_close(repo);
6824 if (error == NULL)
6825 error = close_err;
6827 if (worktree)
6828 got_worktree_close(worktree);
6829 if (pack_fds) {
6830 const struct got_error *pack_err =
6831 got_repo_pack_fds_close(pack_fds);
6832 if (error == NULL)
6833 error = pack_err;
6835 free(cwd);
6836 free(repo_path);
6837 free(keyword_idstr);
6838 return error;
6841 __dead static void
6842 usage_branch(void)
6844 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6845 "[-r repository-path] [name]\n", getprogname());
6846 exit(1);
6849 static const struct got_error *
6850 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6851 struct got_reference *ref)
6853 const struct got_error *err = NULL;
6854 const char *refname;
6855 char *refstr;
6856 char marker = ' ';
6858 refname = got_ref_get_name(ref);
6859 if (worktree && strcmp(refname,
6860 got_worktree_get_head_ref_name(worktree)) == 0) {
6861 err = got_worktree_get_state(&marker, repo, worktree,
6862 check_cancelled, NULL);
6863 if (err != NULL)
6864 return err;
6867 if (strncmp(refname, "refs/heads/", 11) == 0)
6868 refname += 11;
6869 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6870 refname += 18;
6871 if (strncmp(refname, "refs/remotes/", 13) == 0)
6872 refname += 13;
6874 refstr = got_ref_to_str(ref);
6875 if (refstr == NULL)
6876 return got_error_from_errno("got_ref_to_str");
6878 printf("%c %s: %s\n", marker, refname, refstr);
6879 free(refstr);
6880 return NULL;
6883 static const struct got_error *
6884 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6886 const char *refname;
6888 if (worktree == NULL)
6889 return got_error(GOT_ERR_NOT_WORKTREE);
6891 refname = got_worktree_get_head_ref_name(worktree);
6893 if (strncmp(refname, "refs/heads/", 11) == 0)
6894 refname += 11;
6895 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6896 refname += 18;
6898 printf("%s\n", refname);
6900 return NULL;
6903 static const struct got_error *
6904 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6905 int sort_by_time)
6907 static const struct got_error *err = NULL;
6908 struct got_reflist_head refs;
6909 struct got_reflist_entry *re;
6910 struct got_reference *temp_ref = NULL;
6911 int rebase_in_progress, histedit_in_progress;
6913 TAILQ_INIT(&refs);
6915 if (worktree) {
6916 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6917 worktree);
6918 if (err)
6919 return err;
6921 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6922 worktree);
6923 if (err)
6924 return err;
6926 if (rebase_in_progress || histedit_in_progress) {
6927 err = got_ref_open(&temp_ref, repo,
6928 got_worktree_get_head_ref_name(worktree), 0);
6929 if (err)
6930 return err;
6931 list_branch(repo, worktree, temp_ref);
6932 got_ref_close(temp_ref);
6936 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6937 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6938 repo);
6939 if (err)
6940 return err;
6942 TAILQ_FOREACH(re, &refs, entry)
6943 list_branch(repo, worktree, re->ref);
6945 got_ref_list_free(&refs);
6947 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6948 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6949 repo);
6950 if (err)
6951 return err;
6953 TAILQ_FOREACH(re, &refs, entry)
6954 list_branch(repo, worktree, re->ref);
6956 got_ref_list_free(&refs);
6958 return NULL;
6961 static const struct got_error *
6962 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6963 const char *branch_name)
6965 const struct got_error *err = NULL;
6966 struct got_reference *ref = NULL;
6967 char *refname, *remote_refname = NULL;
6969 if (strncmp(branch_name, "refs/", 5) == 0)
6970 branch_name += 5;
6971 if (strncmp(branch_name, "heads/", 6) == 0)
6972 branch_name += 6;
6973 else if (strncmp(branch_name, "remotes/", 8) == 0)
6974 branch_name += 8;
6976 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6977 return got_error_from_errno("asprintf");
6979 if (asprintf(&remote_refname, "refs/remotes/%s",
6980 branch_name) == -1) {
6981 err = got_error_from_errno("asprintf");
6982 goto done;
6985 err = got_ref_open(&ref, repo, refname, 0);
6986 if (err) {
6987 const struct got_error *err2;
6988 if (err->code != GOT_ERR_NOT_REF)
6989 goto done;
6991 * Keep 'err' intact such that if neither branch exists
6992 * we report "refs/heads" rather than "refs/remotes" in
6993 * our error message.
6995 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6996 if (err2)
6997 goto done;
6998 err = NULL;
7001 if (worktree &&
7002 strcmp(got_worktree_get_head_ref_name(worktree),
7003 got_ref_get_name(ref)) == 0) {
7004 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7005 "will not delete this work tree's current branch");
7006 goto done;
7009 err = delete_ref(repo, ref);
7010 done:
7011 if (ref)
7012 got_ref_close(ref);
7013 free(refname);
7014 free(remote_refname);
7015 return err;
7018 static const struct got_error *
7019 add_branch(struct got_repository *repo, const char *branch_name,
7020 struct got_object_id *base_commit_id)
7022 const struct got_error *err = NULL;
7023 struct got_reference *ref = NULL;
7024 char *refname = NULL;
7027 * Don't let the user create a branch name with a leading '-'.
7028 * While technically a valid reference name, this case is usually
7029 * an unintended typo.
7031 if (branch_name[0] == '-')
7032 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7034 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7035 branch_name += 11;
7037 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7038 err = got_error_from_errno("asprintf");
7039 goto done;
7042 err = got_ref_open(&ref, repo, refname, 0);
7043 if (err == NULL) {
7044 err = got_error(GOT_ERR_BRANCH_EXISTS);
7045 goto done;
7046 } else if (err->code != GOT_ERR_NOT_REF)
7047 goto done;
7049 err = got_ref_alloc(&ref, refname, base_commit_id);
7050 if (err)
7051 goto done;
7053 err = got_ref_write(ref, repo);
7054 done:
7055 if (ref)
7056 got_ref_close(ref);
7057 free(refname);
7058 return err;
7061 static const struct got_error *
7062 cmd_branch(int argc, char *argv[])
7064 const struct got_error *error = NULL;
7065 struct got_repository *repo = NULL;
7066 struct got_worktree *worktree = NULL;
7067 char *cwd = NULL, *repo_path = NULL;
7068 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7069 const char *delref = NULL, *commit_id_arg = NULL;
7070 struct got_reference *ref = NULL;
7071 struct got_pathlist_head paths;
7072 struct got_object_id *commit_id = NULL;
7073 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7074 int *pack_fds = NULL;
7076 TAILQ_INIT(&paths);
7078 #ifndef PROFILE
7079 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7080 "sendfd unveil", NULL) == -1)
7081 err(1, "pledge");
7082 #endif
7084 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7085 switch (ch) {
7086 case 'c':
7087 commit_id_arg = optarg;
7088 break;
7089 case 'd':
7090 delref = optarg;
7091 break;
7092 case 'l':
7093 do_list = 1;
7094 break;
7095 case 'n':
7096 do_update = 0;
7097 break;
7098 case 'r':
7099 repo_path = realpath(optarg, NULL);
7100 if (repo_path == NULL)
7101 return got_error_from_errno2("realpath",
7102 optarg);
7103 got_path_strip_trailing_slashes(repo_path);
7104 break;
7105 case 't':
7106 sort_by_time = 1;
7107 break;
7108 default:
7109 usage_branch();
7110 /* NOTREACHED */
7114 if (do_list && delref)
7115 option_conflict('l', 'd');
7116 if (sort_by_time && !do_list)
7117 errx(1, "-t option requires -l option");
7119 argc -= optind;
7120 argv += optind;
7122 if (!do_list && !delref && argc == 0)
7123 do_show = 1;
7125 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7126 errx(1, "-c option can only be used when creating a branch");
7128 if (do_list || delref) {
7129 if (argc > 0)
7130 usage_branch();
7131 } else if (!do_show && argc != 1)
7132 usage_branch();
7134 cwd = getcwd(NULL, 0);
7135 if (cwd == NULL) {
7136 error = got_error_from_errno("getcwd");
7137 goto done;
7140 error = got_repo_pack_fds_open(&pack_fds);
7141 if (error != NULL)
7142 goto done;
7144 if (repo_path == NULL) {
7145 error = got_worktree_open(&worktree, cwd,
7146 GOT_WORKTREE_GOT_DIR);
7147 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7148 goto done;
7149 else
7150 error = NULL;
7151 if (worktree) {
7152 repo_path =
7153 strdup(got_worktree_get_repo_path(worktree));
7154 if (repo_path == NULL)
7155 error = got_error_from_errno("strdup");
7156 if (error)
7157 goto done;
7158 } else {
7159 repo_path = strdup(cwd);
7160 if (repo_path == NULL) {
7161 error = got_error_from_errno("strdup");
7162 goto done;
7167 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7168 if (error != NULL)
7169 goto done;
7171 #ifndef PROFILE
7172 if (do_list || do_show) {
7173 /* Remove "cpath" promise. */
7174 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7175 NULL) == -1)
7176 err(1, "pledge");
7178 #endif
7180 error = apply_unveil(got_repo_get_path(repo), do_list,
7181 worktree ? got_worktree_get_root_path(worktree) : NULL);
7182 if (error)
7183 goto done;
7185 if (do_show)
7186 error = show_current_branch(repo, worktree);
7187 else if (do_list)
7188 error = list_branches(repo, worktree, sort_by_time);
7189 else if (delref)
7190 error = delete_branch(repo, worktree, delref);
7191 else {
7192 struct got_reflist_head refs;
7193 TAILQ_INIT(&refs);
7194 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7195 NULL);
7196 if (error)
7197 goto done;
7198 if (commit_id_arg == NULL)
7199 commit_id_arg = worktree ?
7200 got_worktree_get_head_ref_name(worktree) :
7201 GOT_REF_HEAD;
7202 else {
7203 error = got_keyword_to_idstr(&keyword_idstr,
7204 commit_id_arg, repo, worktree);
7205 if (error != NULL)
7206 goto done;
7207 if (keyword_idstr != NULL)
7208 commit_id_arg = keyword_idstr;
7210 error = got_repo_match_object_id(&commit_id, NULL,
7211 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7212 got_ref_list_free(&refs);
7213 if (error)
7214 goto done;
7215 error = add_branch(repo, argv[0], commit_id);
7216 if (error)
7217 goto done;
7218 if (worktree && do_update) {
7219 struct got_update_progress_arg upa;
7220 char *branch_refname = NULL;
7222 error = got_object_id_str(&commit_id_str, commit_id);
7223 if (error)
7224 goto done;
7225 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7226 worktree);
7227 if (error)
7228 goto done;
7229 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7230 == -1) {
7231 error = got_error_from_errno("asprintf");
7232 goto done;
7234 error = got_ref_open(&ref, repo, branch_refname, 0);
7235 free(branch_refname);
7236 if (error)
7237 goto done;
7238 error = switch_head_ref(ref, commit_id, worktree,
7239 repo);
7240 if (error)
7241 goto done;
7242 error = got_worktree_set_base_commit_id(worktree, repo,
7243 commit_id);
7244 if (error)
7245 goto done;
7246 memset(&upa, 0, sizeof(upa));
7247 error = got_worktree_checkout_files(worktree, &paths,
7248 repo, update_progress, &upa, check_cancelled,
7249 NULL);
7250 if (error)
7251 goto done;
7252 if (upa.did_something) {
7253 printf("Updated to %s: %s\n",
7254 got_worktree_get_head_ref_name(worktree),
7255 commit_id_str);
7257 print_update_progress_stats(&upa);
7260 done:
7261 free(keyword_idstr);
7262 if (ref)
7263 got_ref_close(ref);
7264 if (repo) {
7265 const struct got_error *close_err = got_repo_close(repo);
7266 if (error == NULL)
7267 error = close_err;
7269 if (worktree)
7270 got_worktree_close(worktree);
7271 if (pack_fds) {
7272 const struct got_error *pack_err =
7273 got_repo_pack_fds_close(pack_fds);
7274 if (error == NULL)
7275 error = pack_err;
7277 free(cwd);
7278 free(repo_path);
7279 free(commit_id);
7280 free(commit_id_str);
7281 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7282 return error;
7286 __dead static void
7287 usage_tag(void)
7289 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7290 "[-r repository-path] [-s signer-id] name\n", getprogname());
7291 exit(1);
7294 #if 0
7295 static const struct got_error *
7296 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7298 const struct got_error *err = NULL;
7299 struct got_reflist_entry *re, *se, *new;
7300 struct got_object_id *re_id, *se_id;
7301 struct got_tag_object *re_tag, *se_tag;
7302 time_t re_time, se_time;
7304 STAILQ_FOREACH(re, tags, entry) {
7305 se = STAILQ_FIRST(sorted);
7306 if (se == NULL) {
7307 err = got_reflist_entry_dup(&new, re);
7308 if (err)
7309 return err;
7310 STAILQ_INSERT_HEAD(sorted, new, entry);
7311 continue;
7312 } else {
7313 err = got_ref_resolve(&re_id, repo, re->ref);
7314 if (err)
7315 break;
7316 err = got_object_open_as_tag(&re_tag, repo, re_id);
7317 free(re_id);
7318 if (err)
7319 break;
7320 re_time = got_object_tag_get_tagger_time(re_tag);
7321 got_object_tag_close(re_tag);
7324 while (se) {
7325 err = got_ref_resolve(&se_id, repo, re->ref);
7326 if (err)
7327 break;
7328 err = got_object_open_as_tag(&se_tag, repo, se_id);
7329 free(se_id);
7330 if (err)
7331 break;
7332 se_time = got_object_tag_get_tagger_time(se_tag);
7333 got_object_tag_close(se_tag);
7335 if (se_time > re_time) {
7336 err = got_reflist_entry_dup(&new, re);
7337 if (err)
7338 return err;
7339 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7340 break;
7342 se = STAILQ_NEXT(se, entry);
7343 continue;
7346 done:
7347 return err;
7349 #endif
7351 static const struct got_error *
7352 get_tag_refname(char **refname, const char *tag_name)
7354 const struct got_error *err;
7356 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7357 *refname = strdup(tag_name);
7358 if (*refname == NULL)
7359 return got_error_from_errno("strdup");
7360 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7361 err = got_error_from_errno("asprintf");
7362 *refname = NULL;
7363 return err;
7366 return NULL;
7369 static const struct got_error *
7370 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7371 const char *allowed_signers, const char *revoked_signers, int verbosity)
7373 static const struct got_error *err = NULL;
7374 struct got_reflist_head refs;
7375 struct got_reflist_entry *re;
7376 char *wanted_refname = NULL;
7377 int bad_sigs = 0;
7379 TAILQ_INIT(&refs);
7381 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7382 if (err)
7383 return err;
7385 if (tag_name) {
7386 struct got_reference *ref;
7387 err = get_tag_refname(&wanted_refname, tag_name);
7388 if (err)
7389 goto done;
7390 /* Wanted tag reference should exist. */
7391 err = got_ref_open(&ref, repo, wanted_refname, 0);
7392 if (err)
7393 goto done;
7394 got_ref_close(ref);
7397 TAILQ_FOREACH(re, &refs, entry) {
7398 const char *refname;
7399 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7400 char datebuf[26];
7401 const char *tagger, *ssh_sig = NULL;
7402 char *sig_msg = NULL;
7403 time_t tagger_time;
7404 struct got_object_id *id;
7405 struct got_tag_object *tag;
7406 struct got_commit_object *commit = NULL;
7408 refname = got_ref_get_name(re->ref);
7409 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7410 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7411 continue;
7412 refname += 10;
7413 refstr = got_ref_to_str(re->ref);
7414 if (refstr == NULL) {
7415 err = got_error_from_errno("got_ref_to_str");
7416 break;
7419 err = got_ref_resolve(&id, repo, re->ref);
7420 if (err)
7421 break;
7422 err = got_object_open_as_tag(&tag, repo, id);
7423 if (err) {
7424 if (err->code != GOT_ERR_OBJ_TYPE) {
7425 free(id);
7426 break;
7428 /* "lightweight" tag */
7429 err = got_object_open_as_commit(&commit, repo, id);
7430 if (err) {
7431 free(id);
7432 break;
7434 tagger = got_object_commit_get_committer(commit);
7435 tagger_time =
7436 got_object_commit_get_committer_time(commit);
7437 err = got_object_id_str(&id_str, id);
7438 free(id);
7439 if (err)
7440 break;
7441 } else {
7442 free(id);
7443 tagger = got_object_tag_get_tagger(tag);
7444 tagger_time = got_object_tag_get_tagger_time(tag);
7445 err = got_object_id_str(&id_str,
7446 got_object_tag_get_object_id(tag));
7447 if (err)
7448 break;
7451 if (tag && verify_tags) {
7452 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7453 got_object_tag_get_message(tag));
7454 if (ssh_sig && allowed_signers == NULL) {
7455 err = got_error_msg(
7456 GOT_ERR_VERIFY_TAG_SIGNATURE,
7457 "SSH signature verification requires "
7458 "setting allowed_signers in "
7459 "got.conf(5)");
7460 break;
7464 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7465 free(refstr);
7466 printf("from: %s\n", tagger);
7467 datestr = get_datestr(&tagger_time, datebuf);
7468 if (datestr)
7469 printf("date: %s UTC\n", datestr);
7470 if (commit)
7471 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7472 else {
7473 switch (got_object_tag_get_object_type(tag)) {
7474 case GOT_OBJ_TYPE_BLOB:
7475 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7476 id_str);
7477 break;
7478 case GOT_OBJ_TYPE_TREE:
7479 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7480 id_str);
7481 break;
7482 case GOT_OBJ_TYPE_COMMIT:
7483 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7484 id_str);
7485 break;
7486 case GOT_OBJ_TYPE_TAG:
7487 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7488 id_str);
7489 break;
7490 default:
7491 break;
7494 free(id_str);
7496 if (ssh_sig) {
7497 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7498 allowed_signers, revoked_signers, verbosity);
7499 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7500 bad_sigs = 1;
7501 else if (err)
7502 break;
7503 printf("signature: %s", sig_msg);
7504 free(sig_msg);
7505 sig_msg = NULL;
7508 if (commit) {
7509 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7510 if (err)
7511 break;
7512 got_object_commit_close(commit);
7513 } else {
7514 tagmsg0 = strdup(got_object_tag_get_message(tag));
7515 got_object_tag_close(tag);
7516 if (tagmsg0 == NULL) {
7517 err = got_error_from_errno("strdup");
7518 break;
7522 tagmsg = tagmsg0;
7523 do {
7524 line = strsep(&tagmsg, "\n");
7525 if (line)
7526 printf(" %s\n", line);
7527 } while (line);
7528 free(tagmsg0);
7530 done:
7531 got_ref_list_free(&refs);
7532 free(wanted_refname);
7534 if (err == NULL && bad_sigs)
7535 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7536 return err;
7539 static const struct got_error *
7540 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7541 const char *tag_name, const char *repo_path)
7543 const struct got_error *err = NULL;
7544 char *template = NULL, *initial_content = NULL;
7545 char *editor = NULL;
7546 int initial_content_len;
7547 int fd = -1;
7549 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7550 err = got_error_from_errno("asprintf");
7551 goto done;
7554 initial_content_len = asprintf(&initial_content,
7555 "\n# tagging commit %s as %s\n",
7556 commit_id_str, tag_name);
7557 if (initial_content_len == -1) {
7558 err = got_error_from_errno("asprintf");
7559 goto done;
7562 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7563 if (err)
7564 goto done;
7566 if (write(fd, initial_content, initial_content_len) == -1) {
7567 err = got_error_from_errno2("write", *tagmsg_path);
7568 goto done;
7570 if (close(fd) == -1) {
7571 err = got_error_from_errno2("close", *tagmsg_path);
7572 goto done;
7574 fd = -1;
7576 err = get_editor(&editor);
7577 if (err)
7578 goto done;
7579 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7580 initial_content_len, 1);
7581 done:
7582 free(initial_content);
7583 free(template);
7584 free(editor);
7586 if (fd != -1 && close(fd) == -1 && err == NULL)
7587 err = got_error_from_errno2("close", *tagmsg_path);
7589 if (err) {
7590 free(*tagmsg);
7591 *tagmsg = NULL;
7593 return err;
7596 static const struct got_error *
7597 add_tag(struct got_repository *repo, const char *tagger,
7598 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7599 const char *signer_id, int verbosity)
7601 const struct got_error *err = NULL;
7602 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7603 char *label = NULL, *commit_id_str = NULL;
7604 struct got_reference *ref = NULL;
7605 char *refname = NULL, *tagmsg = NULL;
7606 char *tagmsg_path = NULL, *tag_id_str = NULL;
7607 int preserve_tagmsg = 0;
7608 struct got_reflist_head refs;
7610 TAILQ_INIT(&refs);
7613 * Don't let the user create a tag name with a leading '-'.
7614 * While technically a valid reference name, this case is usually
7615 * an unintended typo.
7617 if (tag_name[0] == '-')
7618 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7620 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7621 if (err)
7622 goto done;
7624 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7625 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7626 if (err)
7627 goto done;
7629 err = got_object_id_str(&commit_id_str, commit_id);
7630 if (err)
7631 goto done;
7633 err = get_tag_refname(&refname, tag_name);
7634 if (err)
7635 goto done;
7636 if (strncmp("refs/tags/", tag_name, 10) == 0)
7637 tag_name += 10;
7639 err = got_ref_open(&ref, repo, refname, 0);
7640 if (err == NULL) {
7641 err = got_error(GOT_ERR_TAG_EXISTS);
7642 goto done;
7643 } else if (err->code != GOT_ERR_NOT_REF)
7644 goto done;
7646 if (tagmsg_arg == NULL) {
7647 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7648 tag_name, got_repo_get_path(repo));
7649 if (err) {
7650 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7651 tagmsg_path != NULL)
7652 preserve_tagmsg = 1;
7653 goto done;
7655 /* Editor is done; we can now apply unveil(2) */
7656 err = got_sigs_apply_unveil();
7657 if (err)
7658 goto done;
7659 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7660 if (err)
7661 goto done;
7664 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7665 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7666 verbosity);
7667 if (err) {
7668 if (tagmsg_path)
7669 preserve_tagmsg = 1;
7670 goto done;
7673 err = got_ref_alloc(&ref, refname, tag_id);
7674 if (err) {
7675 if (tagmsg_path)
7676 preserve_tagmsg = 1;
7677 goto done;
7680 err = got_ref_write(ref, repo);
7681 if (err) {
7682 if (tagmsg_path)
7683 preserve_tagmsg = 1;
7684 goto done;
7687 err = got_object_id_str(&tag_id_str, tag_id);
7688 if (err) {
7689 if (tagmsg_path)
7690 preserve_tagmsg = 1;
7691 goto done;
7693 printf("Created tag %s\n", tag_id_str);
7694 done:
7695 if (preserve_tagmsg) {
7696 fprintf(stderr, "%s: tag message preserved in %s\n",
7697 getprogname(), tagmsg_path);
7698 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7699 err = got_error_from_errno2("unlink", tagmsg_path);
7700 free(tag_id_str);
7701 if (ref)
7702 got_ref_close(ref);
7703 free(commit_id);
7704 free(commit_id_str);
7705 free(refname);
7706 free(tagmsg);
7707 free(tagmsg_path);
7708 got_ref_list_free(&refs);
7709 return err;
7712 static const struct got_error *
7713 cmd_tag(int argc, char *argv[])
7715 const struct got_error *error = NULL;
7716 struct got_repository *repo = NULL;
7717 struct got_worktree *worktree = NULL;
7718 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7719 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7720 char *allowed_signers = NULL, *revoked_signers = NULL;
7721 const char *signer_id = NULL;
7722 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7723 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7724 int *pack_fds = NULL;
7726 #ifndef PROFILE
7727 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7728 "sendfd unveil", NULL) == -1)
7729 err(1, "pledge");
7730 #endif
7732 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7733 switch (ch) {
7734 case 'c':
7735 commit_id_arg = optarg;
7736 break;
7737 case 'l':
7738 do_list = 1;
7739 break;
7740 case 'm':
7741 tagmsg = optarg;
7742 break;
7743 case 'r':
7744 repo_path = realpath(optarg, NULL);
7745 if (repo_path == NULL) {
7746 error = got_error_from_errno2("realpath",
7747 optarg);
7748 goto done;
7750 got_path_strip_trailing_slashes(repo_path);
7751 break;
7752 case 's':
7753 signer_id = optarg;
7754 break;
7755 case 'V':
7756 verify_tags = 1;
7757 break;
7758 case 'v':
7759 if (verbosity < 0)
7760 verbosity = 0;
7761 else if (verbosity < 3)
7762 verbosity++;
7763 break;
7764 default:
7765 usage_tag();
7766 /* NOTREACHED */
7770 argc -= optind;
7771 argv += optind;
7773 if (do_list || verify_tags) {
7774 if (commit_id_arg != NULL)
7775 errx(1,
7776 "-c option can only be used when creating a tag");
7777 if (tagmsg) {
7778 if (do_list)
7779 option_conflict('l', 'm');
7780 else
7781 option_conflict('V', 'm');
7783 if (signer_id) {
7784 if (do_list)
7785 option_conflict('l', 's');
7786 else
7787 option_conflict('V', 's');
7789 if (argc > 1)
7790 usage_tag();
7791 } else if (argc != 1)
7792 usage_tag();
7794 if (argc == 1)
7795 tag_name = argv[0];
7797 cwd = getcwd(NULL, 0);
7798 if (cwd == NULL) {
7799 error = got_error_from_errno("getcwd");
7800 goto done;
7803 error = got_repo_pack_fds_open(&pack_fds);
7804 if (error != NULL)
7805 goto done;
7807 if (repo_path == NULL) {
7808 error = got_worktree_open(&worktree, cwd,
7809 GOT_WORKTREE_GOT_DIR);
7810 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7811 goto done;
7812 else
7813 error = NULL;
7814 if (worktree) {
7815 repo_path =
7816 strdup(got_worktree_get_repo_path(worktree));
7817 if (repo_path == NULL)
7818 error = got_error_from_errno("strdup");
7819 if (error)
7820 goto done;
7821 } else {
7822 repo_path = strdup(cwd);
7823 if (repo_path == NULL) {
7824 error = got_error_from_errno("strdup");
7825 goto done;
7830 if (do_list || verify_tags) {
7831 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7832 if (error != NULL)
7833 goto done;
7834 error = get_allowed_signers(&allowed_signers, repo, worktree);
7835 if (error)
7836 goto done;
7837 error = get_revoked_signers(&revoked_signers, repo, worktree);
7838 if (error)
7839 goto done;
7840 if (worktree) {
7841 /* Release work tree lock. */
7842 got_worktree_close(worktree);
7843 worktree = NULL;
7847 * Remove "cpath" promise unless needed for signature tmpfile
7848 * creation.
7850 if (verify_tags)
7851 got_sigs_apply_unveil();
7852 else {
7853 #ifndef PROFILE
7854 if (pledge("stdio rpath wpath flock proc exec sendfd "
7855 "unveil", NULL) == -1)
7856 err(1, "pledge");
7857 #endif
7859 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7860 if (error)
7861 goto done;
7862 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7863 revoked_signers, verbosity);
7864 } else {
7865 error = get_gitconfig_path(&gitconfig_path);
7866 if (error)
7867 goto done;
7868 error = got_repo_open(&repo, repo_path, gitconfig_path,
7869 pack_fds);
7870 if (error != NULL)
7871 goto done;
7873 error = get_author(&tagger, repo, worktree);
7874 if (error)
7875 goto done;
7876 if (signer_id == NULL)
7877 signer_id = get_signer_id(repo, worktree);
7879 if (tagmsg) {
7880 if (signer_id) {
7881 error = got_sigs_apply_unveil();
7882 if (error)
7883 goto done;
7885 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7886 if (error)
7887 goto done;
7890 if (commit_id_arg == NULL) {
7891 struct got_reference *head_ref;
7892 struct got_object_id *commit_id;
7893 error = got_ref_open(&head_ref, repo,
7894 worktree ? got_worktree_get_head_ref_name(worktree)
7895 : GOT_REF_HEAD, 0);
7896 if (error)
7897 goto done;
7898 error = got_ref_resolve(&commit_id, repo, head_ref);
7899 got_ref_close(head_ref);
7900 if (error)
7901 goto done;
7902 error = got_object_id_str(&commit_id_str, commit_id);
7903 free(commit_id);
7904 if (error)
7905 goto done;
7906 } else {
7907 error = got_keyword_to_idstr(&keyword_idstr,
7908 commit_id_arg, repo, worktree);
7909 if (error != NULL)
7910 goto done;
7911 commit_id_str = keyword_idstr;
7914 if (worktree) {
7915 /* Release work tree lock. */
7916 got_worktree_close(worktree);
7917 worktree = NULL;
7920 error = add_tag(repo, tagger, tag_name,
7921 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7922 signer_id, verbosity);
7924 done:
7925 if (repo) {
7926 const struct got_error *close_err = got_repo_close(repo);
7927 if (error == NULL)
7928 error = close_err;
7930 if (worktree)
7931 got_worktree_close(worktree);
7932 if (pack_fds) {
7933 const struct got_error *pack_err =
7934 got_repo_pack_fds_close(pack_fds);
7935 if (error == NULL)
7936 error = pack_err;
7938 free(cwd);
7939 free(repo_path);
7940 free(gitconfig_path);
7941 free(commit_id_str);
7942 free(tagger);
7943 free(allowed_signers);
7944 free(revoked_signers);
7945 return error;
7948 __dead static void
7949 usage_add(void)
7951 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7952 exit(1);
7955 static const struct got_error *
7956 add_progress(void *arg, unsigned char status, const char *path)
7958 while (path[0] == '/')
7959 path++;
7960 printf("%c %s\n", status, path);
7961 return NULL;
7964 static const struct got_error *
7965 cmd_add(int argc, char *argv[])
7967 const struct got_error *error = NULL;
7968 struct got_repository *repo = NULL;
7969 struct got_worktree *worktree = NULL;
7970 char *cwd = NULL;
7971 struct got_pathlist_head paths;
7972 struct got_pathlist_entry *pe;
7973 int ch, can_recurse = 0, no_ignores = 0;
7974 int *pack_fds = NULL;
7976 TAILQ_INIT(&paths);
7978 #ifndef PROFILE
7979 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7980 NULL) == -1)
7981 err(1, "pledge");
7982 #endif
7984 while ((ch = getopt(argc, argv, "IR")) != -1) {
7985 switch (ch) {
7986 case 'I':
7987 no_ignores = 1;
7988 break;
7989 case 'R':
7990 can_recurse = 1;
7991 break;
7992 default:
7993 usage_add();
7994 /* NOTREACHED */
7998 argc -= optind;
7999 argv += optind;
8001 if (argc < 1)
8002 usage_add();
8004 cwd = getcwd(NULL, 0);
8005 if (cwd == NULL) {
8006 error = got_error_from_errno("getcwd");
8007 goto done;
8010 error = got_repo_pack_fds_open(&pack_fds);
8011 if (error != NULL)
8012 goto done;
8014 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8015 if (error) {
8016 if (error->code == GOT_ERR_NOT_WORKTREE)
8017 error = wrap_not_worktree_error(error, "add", cwd);
8018 goto done;
8021 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8022 NULL, pack_fds);
8023 if (error != NULL)
8024 goto done;
8026 error = apply_unveil(got_repo_get_path(repo), 1,
8027 got_worktree_get_root_path(worktree));
8028 if (error)
8029 goto done;
8031 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8032 if (error)
8033 goto done;
8035 if (!can_recurse) {
8036 char *ondisk_path;
8037 struct stat sb;
8038 TAILQ_FOREACH(pe, &paths, entry) {
8039 if (asprintf(&ondisk_path, "%s/%s",
8040 got_worktree_get_root_path(worktree),
8041 pe->path) == -1) {
8042 error = got_error_from_errno("asprintf");
8043 goto done;
8045 if (lstat(ondisk_path, &sb) == -1) {
8046 if (errno == ENOENT) {
8047 free(ondisk_path);
8048 continue;
8050 error = got_error_from_errno2("lstat",
8051 ondisk_path);
8052 free(ondisk_path);
8053 goto done;
8055 free(ondisk_path);
8056 if (S_ISDIR(sb.st_mode)) {
8057 error = got_error_msg(GOT_ERR_BAD_PATH,
8058 "adding directories requires -R option");
8059 goto done;
8064 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8065 NULL, repo, no_ignores);
8066 done:
8067 if (repo) {
8068 const struct got_error *close_err = got_repo_close(repo);
8069 if (error == NULL)
8070 error = close_err;
8072 if (worktree)
8073 got_worktree_close(worktree);
8074 if (pack_fds) {
8075 const struct got_error *pack_err =
8076 got_repo_pack_fds_close(pack_fds);
8077 if (error == NULL)
8078 error = pack_err;
8080 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8081 free(cwd);
8082 return error;
8085 __dead static void
8086 usage_remove(void)
8088 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8089 getprogname());
8090 exit(1);
8093 static const struct got_error *
8094 print_remove_status(void *arg, unsigned char status,
8095 unsigned char staged_status, const char *path)
8097 while (path[0] == '/')
8098 path++;
8099 if (status == GOT_STATUS_NONEXISTENT)
8100 return NULL;
8101 if (status == staged_status && (status == GOT_STATUS_DELETE))
8102 status = GOT_STATUS_NO_CHANGE;
8103 printf("%c%c %s\n", status, staged_status, path);
8104 return NULL;
8107 static const struct got_error *
8108 cmd_remove(int argc, char *argv[])
8110 const struct got_error *error = NULL;
8111 struct got_worktree *worktree = NULL;
8112 struct got_repository *repo = NULL;
8113 const char *status_codes = NULL;
8114 char *cwd = NULL;
8115 struct got_pathlist_head paths;
8116 struct got_pathlist_entry *pe;
8117 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8118 int ignore_missing_paths = 0;
8119 int *pack_fds = NULL;
8121 TAILQ_INIT(&paths);
8123 #ifndef PROFILE
8124 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8125 NULL) == -1)
8126 err(1, "pledge");
8127 #endif
8129 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8130 switch (ch) {
8131 case 'f':
8132 delete_local_mods = 1;
8133 ignore_missing_paths = 1;
8134 break;
8135 case 'k':
8136 keep_on_disk = 1;
8137 break;
8138 case 'R':
8139 can_recurse = 1;
8140 break;
8141 case 's':
8142 for (i = 0; optarg[i] != '\0'; i++) {
8143 switch (optarg[i]) {
8144 case GOT_STATUS_MODIFY:
8145 delete_local_mods = 1;
8146 break;
8147 case GOT_STATUS_MISSING:
8148 ignore_missing_paths = 1;
8149 break;
8150 default:
8151 errx(1, "invalid status code '%c'",
8152 optarg[i]);
8155 status_codes = optarg;
8156 break;
8157 default:
8158 usage_remove();
8159 /* NOTREACHED */
8163 argc -= optind;
8164 argv += optind;
8166 if (argc < 1)
8167 usage_remove();
8169 cwd = getcwd(NULL, 0);
8170 if (cwd == NULL) {
8171 error = got_error_from_errno("getcwd");
8172 goto done;
8175 error = got_repo_pack_fds_open(&pack_fds);
8176 if (error != NULL)
8177 goto done;
8179 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8180 if (error) {
8181 if (error->code == GOT_ERR_NOT_WORKTREE)
8182 error = wrap_not_worktree_error(error, "remove", cwd);
8183 goto done;
8186 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8187 NULL, pack_fds);
8188 if (error)
8189 goto done;
8191 error = apply_unveil(got_repo_get_path(repo), 1,
8192 got_worktree_get_root_path(worktree));
8193 if (error)
8194 goto done;
8196 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8197 if (error)
8198 goto done;
8200 if (!can_recurse) {
8201 char *ondisk_path;
8202 struct stat sb;
8203 TAILQ_FOREACH(pe, &paths, entry) {
8204 if (asprintf(&ondisk_path, "%s/%s",
8205 got_worktree_get_root_path(worktree),
8206 pe->path) == -1) {
8207 error = got_error_from_errno("asprintf");
8208 goto done;
8210 if (lstat(ondisk_path, &sb) == -1) {
8211 if (errno == ENOENT) {
8212 free(ondisk_path);
8213 continue;
8215 error = got_error_from_errno2("lstat",
8216 ondisk_path);
8217 free(ondisk_path);
8218 goto done;
8220 free(ondisk_path);
8221 if (S_ISDIR(sb.st_mode)) {
8222 error = got_error_msg(GOT_ERR_BAD_PATH,
8223 "removing directories requires -R option");
8224 goto done;
8229 error = got_worktree_schedule_delete(worktree, &paths,
8230 delete_local_mods, status_codes, print_remove_status, NULL,
8231 repo, keep_on_disk, ignore_missing_paths);
8232 done:
8233 if (repo) {
8234 const struct got_error *close_err = got_repo_close(repo);
8235 if (error == NULL)
8236 error = close_err;
8238 if (worktree)
8239 got_worktree_close(worktree);
8240 if (pack_fds) {
8241 const struct got_error *pack_err =
8242 got_repo_pack_fds_close(pack_fds);
8243 if (error == NULL)
8244 error = pack_err;
8246 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8247 free(cwd);
8248 return error;
8251 __dead static void
8252 usage_patch(void)
8254 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8255 "[patchfile]\n", getprogname());
8256 exit(1);
8259 static const struct got_error *
8260 patch_from_stdin(int *patchfd)
8262 const struct got_error *err = NULL;
8263 ssize_t r;
8264 char buf[BUFSIZ];
8265 sig_t sighup, sigint, sigquit;
8267 *patchfd = got_opentempfd();
8268 if (*patchfd == -1)
8269 return got_error_from_errno("got_opentempfd");
8271 sighup = signal(SIGHUP, SIG_DFL);
8272 sigint = signal(SIGINT, SIG_DFL);
8273 sigquit = signal(SIGQUIT, SIG_DFL);
8275 for (;;) {
8276 r = read(0, buf, sizeof(buf));
8277 if (r == -1) {
8278 err = got_error_from_errno("read");
8279 break;
8281 if (r == 0)
8282 break;
8283 if (write(*patchfd, buf, r) == -1) {
8284 err = got_error_from_errno("write");
8285 break;
8289 signal(SIGHUP, sighup);
8290 signal(SIGINT, sigint);
8291 signal(SIGQUIT, sigquit);
8293 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8294 err = got_error_from_errno("lseek");
8296 if (err != NULL) {
8297 close(*patchfd);
8298 *patchfd = -1;
8301 return err;
8304 struct got_patch_progress_arg {
8305 int did_something;
8306 int conflicts;
8307 int rejects;
8310 static const struct got_error *
8311 patch_progress(void *arg, const char *old, const char *new,
8312 unsigned char status, const struct got_error *error, int old_from,
8313 int old_lines, int new_from, int new_lines, int offset,
8314 int ws_mangled, const struct got_error *hunk_err)
8316 const char *path = new == NULL ? old : new;
8317 struct got_patch_progress_arg *a = arg;
8319 while (*path == '/')
8320 path++;
8322 if (status != GOT_STATUS_NO_CHANGE &&
8323 status != 0 /* per-hunk progress */) {
8324 printf("%c %s\n", status, path);
8325 a->did_something = 1;
8328 if (hunk_err == NULL) {
8329 if (status == GOT_STATUS_CANNOT_UPDATE)
8330 a->rejects++;
8331 else if (status == GOT_STATUS_CONFLICT)
8332 a->conflicts++;
8335 if (error != NULL)
8336 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8338 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8339 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8340 old_lines, new_from, new_lines);
8341 if (hunk_err != NULL)
8342 printf("%s\n", hunk_err->msg);
8343 else if (offset != 0)
8344 printf("applied with offset %d\n", offset);
8345 else
8346 printf("hunk contains mangled whitespace\n");
8349 return NULL;
8352 static void
8353 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8355 if (!ppa->did_something)
8356 return;
8358 if (ppa->conflicts > 0)
8359 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8361 if (ppa->rejects > 0) {
8362 printf("Files where patch failed to apply: %d\n",
8363 ppa->rejects);
8367 static const struct got_error *
8368 cmd_patch(int argc, char *argv[])
8370 const struct got_error *error = NULL, *close_error = NULL;
8371 struct got_worktree *worktree = NULL;
8372 struct got_repository *repo = NULL;
8373 struct got_reflist_head refs;
8374 struct got_object_id *commit_id = NULL;
8375 const char *commit_id_str = NULL;
8376 struct stat sb;
8377 const char *errstr;
8378 char *cwd = NULL, *keyword_idstr = NULL;
8379 int ch, nop = 0, strip = -1, reverse = 0;
8380 int patchfd;
8381 int *pack_fds = NULL;
8382 struct got_patch_progress_arg ppa;
8384 TAILQ_INIT(&refs);
8386 #ifndef PROFILE
8387 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8388 "unveil", NULL) == -1)
8389 err(1, "pledge");
8390 #endif
8392 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8393 switch (ch) {
8394 case 'c':
8395 commit_id_str = optarg;
8396 break;
8397 case 'n':
8398 nop = 1;
8399 break;
8400 case 'p':
8401 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8402 if (errstr != NULL)
8403 errx(1, "pathname strip count is %s: %s",
8404 errstr, optarg);
8405 break;
8406 case 'R':
8407 reverse = 1;
8408 break;
8409 default:
8410 usage_patch();
8411 /* NOTREACHED */
8415 argc -= optind;
8416 argv += optind;
8418 if (argc == 0) {
8419 error = patch_from_stdin(&patchfd);
8420 if (error)
8421 return error;
8422 } else if (argc == 1) {
8423 patchfd = open(argv[0], O_RDONLY);
8424 if (patchfd == -1) {
8425 error = got_error_from_errno2("open", argv[0]);
8426 return error;
8428 if (fstat(patchfd, &sb) == -1) {
8429 error = got_error_from_errno2("fstat", argv[0]);
8430 goto done;
8432 if (!S_ISREG(sb.st_mode)) {
8433 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8434 goto done;
8436 } else
8437 usage_patch();
8439 if ((cwd = getcwd(NULL, 0)) == NULL) {
8440 error = got_error_from_errno("getcwd");
8441 goto done;
8444 error = got_repo_pack_fds_open(&pack_fds);
8445 if (error != NULL)
8446 goto done;
8448 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8449 if (error != NULL)
8450 goto done;
8452 const char *repo_path = got_worktree_get_repo_path(worktree);
8453 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8454 if (error != NULL)
8455 goto done;
8457 error = apply_unveil(got_repo_get_path(repo), 0,
8458 got_worktree_get_root_path(worktree));
8459 if (error != NULL)
8460 goto done;
8462 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8463 if (error)
8464 goto done;
8466 if (commit_id_str != NULL) {
8467 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8468 repo, worktree);
8469 if (error != NULL)
8470 goto done;
8472 error = got_repo_match_object_id(&commit_id, NULL,
8473 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8474 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8475 if (error)
8476 goto done;
8479 memset(&ppa, 0, sizeof(ppa));
8480 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8481 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8482 print_patch_progress_stats(&ppa);
8483 done:
8484 got_ref_list_free(&refs);
8485 free(keyword_idstr);
8486 free(commit_id);
8487 if (repo) {
8488 close_error = got_repo_close(repo);
8489 if (error == NULL)
8490 error = close_error;
8492 if (worktree != NULL) {
8493 close_error = got_worktree_close(worktree);
8494 if (error == NULL)
8495 error = close_error;
8497 if (pack_fds) {
8498 const struct got_error *pack_err =
8499 got_repo_pack_fds_close(pack_fds);
8500 if (error == NULL)
8501 error = pack_err;
8503 free(cwd);
8504 return error;
8507 __dead static void
8508 usage_revert(void)
8510 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8511 getprogname());
8512 exit(1);
8515 static const struct got_error *
8516 revert_progress(void *arg, unsigned char status, const char *path)
8518 if (status == GOT_STATUS_UNVERSIONED)
8519 return NULL;
8521 while (path[0] == '/')
8522 path++;
8523 printf("%c %s\n", status, path);
8524 return NULL;
8527 struct choose_patch_arg {
8528 FILE *patch_script_file;
8529 const char *action;
8532 static const struct got_error *
8533 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8534 int nchanges, const char *action)
8536 const struct got_error *err;
8537 char *line = NULL;
8538 size_t linesize = 0;
8539 ssize_t linelen;
8541 switch (status) {
8542 case GOT_STATUS_ADD:
8543 printf("A %s\n%s this addition? [y/n] ", path, action);
8544 break;
8545 case GOT_STATUS_DELETE:
8546 printf("D %s\n%s this deletion? [y/n] ", path, action);
8547 break;
8548 case GOT_STATUS_MODIFY:
8549 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8550 return got_error_from_errno("fseek");
8551 printf(GOT_COMMIT_SEP_STR);
8552 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8553 printf("%s", line);
8554 if (linelen == -1 && ferror(patch_file)) {
8555 err = got_error_from_errno("getline");
8556 free(line);
8557 return err;
8559 free(line);
8560 printf(GOT_COMMIT_SEP_STR);
8561 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8562 path, n, nchanges, action);
8563 break;
8564 default:
8565 return got_error_path(path, GOT_ERR_FILE_STATUS);
8568 fflush(stdout);
8569 return NULL;
8572 static const struct got_error *
8573 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8574 FILE *patch_file, int n, int nchanges)
8576 const struct got_error *err = NULL;
8577 char *line = NULL;
8578 size_t linesize = 0;
8579 ssize_t linelen;
8580 int resp = ' ';
8581 struct choose_patch_arg *a = arg;
8583 *choice = GOT_PATCH_CHOICE_NONE;
8585 if (a->patch_script_file) {
8586 char *nl;
8587 err = show_change(status, path, patch_file, n, nchanges,
8588 a->action);
8589 if (err)
8590 return err;
8591 linelen = getline(&line, &linesize, a->patch_script_file);
8592 if (linelen == -1) {
8593 if (ferror(a->patch_script_file))
8594 return got_error_from_errno("getline");
8595 return NULL;
8597 nl = strchr(line, '\n');
8598 if (nl)
8599 *nl = '\0';
8600 if (strcmp(line, "y") == 0) {
8601 *choice = GOT_PATCH_CHOICE_YES;
8602 printf("y\n");
8603 } else if (strcmp(line, "n") == 0) {
8604 *choice = GOT_PATCH_CHOICE_NO;
8605 printf("n\n");
8606 } else if (strcmp(line, "q") == 0 &&
8607 status == GOT_STATUS_MODIFY) {
8608 *choice = GOT_PATCH_CHOICE_QUIT;
8609 printf("q\n");
8610 } else
8611 printf("invalid response '%s'\n", line);
8612 free(line);
8613 return NULL;
8616 while (resp != 'y' && resp != 'n' && resp != 'q') {
8617 err = show_change(status, path, patch_file, n, nchanges,
8618 a->action);
8619 if (err)
8620 return err;
8621 resp = getchar();
8622 if (resp == '\n')
8623 resp = getchar();
8624 if (status == GOT_STATUS_MODIFY) {
8625 if (resp != 'y' && resp != 'n' && resp != 'q') {
8626 printf("invalid response '%c'\n", resp);
8627 resp = ' ';
8629 } else if (resp != 'y' && resp != 'n') {
8630 printf("invalid response '%c'\n", resp);
8631 resp = ' ';
8635 if (resp == 'y')
8636 *choice = GOT_PATCH_CHOICE_YES;
8637 else if (resp == 'n')
8638 *choice = GOT_PATCH_CHOICE_NO;
8639 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8640 *choice = GOT_PATCH_CHOICE_QUIT;
8642 return NULL;
8645 struct wt_commitable_path_arg {
8646 struct got_pathlist_head *commit_paths;
8647 int *has_changes;
8651 * Shortcut work tree status callback to determine if the set of paths scanned
8652 * has at least one versioned path that is being modified and, if not NULL, is
8653 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8654 * soon as a path is passed with a status that satisfies this criteria.
8656 static const struct got_error *
8657 worktree_has_commitable_path(void *arg, unsigned char status,
8658 unsigned char staged_status, const char *path,
8659 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8660 struct got_object_id *commit_id, int dirfd, const char *de_name)
8662 struct wt_commitable_path_arg *a = arg;
8664 if (status == staged_status && (status == GOT_STATUS_DELETE))
8665 status = GOT_STATUS_NO_CHANGE;
8667 if (!(status == GOT_STATUS_NO_CHANGE ||
8668 status == GOT_STATUS_UNVERSIONED) ||
8669 staged_status != GOT_STATUS_NO_CHANGE) {
8670 if (a->commit_paths != NULL) {
8671 struct got_pathlist_entry *pe;
8673 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8674 if (strncmp(path, pe->path,
8675 pe->path_len) == 0) {
8676 *a->has_changes = 1;
8677 break;
8680 } else
8681 *a->has_changes = 1;
8683 if (*a->has_changes)
8684 return got_error(GOT_ERR_FILE_MODIFIED);
8687 return NULL;
8691 * Check that the changeset of the commit identified by id is
8692 * comprised of at least one modified path that is being committed.
8694 static const struct got_error *
8695 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8696 struct got_object_id *id, struct got_worktree *worktree,
8697 struct got_repository *repo)
8699 const struct got_error *err;
8700 struct got_pathlist_head paths;
8701 struct got_commit_object *commit = NULL, *pcommit = NULL;
8702 struct got_tree_object *tree = NULL, *ptree = NULL;
8703 struct got_object_qid *pid;
8705 TAILQ_INIT(&paths);
8707 err = got_object_open_as_commit(&commit, repo, id);
8708 if (err)
8709 goto done;
8711 err = got_object_open_as_tree(&tree, repo,
8712 got_object_commit_get_tree_id(commit));
8713 if (err)
8714 goto done;
8716 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8717 if (pid != NULL) {
8718 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8719 if (err)
8720 goto done;
8722 err = got_object_open_as_tree(&ptree, repo,
8723 got_object_commit_get_tree_id(pcommit));
8724 if (err)
8725 goto done;
8728 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8729 got_diff_tree_collect_changed_paths, &paths, 0);
8730 if (err)
8731 goto done;
8733 err = got_worktree_status(worktree, &paths, repo, 0,
8734 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8735 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8737 * At least one changed path in the referenced commit is
8738 * modified in the work tree, that's all we need to know!
8740 err = NULL;
8743 done:
8744 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8745 if (commit)
8746 got_object_commit_close(commit);
8747 if (pcommit)
8748 got_object_commit_close(pcommit);
8749 if (tree)
8750 got_object_tree_close(tree);
8751 if (ptree)
8752 got_object_tree_close(ptree);
8753 return err;
8757 * Remove any "logmsg" reference comprised entirely of paths that have
8758 * been reverted in this work tree. If any path in the logmsg ref changeset
8759 * remains in a changed state in the worktree, do not remove the reference.
8761 static const struct got_error *
8762 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8764 const struct got_error *err;
8765 struct got_reflist_head refs;
8766 struct got_reflist_entry *re;
8767 struct got_commit_object *commit = NULL;
8768 struct got_object_id *commit_id = NULL;
8769 struct wt_commitable_path_arg wcpa;
8770 char *uuidstr = NULL;
8772 TAILQ_INIT(&refs);
8774 err = got_worktree_get_uuid(&uuidstr, worktree);
8775 if (err)
8776 goto done;
8778 err = got_ref_list(&refs, repo, "refs/got/worktree",
8779 got_ref_cmp_by_name, repo);
8780 if (err)
8781 goto done;
8783 TAILQ_FOREACH(re, &refs, entry) {
8784 const char *refname;
8785 int has_changes = 0;
8787 refname = got_ref_get_name(re->ref);
8789 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8790 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8791 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8792 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8793 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8794 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8795 else
8796 continue;
8798 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8799 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8800 else
8801 continue;
8803 err = got_repo_match_object_id(&commit_id, NULL, refname,
8804 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8805 if (err)
8806 goto done;
8808 err = got_object_open_as_commit(&commit, repo, commit_id);
8809 if (err)
8810 goto done;
8812 wcpa.commit_paths = NULL;
8813 wcpa.has_changes = &has_changes;
8815 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8816 worktree, repo);
8817 if (err)
8818 goto done;
8820 if (!has_changes) {
8821 err = got_ref_delete(re->ref, repo);
8822 if (err)
8823 goto done;
8826 got_object_commit_close(commit);
8827 commit = NULL;
8828 free(commit_id);
8829 commit_id = NULL;
8832 done:
8833 free(uuidstr);
8834 free(commit_id);
8835 got_ref_list_free(&refs);
8836 if (commit)
8837 got_object_commit_close(commit);
8838 return err;
8841 static const struct got_error *
8842 cmd_revert(int argc, char *argv[])
8844 const struct got_error *error = NULL;
8845 struct got_worktree *worktree = NULL;
8846 struct got_repository *repo = NULL;
8847 char *cwd = NULL, *path = NULL;
8848 struct got_pathlist_head paths;
8849 struct got_pathlist_entry *pe;
8850 int ch, can_recurse = 0, pflag = 0;
8851 FILE *patch_script_file = NULL;
8852 const char *patch_script_path = NULL;
8853 struct choose_patch_arg cpa;
8854 int *pack_fds = NULL;
8856 TAILQ_INIT(&paths);
8858 #ifndef PROFILE
8859 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8860 "unveil", NULL) == -1)
8861 err(1, "pledge");
8862 #endif
8864 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8865 switch (ch) {
8866 case 'F':
8867 patch_script_path = optarg;
8868 break;
8869 case 'p':
8870 pflag = 1;
8871 break;
8872 case 'R':
8873 can_recurse = 1;
8874 break;
8875 default:
8876 usage_revert();
8877 /* NOTREACHED */
8881 argc -= optind;
8882 argv += optind;
8884 if (argc < 1)
8885 usage_revert();
8886 if (patch_script_path && !pflag)
8887 errx(1, "-F option can only be used together with -p option");
8889 cwd = getcwd(NULL, 0);
8890 if (cwd == NULL) {
8891 error = got_error_from_errno("getcwd");
8892 goto done;
8895 error = got_repo_pack_fds_open(&pack_fds);
8896 if (error != NULL)
8897 goto done;
8899 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8900 if (error) {
8901 if (error->code == GOT_ERR_NOT_WORKTREE)
8902 error = wrap_not_worktree_error(error, "revert", cwd);
8903 goto done;
8906 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8907 NULL, pack_fds);
8908 if (error != NULL)
8909 goto done;
8911 if (patch_script_path) {
8912 patch_script_file = fopen(patch_script_path, "re");
8913 if (patch_script_file == NULL) {
8914 error = got_error_from_errno2("fopen",
8915 patch_script_path);
8916 goto done;
8921 * XXX "c" perm needed on repo dir to delete merge references.
8923 error = apply_unveil(got_repo_get_path(repo), 0,
8924 got_worktree_get_root_path(worktree));
8925 if (error)
8926 goto done;
8928 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8929 if (error)
8930 goto done;
8932 if (!can_recurse) {
8933 char *ondisk_path;
8934 struct stat sb;
8935 TAILQ_FOREACH(pe, &paths, entry) {
8936 if (asprintf(&ondisk_path, "%s/%s",
8937 got_worktree_get_root_path(worktree),
8938 pe->path) == -1) {
8939 error = got_error_from_errno("asprintf");
8940 goto done;
8942 if (lstat(ondisk_path, &sb) == -1) {
8943 if (errno == ENOENT) {
8944 free(ondisk_path);
8945 continue;
8947 error = got_error_from_errno2("lstat",
8948 ondisk_path);
8949 free(ondisk_path);
8950 goto done;
8952 free(ondisk_path);
8953 if (S_ISDIR(sb.st_mode)) {
8954 error = got_error_msg(GOT_ERR_BAD_PATH,
8955 "reverting directories requires -R option");
8956 goto done;
8961 cpa.patch_script_file = patch_script_file;
8962 cpa.action = "revert";
8963 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8964 pflag ? choose_patch : NULL, &cpa, repo);
8966 error = rm_logmsg_ref(worktree, repo);
8967 done:
8968 if (patch_script_file && fclose(patch_script_file) == EOF &&
8969 error == NULL)
8970 error = got_error_from_errno2("fclose", patch_script_path);
8971 if (repo) {
8972 const struct got_error *close_err = got_repo_close(repo);
8973 if (error == NULL)
8974 error = close_err;
8976 if (worktree)
8977 got_worktree_close(worktree);
8978 if (pack_fds) {
8979 const struct got_error *pack_err =
8980 got_repo_pack_fds_close(pack_fds);
8981 if (error == NULL)
8982 error = pack_err;
8984 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8985 free(path);
8986 free(cwd);
8987 return error;
8990 __dead static void
8991 usage_commit(void)
8993 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8994 "[-m message] [path ...]\n", getprogname());
8995 exit(1);
8998 struct collect_commit_logmsg_arg {
8999 const char *cmdline_log;
9000 const char *prepared_log;
9001 const char *merged_log;
9002 int non_interactive;
9003 const char *editor;
9004 const char *worktree_path;
9005 const char *branch_name;
9006 const char *repo_path;
9007 char *logmsg_path;
9011 static const struct got_error *
9012 read_prepared_logmsg(char **logmsg, const char *path)
9014 const struct got_error *err = NULL;
9015 FILE *f = NULL;
9016 struct stat sb;
9017 size_t r;
9019 *logmsg = NULL;
9020 memset(&sb, 0, sizeof(sb));
9022 f = fopen(path, "re");
9023 if (f == NULL)
9024 return got_error_from_errno2("fopen", path);
9026 if (fstat(fileno(f), &sb) == -1) {
9027 err = got_error_from_errno2("fstat", path);
9028 goto done;
9030 if (sb.st_size == 0) {
9031 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9032 goto done;
9035 *logmsg = malloc(sb.st_size + 1);
9036 if (*logmsg == NULL) {
9037 err = got_error_from_errno("malloc");
9038 goto done;
9041 r = fread(*logmsg, 1, sb.st_size, f);
9042 if (r != sb.st_size) {
9043 if (ferror(f))
9044 err = got_error_from_errno2("fread", path);
9045 else
9046 err = got_error(GOT_ERR_IO);
9047 goto done;
9049 (*logmsg)[sb.st_size] = '\0';
9050 done:
9051 if (fclose(f) == EOF && err == NULL)
9052 err = got_error_from_errno2("fclose", path);
9053 if (err) {
9054 free(*logmsg);
9055 *logmsg = NULL;
9057 return err;
9060 static const struct got_error *
9061 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9062 const char *diff_path, char **logmsg, void *arg)
9064 char *initial_content = NULL;
9065 struct got_pathlist_entry *pe;
9066 const struct got_error *err = NULL;
9067 char *template = NULL;
9068 char *prepared_msg = NULL, *merged_msg = NULL;
9069 struct collect_commit_logmsg_arg *a = arg;
9070 int initial_content_len;
9071 int fd = -1;
9072 size_t len;
9074 /* if a message was specified on the command line, just use it */
9075 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9076 len = strlen(a->cmdline_log) + 1;
9077 *logmsg = malloc(len + 1);
9078 if (*logmsg == NULL)
9079 return got_error_from_errno("malloc");
9080 strlcpy(*logmsg, a->cmdline_log, len);
9081 return NULL;
9082 } else if (a->prepared_log != NULL && a->non_interactive)
9083 return read_prepared_logmsg(logmsg, a->prepared_log);
9085 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9086 return got_error_from_errno("asprintf");
9088 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9089 if (err)
9090 goto done;
9092 if (a->prepared_log) {
9093 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9094 if (err)
9095 goto done;
9096 } else if (a->merged_log) {
9097 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9098 if (err)
9099 goto done;
9102 initial_content_len = asprintf(&initial_content,
9103 "%s%s\n# changes to be committed on branch %s:\n",
9104 prepared_msg ? prepared_msg : "",
9105 merged_msg ? merged_msg : "", a->branch_name);
9106 if (initial_content_len == -1) {
9107 err = got_error_from_errno("asprintf");
9108 goto done;
9111 if (write(fd, initial_content, initial_content_len) == -1) {
9112 err = got_error_from_errno2("write", a->logmsg_path);
9113 goto done;
9116 TAILQ_FOREACH(pe, commitable_paths, entry) {
9117 struct got_commitable *ct = pe->data;
9118 dprintf(fd, "# %c %s\n",
9119 got_commitable_get_status(ct),
9120 got_commitable_get_path(ct));
9123 if (diff_path) {
9124 dprintf(fd, "# detailed changes can be viewed in %s\n",
9125 diff_path);
9128 if (close(fd) == -1) {
9129 err = got_error_from_errno2("close", a->logmsg_path);
9130 goto done;
9132 fd = -1;
9134 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9135 initial_content_len, a->prepared_log ? 0 : 1);
9136 done:
9137 free(initial_content);
9138 free(template);
9139 free(prepared_msg);
9140 free(merged_msg);
9142 if (fd != -1 && close(fd) == -1 && err == NULL)
9143 err = got_error_from_errno2("close", a->logmsg_path);
9145 /* Editor is done; we can now apply unveil(2) */
9146 if (err == NULL)
9147 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9148 if (err) {
9149 free(*logmsg);
9150 *logmsg = NULL;
9152 return err;
9155 static const struct got_error *
9156 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9157 const char *type, int has_content)
9159 const struct got_error *err = NULL;
9160 char *logmsg = NULL;
9162 err = got_object_commit_get_logmsg(&logmsg, commit);
9163 if (err)
9164 return err;
9166 if (fprintf(f, "%s# log message of %s commit %s:%s",
9167 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9168 err = got_ferror(f, GOT_ERR_IO);
9170 free(logmsg);
9171 return err;
9175 * Lookup "logmsg" references of backed-out and cherrypicked commits
9176 * belonging to the current work tree. If found, and the worktree has
9177 * at least one modified file that was changed in the referenced commit,
9178 * add its log message to a new temporary file at *logmsg_path.
9179 * Add all refs found to matched_refs to be scheduled for removal on
9180 * successful commit.
9182 static const struct got_error *
9183 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9184 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9185 struct got_repository *repo)
9187 const struct got_error *err;
9188 struct got_commit_object *commit = NULL;
9189 struct got_object_id *id = NULL;
9190 struct got_reflist_head refs;
9191 struct got_reflist_entry *re, *re_match;
9192 FILE *f = NULL;
9193 char *uuidstr = NULL;
9194 int added_logmsg = 0;
9196 TAILQ_INIT(&refs);
9198 *logmsg_path = NULL;
9200 err = got_worktree_get_uuid(&uuidstr, worktree);
9201 if (err)
9202 goto done;
9204 err = got_ref_list(&refs, repo, "refs/got/worktree",
9205 got_ref_cmp_by_name, repo);
9206 if (err)
9207 goto done;
9209 TAILQ_FOREACH(re, &refs, entry) {
9210 const char *refname, *type;
9211 struct wt_commitable_path_arg wcpa;
9212 int add_logmsg = 0;
9214 refname = got_ref_get_name(re->ref);
9216 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9217 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9218 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9219 type = "cherrypicked";
9220 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9221 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9222 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9223 type = "backed-out";
9224 } else
9225 continue;
9227 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9228 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9229 else
9230 continue;
9232 err = got_repo_match_object_id(&id, NULL, refname,
9233 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9234 if (err)
9235 goto done;
9237 err = got_object_open_as_commit(&commit, repo, id);
9238 if (err)
9239 goto done;
9241 wcpa.commit_paths = paths;
9242 wcpa.has_changes = &add_logmsg;
9244 err = commit_path_changed_in_worktree(&wcpa, id,
9245 worktree, repo);
9246 if (err)
9247 goto done;
9249 if (add_logmsg) {
9250 if (f == NULL) {
9251 err = got_opentemp_named(logmsg_path, &f,
9252 "got-commit-logmsg", "");
9253 if (err)
9254 goto done;
9256 err = cat_logmsg(f, commit, refname, type,
9257 added_logmsg);
9258 if (err)
9259 goto done;
9260 if (!added_logmsg)
9261 ++added_logmsg;
9263 err = got_reflist_entry_dup(&re_match, re);
9264 if (err)
9265 goto done;
9266 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9269 got_object_commit_close(commit);
9270 commit = NULL;
9271 free(id);
9272 id = NULL;
9275 done:
9276 free(id);
9277 free(uuidstr);
9278 got_ref_list_free(&refs);
9279 if (commit)
9280 got_object_commit_close(commit);
9281 if (f && fclose(f) == EOF && err == NULL)
9282 err = got_error_from_errno("fclose");
9283 if (!added_logmsg) {
9284 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9285 err = got_error_from_errno2("unlink", *logmsg_path);
9286 *logmsg_path = NULL;
9288 return err;
9291 static const struct got_error *
9292 cmd_commit(int argc, char *argv[])
9294 const struct got_error *error = NULL;
9295 struct got_worktree *worktree = NULL;
9296 struct got_repository *repo = NULL;
9297 char *cwd = NULL, *id_str = NULL;
9298 struct got_object_id *id = NULL;
9299 const char *logmsg = NULL;
9300 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9301 struct collect_commit_logmsg_arg cl_arg;
9302 const char *author = NULL;
9303 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9304 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9305 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9306 int show_diff = 1, commit_conflicts = 0;
9307 struct got_pathlist_head paths;
9308 struct got_reflist_head refs;
9309 struct got_reflist_entry *re;
9310 int *pack_fds = NULL;
9312 TAILQ_INIT(&refs);
9313 TAILQ_INIT(&paths);
9314 cl_arg.logmsg_path = NULL;
9316 #ifndef PROFILE
9317 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9318 "unveil", NULL) == -1)
9319 err(1, "pledge");
9320 #endif
9322 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9323 switch (ch) {
9324 case 'A':
9325 author = optarg;
9326 error = valid_author(author);
9327 if (error)
9328 return error;
9329 break;
9330 case 'C':
9331 commit_conflicts = 1;
9332 break;
9333 case 'F':
9334 if (logmsg != NULL)
9335 option_conflict('F', 'm');
9336 prepared_logmsg = realpath(optarg, NULL);
9337 if (prepared_logmsg == NULL)
9338 return got_error_from_errno2("realpath",
9339 optarg);
9340 break;
9341 case 'm':
9342 if (prepared_logmsg)
9343 option_conflict('m', 'F');
9344 logmsg = optarg;
9345 break;
9346 case 'N':
9347 non_interactive = 1;
9348 break;
9349 case 'n':
9350 show_diff = 0;
9351 break;
9352 case 'S':
9353 allow_bad_symlinks = 1;
9354 break;
9355 default:
9356 usage_commit();
9357 /* NOTREACHED */
9361 argc -= optind;
9362 argv += optind;
9364 cwd = getcwd(NULL, 0);
9365 if (cwd == NULL) {
9366 error = got_error_from_errno("getcwd");
9367 goto done;
9370 error = got_repo_pack_fds_open(&pack_fds);
9371 if (error != NULL)
9372 goto done;
9374 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9375 if (error) {
9376 if (error->code == GOT_ERR_NOT_WORKTREE)
9377 error = wrap_not_worktree_error(error, "commit", cwd);
9378 goto done;
9381 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9382 if (error)
9383 goto done;
9384 if (rebase_in_progress) {
9385 error = got_error(GOT_ERR_REBASING);
9386 goto done;
9389 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9390 worktree);
9391 if (error)
9392 goto done;
9394 error = get_gitconfig_path(&gitconfig_path);
9395 if (error)
9396 goto done;
9397 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9398 gitconfig_path, pack_fds);
9399 if (error != NULL)
9400 goto done;
9402 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9403 if (error)
9404 goto done;
9405 if (merge_in_progress) {
9406 error = got_error(GOT_ERR_MERGE_BUSY);
9407 goto done;
9410 error = get_author(&committer, repo, worktree);
9411 if (error)
9412 goto done;
9414 if (author == NULL)
9415 author = committer;
9418 * unveil(2) traverses exec(2); if an editor is used we have
9419 * to apply unveil after the log message has been written.
9421 if (logmsg == NULL || strlen(logmsg) == 0)
9422 error = get_editor(&editor);
9423 else
9424 error = apply_unveil(got_repo_get_path(repo), 0,
9425 got_worktree_get_root_path(worktree));
9426 if (error)
9427 goto done;
9429 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9430 if (error)
9431 goto done;
9433 if (prepared_logmsg == NULL) {
9434 error = lookup_logmsg_ref(&merged_logmsg,
9435 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9436 if (error)
9437 goto done;
9440 cl_arg.editor = editor;
9441 cl_arg.cmdline_log = logmsg;
9442 cl_arg.prepared_log = prepared_logmsg;
9443 cl_arg.merged_log = merged_logmsg;
9444 cl_arg.non_interactive = non_interactive;
9445 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9446 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9447 if (!histedit_in_progress) {
9448 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9449 error = got_error(GOT_ERR_COMMIT_BRANCH);
9450 goto done;
9452 cl_arg.branch_name += 11;
9454 cl_arg.repo_path = got_repo_get_path(repo);
9455 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9456 allow_bad_symlinks, show_diff, commit_conflicts,
9457 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9458 if (error) {
9459 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9460 cl_arg.logmsg_path != NULL)
9461 preserve_logmsg = 1;
9462 goto done;
9465 error = got_object_id_str(&id_str, id);
9466 if (error)
9467 goto done;
9468 printf("Created commit %s\n", id_str);
9470 TAILQ_FOREACH(re, &refs, entry) {
9471 error = got_ref_delete(re->ref, repo);
9472 if (error)
9473 goto done;
9476 done:
9477 if (preserve_logmsg) {
9478 fprintf(stderr, "%s: log message preserved in %s\n",
9479 getprogname(), cl_arg.logmsg_path);
9480 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9481 error == NULL)
9482 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9483 free(cl_arg.logmsg_path);
9484 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9485 error = got_error_from_errno2("unlink", merged_logmsg);
9486 free(merged_logmsg);
9487 if (repo) {
9488 const struct got_error *close_err = got_repo_close(repo);
9489 if (error == NULL)
9490 error = close_err;
9492 if (worktree)
9493 got_worktree_close(worktree);
9494 if (pack_fds) {
9495 const struct got_error *pack_err =
9496 got_repo_pack_fds_close(pack_fds);
9497 if (error == NULL)
9498 error = pack_err;
9500 got_ref_list_free(&refs);
9501 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9502 free(cwd);
9503 free(id_str);
9504 free(gitconfig_path);
9505 free(editor);
9506 free(committer);
9507 free(prepared_logmsg);
9508 return error;
9511 __dead static void
9512 usage_send(void)
9514 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9515 "[-r repository-path] [-t tag] [remote-repository]\n",
9516 getprogname());
9517 exit(1);
9520 static void
9521 print_load_info(int print_colored, int print_found, int print_trees,
9522 int ncolored, int nfound, int ntrees)
9524 if (print_colored) {
9525 printf("%d commit%s colored", ncolored,
9526 ncolored == 1 ? "" : "s");
9528 if (print_found) {
9529 printf("%s%d object%s found",
9530 ncolored > 0 ? "; " : "",
9531 nfound, nfound == 1 ? "" : "s");
9533 if (print_trees) {
9534 printf("; %d tree%s scanned", ntrees,
9535 ntrees == 1 ? "" : "s");
9539 struct got_send_progress_arg {
9540 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9541 int verbosity;
9542 int last_ncolored;
9543 int last_nfound;
9544 int last_ntrees;
9545 int loading_done;
9546 int last_ncommits;
9547 int last_nobj_total;
9548 int last_p_deltify;
9549 int last_p_written;
9550 int last_p_sent;
9551 int printed_something;
9552 int sent_something;
9553 struct got_pathlist_head *delete_branches;
9556 static const struct got_error *
9557 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9558 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9559 int nobj_written, off_t bytes_sent, const char *refname,
9560 const char *errmsg, int success)
9562 struct got_send_progress_arg *a = arg;
9563 char scaled_packsize[FMT_SCALED_STRSIZE];
9564 char scaled_sent[FMT_SCALED_STRSIZE];
9565 int p_deltify = 0, p_written = 0, p_sent = 0;
9566 int print_colored = 0, print_found = 0, print_trees = 0;
9567 int print_searching = 0, print_total = 0;
9568 int print_deltify = 0, print_written = 0, print_sent = 0;
9570 if (a->verbosity < 0)
9571 return NULL;
9573 if (refname) {
9574 const char *status = success ? "accepted" : "rejected";
9576 if (success) {
9577 struct got_pathlist_entry *pe;
9578 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9579 const char *branchname = pe->path;
9580 if (got_path_cmp(branchname, refname,
9581 strlen(branchname), strlen(refname)) == 0) {
9582 status = "deleted";
9583 a->sent_something = 1;
9584 break;
9589 if (a->printed_something)
9590 putchar('\n');
9591 printf("Server has %s %s", status, refname);
9592 if (errmsg)
9593 printf(": %s", errmsg);
9594 a->printed_something = 1;
9595 return NULL;
9598 if (a->last_ncolored != ncolored) {
9599 print_colored = 1;
9600 a->last_ncolored = ncolored;
9603 if (a->last_nfound != nfound) {
9604 print_colored = 1;
9605 print_found = 1;
9606 a->last_nfound = nfound;
9609 if (a->last_ntrees != ntrees) {
9610 print_colored = 1;
9611 print_found = 1;
9612 print_trees = 1;
9613 a->last_ntrees = ntrees;
9616 if ((print_colored || print_found || print_trees) &&
9617 !a->loading_done) {
9618 printf("\r");
9619 print_load_info(print_colored, print_found, print_trees,
9620 ncolored, nfound, ntrees);
9621 a->printed_something = 1;
9622 fflush(stdout);
9623 return NULL;
9624 } else if (!a->loading_done) {
9625 printf("\r");
9626 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9627 printf("\n");
9628 a->loading_done = 1;
9631 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9632 return got_error_from_errno("fmt_scaled");
9633 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9634 return got_error_from_errno("fmt_scaled");
9636 if (a->last_ncommits != ncommits) {
9637 print_searching = 1;
9638 a->last_ncommits = ncommits;
9641 if (a->last_nobj_total != nobj_total) {
9642 print_searching = 1;
9643 print_total = 1;
9644 a->last_nobj_total = nobj_total;
9647 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9648 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9649 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9650 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9651 return got_error(GOT_ERR_NO_SPACE);
9654 if (nobj_deltify > 0 || nobj_written > 0) {
9655 if (nobj_deltify > 0) {
9656 p_deltify = (nobj_deltify * 100) / nobj_total;
9657 if (p_deltify != a->last_p_deltify) {
9658 a->last_p_deltify = p_deltify;
9659 print_searching = 1;
9660 print_total = 1;
9661 print_deltify = 1;
9664 if (nobj_written > 0) {
9665 p_written = (nobj_written * 100) / nobj_total;
9666 if (p_written != a->last_p_written) {
9667 a->last_p_written = p_written;
9668 print_searching = 1;
9669 print_total = 1;
9670 print_deltify = 1;
9671 print_written = 1;
9676 if (bytes_sent > 0) {
9677 p_sent = (bytes_sent * 100) / packfile_size;
9678 if (p_sent != a->last_p_sent) {
9679 a->last_p_sent = p_sent;
9680 print_searching = 1;
9681 print_total = 1;
9682 print_deltify = 1;
9683 print_written = 1;
9684 print_sent = 1;
9686 a->sent_something = 1;
9689 if (print_searching || print_total || print_deltify || print_written ||
9690 print_sent)
9691 printf("\r");
9692 if (print_searching)
9693 printf("packing %d reference%s", ncommits,
9694 ncommits == 1 ? "" : "s");
9695 if (print_total)
9696 printf("; %d object%s", nobj_total,
9697 nobj_total == 1 ? "" : "s");
9698 if (print_deltify)
9699 printf("; deltify: %d%%", p_deltify);
9700 if (print_sent)
9701 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9702 scaled_packsize, p_sent);
9703 else if (print_written)
9704 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9705 scaled_packsize, p_written);
9706 if (print_searching || print_total || print_deltify ||
9707 print_written || print_sent) {
9708 a->printed_something = 1;
9709 fflush(stdout);
9711 return NULL;
9714 static const struct got_error *
9715 cmd_send(int argc, char *argv[])
9717 const struct got_error *error = NULL;
9718 char *cwd = NULL, *repo_path = NULL;
9719 const char *remote_name;
9720 char *proto = NULL, *host = NULL, *port = NULL;
9721 char *repo_name = NULL, *server_path = NULL;
9722 const struct got_remote_repo *remotes;
9723 struct got_remote_repo *remote = NULL;
9724 int nremotes, nbranches = 0, ndelete_branches = 0;
9725 struct got_repository *repo = NULL;
9726 struct got_worktree *worktree = NULL;
9727 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9728 struct got_pathlist_head branches;
9729 struct got_pathlist_head tags;
9730 struct got_reflist_head all_branches;
9731 struct got_reflist_head all_tags;
9732 struct got_pathlist_head delete_args;
9733 struct got_pathlist_head delete_branches;
9734 struct got_reflist_entry *re;
9735 struct got_pathlist_entry *pe;
9736 int i, ch, sendfd = -1, sendstatus;
9737 pid_t sendpid = -1;
9738 struct got_send_progress_arg spa;
9739 int verbosity = 0, overwrite_refs = 0;
9740 int send_all_branches = 0, send_all_tags = 0;
9741 struct got_reference *ref = NULL;
9742 int *pack_fds = NULL;
9744 TAILQ_INIT(&branches);
9745 TAILQ_INIT(&tags);
9746 TAILQ_INIT(&all_branches);
9747 TAILQ_INIT(&all_tags);
9748 TAILQ_INIT(&delete_args);
9749 TAILQ_INIT(&delete_branches);
9751 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9752 switch (ch) {
9753 case 'a':
9754 send_all_branches = 1;
9755 break;
9756 case 'b':
9757 error = got_pathlist_append(&branches, optarg, NULL);
9758 if (error)
9759 return error;
9760 nbranches++;
9761 break;
9762 case 'd':
9763 error = got_pathlist_append(&delete_args, optarg, NULL);
9764 if (error)
9765 return error;
9766 break;
9767 case 'f':
9768 overwrite_refs = 1;
9769 break;
9770 case 'q':
9771 verbosity = -1;
9772 break;
9773 case 'r':
9774 repo_path = realpath(optarg, NULL);
9775 if (repo_path == NULL)
9776 return got_error_from_errno2("realpath",
9777 optarg);
9778 got_path_strip_trailing_slashes(repo_path);
9779 break;
9780 case 'T':
9781 send_all_tags = 1;
9782 break;
9783 case 't':
9784 error = got_pathlist_append(&tags, optarg, NULL);
9785 if (error)
9786 return error;
9787 break;
9788 case 'v':
9789 if (verbosity < 0)
9790 verbosity = 0;
9791 else if (verbosity < 3)
9792 verbosity++;
9793 break;
9794 default:
9795 usage_send();
9796 /* NOTREACHED */
9799 argc -= optind;
9800 argv += optind;
9802 if (send_all_branches && !TAILQ_EMPTY(&branches))
9803 option_conflict('a', 'b');
9804 if (send_all_tags && !TAILQ_EMPTY(&tags))
9805 option_conflict('T', 't');
9808 if (argc == 0)
9809 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9810 else if (argc == 1)
9811 remote_name = argv[0];
9812 else
9813 usage_send();
9815 cwd = getcwd(NULL, 0);
9816 if (cwd == NULL) {
9817 error = got_error_from_errno("getcwd");
9818 goto done;
9821 error = got_repo_pack_fds_open(&pack_fds);
9822 if (error != NULL)
9823 goto done;
9825 if (repo_path == NULL) {
9826 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9827 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9828 goto done;
9829 else
9830 error = NULL;
9831 if (worktree) {
9832 repo_path =
9833 strdup(got_worktree_get_repo_path(worktree));
9834 if (repo_path == NULL)
9835 error = got_error_from_errno("strdup");
9836 if (error)
9837 goto done;
9838 } else {
9839 repo_path = strdup(cwd);
9840 if (repo_path == NULL) {
9841 error = got_error_from_errno("strdup");
9842 goto done;
9847 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9848 if (error)
9849 goto done;
9851 if (worktree) {
9852 worktree_conf = got_worktree_get_gotconfig(worktree);
9853 if (worktree_conf) {
9854 got_gotconfig_get_remotes(&nremotes, &remotes,
9855 worktree_conf);
9856 for (i = 0; i < nremotes; i++) {
9857 if (strcmp(remotes[i].name, remote_name) == 0) {
9858 error = got_repo_remote_repo_dup(&remote,
9859 &remotes[i]);
9860 if (error)
9861 goto done;
9862 break;
9867 if (remote == NULL) {
9868 repo_conf = got_repo_get_gotconfig(repo);
9869 if (repo_conf) {
9870 got_gotconfig_get_remotes(&nremotes, &remotes,
9871 repo_conf);
9872 for (i = 0; i < nremotes; i++) {
9873 if (strcmp(remotes[i].name, remote_name) == 0) {
9874 error = got_repo_remote_repo_dup(&remote,
9875 &remotes[i]);
9876 if (error)
9877 goto done;
9878 break;
9883 if (remote == NULL) {
9884 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9885 for (i = 0; i < nremotes; i++) {
9886 if (strcmp(remotes[i].name, remote_name) == 0) {
9887 error = got_repo_remote_repo_dup(&remote,
9888 &remotes[i]);
9889 if (error)
9890 goto done;
9891 break;
9895 if (remote == NULL) {
9896 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9897 goto done;
9900 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9901 &repo_name, remote->send_url);
9902 if (error)
9903 goto done;
9905 if (strcmp(proto, "git") == 0) {
9906 #ifndef PROFILE
9907 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9908 "sendfd dns inet unveil", NULL) == -1)
9909 err(1, "pledge");
9910 #endif
9911 } else if (strcmp(proto, "git+ssh") == 0 ||
9912 strcmp(proto, "ssh") == 0) {
9913 #ifndef PROFILE
9914 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9915 "sendfd unveil", NULL) == -1)
9916 err(1, "pledge");
9917 #endif
9918 } else if (strcmp(proto, "http") == 0 ||
9919 strcmp(proto, "git+http") == 0) {
9920 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9921 goto done;
9922 } else {
9923 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9924 goto done;
9927 error = got_dial_apply_unveil(proto);
9928 if (error)
9929 goto done;
9931 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9932 if (error)
9933 goto done;
9935 if (send_all_branches) {
9936 error = got_ref_list(&all_branches, repo, "refs/heads",
9937 got_ref_cmp_by_name, NULL);
9938 if (error)
9939 goto done;
9940 TAILQ_FOREACH(re, &all_branches, entry) {
9941 const char *branchname = got_ref_get_name(re->ref);
9942 error = got_pathlist_append(&branches,
9943 branchname, NULL);
9944 if (error)
9945 goto done;
9946 nbranches++;
9948 } else if (nbranches == 0) {
9949 for (i = 0; i < remote->nsend_branches; i++) {
9950 error = got_pathlist_append(&branches,
9951 remote->send_branches[i], NULL);
9952 if (error)
9953 goto done;
9957 if (send_all_tags) {
9958 error = got_ref_list(&all_tags, repo, "refs/tags",
9959 got_ref_cmp_by_name, NULL);
9960 if (error)
9961 goto done;
9962 TAILQ_FOREACH(re, &all_tags, entry) {
9963 const char *tagname = got_ref_get_name(re->ref);
9964 error = got_pathlist_append(&tags,
9965 tagname, NULL);
9966 if (error)
9967 goto done;
9972 * To prevent accidents only branches in refs/heads/ can be deleted
9973 * with 'got send -d'.
9974 * Deleting anything else requires local repository access or Git.
9976 TAILQ_FOREACH(pe, &delete_args, entry) {
9977 const char *branchname = pe->path;
9978 char *s;
9979 struct got_pathlist_entry *new;
9980 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9981 s = strdup(branchname);
9982 if (s == NULL) {
9983 error = got_error_from_errno("strdup");
9984 goto done;
9986 } else {
9987 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9988 error = got_error_from_errno("asprintf");
9989 goto done;
9992 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9993 if (error || new == NULL /* duplicate */)
9994 free(s);
9995 if (error)
9996 goto done;
9997 ndelete_branches++;
10000 if (nbranches == 0 && ndelete_branches == 0) {
10001 struct got_reference *head_ref;
10002 if (worktree)
10003 error = got_ref_open(&head_ref, repo,
10004 got_worktree_get_head_ref_name(worktree), 0);
10005 else
10006 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10007 if (error)
10008 goto done;
10009 if (got_ref_is_symbolic(head_ref)) {
10010 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10011 got_ref_close(head_ref);
10012 if (error)
10013 goto done;
10014 } else
10015 ref = head_ref;
10016 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10017 NULL);
10018 if (error)
10019 goto done;
10020 nbranches++;
10023 if (worktree) {
10024 /* Release work tree lock. */
10025 got_worktree_close(worktree);
10026 worktree = NULL;
10029 if (verbosity >= 0) {
10030 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10031 remote->name, proto, host,
10032 port ? ":" : "", port ? port : "",
10033 *server_path == '/' ? "" : "/", server_path);
10036 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10037 server_path, verbosity);
10038 if (error)
10039 goto done;
10041 memset(&spa, 0, sizeof(spa));
10042 spa.last_scaled_packsize[0] = '\0';
10043 spa.last_p_deltify = -1;
10044 spa.last_p_written = -1;
10045 spa.verbosity = verbosity;
10046 spa.delete_branches = &delete_branches;
10047 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10048 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10049 check_cancelled, NULL);
10050 if (spa.printed_something)
10051 putchar('\n');
10052 if (error)
10053 goto done;
10054 if (!spa.sent_something && verbosity >= 0)
10055 printf("Already up-to-date\n");
10056 done:
10057 if (sendpid > 0) {
10058 if (kill(sendpid, SIGTERM) == -1)
10059 error = got_error_from_errno("kill");
10060 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10061 error = got_error_from_errno("waitpid");
10063 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10064 error = got_error_from_errno("close");
10065 if (repo) {
10066 const struct got_error *close_err = got_repo_close(repo);
10067 if (error == NULL)
10068 error = close_err;
10070 if (worktree)
10071 got_worktree_close(worktree);
10072 if (pack_fds) {
10073 const struct got_error *pack_err =
10074 got_repo_pack_fds_close(pack_fds);
10075 if (error == NULL)
10076 error = pack_err;
10078 if (ref)
10079 got_ref_close(ref);
10080 got_repo_free_remote_repo_data(remote);
10081 free(remote);
10082 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10083 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10084 got_ref_list_free(&all_branches);
10085 got_ref_list_free(&all_tags);
10086 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10087 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10088 free(cwd);
10089 free(repo_path);
10090 free(proto);
10091 free(host);
10092 free(port);
10093 free(server_path);
10094 free(repo_name);
10095 return error;
10099 * Print and if delete is set delete all ref_prefix references.
10100 * If wanted_ref is not NULL, only print or delete this reference.
10102 static const struct got_error *
10103 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10104 const char *wanted_ref, int delete, struct got_worktree *worktree,
10105 struct got_repository *repo)
10107 const struct got_error *err;
10108 struct got_pathlist_head paths;
10109 struct got_reflist_head refs;
10110 struct got_reflist_entry *re;
10111 struct got_reflist_object_id_map *refs_idmap = NULL;
10112 struct got_commit_object *commit = NULL;
10113 struct got_object_id *id = NULL;
10114 const char *header_prefix;
10115 char *uuidstr = NULL;
10116 int found = 0;
10118 TAILQ_INIT(&refs);
10119 TAILQ_INIT(&paths);
10121 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10122 if (err)
10123 goto done;
10125 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10126 if (err)
10127 goto done;
10129 if (worktree != NULL) {
10130 err = got_worktree_get_uuid(&uuidstr, worktree);
10131 if (err)
10132 goto done;
10135 if (wanted_ref) {
10136 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10137 wanted_ref += 11;
10140 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10141 header_prefix = "backout";
10142 else
10143 header_prefix = "cherrypick";
10145 TAILQ_FOREACH(re, &refs, entry) {
10146 const char *refname, *wt;
10148 refname = got_ref_get_name(re->ref);
10150 err = check_cancelled(NULL);
10151 if (err)
10152 goto done;
10154 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10155 refname += prefix_len + 1; /* skip '-' delimiter */
10156 else
10157 continue;
10159 wt = refname;
10161 if (worktree == NULL || strncmp(refname, uuidstr,
10162 GOT_WORKTREE_UUID_STRLEN) == 0)
10163 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10164 else
10165 continue;
10167 err = got_repo_match_object_id(&id, NULL, refname,
10168 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10169 if (err)
10170 goto done;
10172 err = got_object_open_as_commit(&commit, repo, id);
10173 if (err)
10174 goto done;
10176 if (wanted_ref)
10177 found = strncmp(wanted_ref, refname,
10178 strlen(wanted_ref)) == 0;
10179 if (wanted_ref && !found) {
10180 struct got_reflist_head *ci_refs;
10182 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10183 id);
10185 if (ci_refs) {
10186 char *refs_str = NULL;
10187 char const *r = NULL;
10189 err = build_refs_str(&refs_str, ci_refs, id,
10190 repo, 1);
10191 if (err)
10192 goto done;
10194 r = refs_str;
10195 while (r) {
10196 if (strncmp(r, wanted_ref,
10197 strlen(wanted_ref)) == 0) {
10198 found = 1;
10199 break;
10201 r = strchr(r, ' ');
10202 if (r)
10203 ++r;
10205 free(refs_str);
10209 if (wanted_ref == NULL || found) {
10210 if (delete) {
10211 err = got_ref_delete(re->ref, repo);
10212 if (err)
10213 goto done;
10214 printf("Deleted: ");
10215 err = print_commit_oneline(commit, id, repo,
10216 refs_idmap);
10217 } else {
10219 * Print paths modified by commit to help
10220 * associate commits with worktree changes.
10222 err = get_changed_paths(&paths, commit,
10223 repo, NULL);
10224 if (err)
10225 goto done;
10227 err = print_commit(commit, id, repo, NULL,
10228 &paths, NULL, 0, 0, refs_idmap, NULL,
10229 header_prefix);
10230 got_pathlist_free(&paths,
10231 GOT_PATHLIST_FREE_ALL);
10233 if (worktree == NULL)
10234 printf("work tree: %.*s\n\n",
10235 GOT_WORKTREE_UUID_STRLEN, wt);
10237 if (err || found)
10238 goto done;
10241 got_object_commit_close(commit);
10242 commit = NULL;
10243 free(id);
10244 id = NULL;
10247 if (wanted_ref != NULL && !found)
10248 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10250 done:
10251 free(id);
10252 free(uuidstr);
10253 got_ref_list_free(&refs);
10254 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10255 if (refs_idmap)
10256 got_reflist_object_id_map_free(refs_idmap);
10257 if (commit)
10258 got_object_commit_close(commit);
10259 return err;
10263 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10264 * identified by id for log messages to prepopulate the editor on commit.
10266 static const struct got_error *
10267 logmsg_ref(struct got_object_id *id, const char *prefix,
10268 struct got_worktree *worktree, struct got_repository *repo)
10270 const struct got_error *err = NULL;
10271 char *idstr, *ref = NULL, *refname = NULL;
10272 int histedit_in_progress;
10273 int rebase_in_progress, merge_in_progress;
10276 * Silenty refuse to create merge reference if any histedit, merge,
10277 * or rebase operation is in progress.
10279 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10280 worktree);
10281 if (err)
10282 return err;
10283 if (histedit_in_progress)
10284 return NULL;
10286 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10287 if (err)
10288 return err;
10289 if (rebase_in_progress)
10290 return NULL;
10292 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10293 repo);
10294 if (err)
10295 return err;
10296 if (merge_in_progress)
10297 return NULL;
10299 err = got_object_id_str(&idstr, id);
10300 if (err)
10301 return err;
10303 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10304 if (err)
10305 goto done;
10307 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10308 err = got_error_from_errno("asprintf");
10309 goto done;
10312 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10313 -1, repo);
10314 done:
10315 free(ref);
10316 free(idstr);
10317 free(refname);
10318 return err;
10321 __dead static void
10322 usage_cherrypick(void)
10324 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10325 getprogname());
10326 exit(1);
10329 static const struct got_error *
10330 cmd_cherrypick(int argc, char *argv[])
10332 const struct got_error *error = NULL;
10333 struct got_worktree *worktree = NULL;
10334 struct got_repository *repo = NULL;
10335 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10336 struct got_object_id *commit_id = NULL;
10337 struct got_commit_object *commit = NULL;
10338 struct got_object_qid *pid;
10339 int ch, list_refs = 0, remove_refs = 0;
10340 struct got_update_progress_arg upa;
10341 int *pack_fds = NULL;
10343 #ifndef PROFILE
10344 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10345 "unveil", NULL) == -1)
10346 err(1, "pledge");
10347 #endif
10349 while ((ch = getopt(argc, argv, "lX")) != -1) {
10350 switch (ch) {
10351 case 'l':
10352 list_refs = 1;
10353 break;
10354 case 'X':
10355 remove_refs = 1;
10356 break;
10357 default:
10358 usage_cherrypick();
10359 /* NOTREACHED */
10363 argc -= optind;
10364 argv += optind;
10366 if (list_refs || remove_refs) {
10367 if (argc != 0 && argc != 1)
10368 usage_cherrypick();
10369 } else if (argc != 1)
10370 usage_cherrypick();
10371 if (list_refs && remove_refs)
10372 option_conflict('l', 'X');
10374 cwd = getcwd(NULL, 0);
10375 if (cwd == NULL) {
10376 error = got_error_from_errno("getcwd");
10377 goto done;
10380 error = got_repo_pack_fds_open(&pack_fds);
10381 if (error != NULL)
10382 goto done;
10384 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10385 if (error) {
10386 if (list_refs || remove_refs) {
10387 if (error->code != GOT_ERR_NOT_WORKTREE)
10388 goto done;
10389 } else {
10390 if (error->code == GOT_ERR_NOT_WORKTREE)
10391 error = wrap_not_worktree_error(error,
10392 "cherrypick", cwd);
10393 goto done;
10397 error = got_repo_open(&repo,
10398 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10399 NULL, pack_fds);
10400 if (error != NULL)
10401 goto done;
10403 error = apply_unveil(got_repo_get_path(repo), 0,
10404 worktree ? got_worktree_get_root_path(worktree) : NULL);
10405 if (error)
10406 goto done;
10408 if (list_refs || remove_refs) {
10409 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10410 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10411 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10412 goto done;
10415 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10416 if (error != NULL)
10417 goto done;
10419 error = got_repo_match_object_id(&commit_id, NULL,
10420 keyword_idstr != NULL ? keyword_idstr : argv[0],
10421 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10422 if (error)
10423 goto done;
10424 error = got_object_id_str(&commit_id_str, commit_id);
10425 if (error)
10426 goto done;
10428 error = got_object_open_as_commit(&commit, repo, commit_id);
10429 if (error)
10430 goto done;
10431 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10432 memset(&upa, 0, sizeof(upa));
10433 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10434 commit_id, repo, update_progress, &upa, check_cancelled,
10435 NULL);
10436 if (error != NULL)
10437 goto done;
10439 if (upa.did_something) {
10440 error = logmsg_ref(commit_id,
10441 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10442 if (error)
10443 goto done;
10444 printf("Merged commit %s\n", commit_id_str);
10446 print_merge_progress_stats(&upa);
10447 done:
10448 free(cwd);
10449 free(keyword_idstr);
10450 if (commit)
10451 got_object_commit_close(commit);
10452 free(commit_id_str);
10453 if (worktree)
10454 got_worktree_close(worktree);
10455 if (repo) {
10456 const struct got_error *close_err = got_repo_close(repo);
10457 if (error == NULL)
10458 error = close_err;
10460 if (pack_fds) {
10461 const struct got_error *pack_err =
10462 got_repo_pack_fds_close(pack_fds);
10463 if (error == NULL)
10464 error = pack_err;
10467 return error;
10470 __dead static void
10471 usage_backout(void)
10473 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10474 exit(1);
10477 static const struct got_error *
10478 cmd_backout(int argc, char *argv[])
10480 const struct got_error *error = NULL;
10481 struct got_worktree *worktree = NULL;
10482 struct got_repository *repo = NULL;
10483 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10484 struct got_object_id *commit_id = NULL;
10485 struct got_commit_object *commit = NULL;
10486 struct got_object_qid *pid;
10487 int ch, list_refs = 0, remove_refs = 0;
10488 struct got_update_progress_arg upa;
10489 int *pack_fds = NULL;
10491 #ifndef PROFILE
10492 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10493 "unveil", NULL) == -1)
10494 err(1, "pledge");
10495 #endif
10497 while ((ch = getopt(argc, argv, "lX")) != -1) {
10498 switch (ch) {
10499 case 'l':
10500 list_refs = 1;
10501 break;
10502 case 'X':
10503 remove_refs = 1;
10504 break;
10505 default:
10506 usage_backout();
10507 /* NOTREACHED */
10511 argc -= optind;
10512 argv += optind;
10514 if (list_refs || remove_refs) {
10515 if (argc != 0 && argc != 1)
10516 usage_backout();
10517 } else if (argc != 1)
10518 usage_backout();
10519 if (list_refs && remove_refs)
10520 option_conflict('l', 'X');
10522 cwd = getcwd(NULL, 0);
10523 if (cwd == NULL) {
10524 error = got_error_from_errno("getcwd");
10525 goto done;
10528 error = got_repo_pack_fds_open(&pack_fds);
10529 if (error != NULL)
10530 goto done;
10532 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10533 if (error) {
10534 if (list_refs || remove_refs) {
10535 if (error->code != GOT_ERR_NOT_WORKTREE)
10536 goto done;
10537 } else {
10538 if (error->code == GOT_ERR_NOT_WORKTREE)
10539 error = wrap_not_worktree_error(error,
10540 "backout", cwd);
10541 goto done;
10545 error = got_repo_open(&repo,
10546 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10547 NULL, pack_fds);
10548 if (error != NULL)
10549 goto done;
10551 error = apply_unveil(got_repo_get_path(repo), 0,
10552 worktree ? got_worktree_get_root_path(worktree) : NULL);
10553 if (error)
10554 goto done;
10556 if (list_refs || remove_refs) {
10557 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10558 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10559 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10560 goto done;
10563 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10564 if (error != NULL)
10565 goto done;
10567 error = got_repo_match_object_id(&commit_id, NULL,
10568 keyword_idstr != NULL ? keyword_idstr : argv[0],
10569 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10570 if (error)
10571 goto done;
10572 error = got_object_id_str(&commit_id_str, commit_id);
10573 if (error)
10574 goto done;
10576 error = got_object_open_as_commit(&commit, repo, commit_id);
10577 if (error)
10578 goto done;
10579 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10580 if (pid == NULL) {
10581 error = got_error(GOT_ERR_ROOT_COMMIT);
10582 goto done;
10585 memset(&upa, 0, sizeof(upa));
10586 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10587 repo, update_progress, &upa, check_cancelled, NULL);
10588 if (error != NULL)
10589 goto done;
10591 if (upa.did_something) {
10592 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10593 worktree, repo);
10594 if (error)
10595 goto done;
10596 printf("Backed out commit %s\n", commit_id_str);
10598 print_merge_progress_stats(&upa);
10599 done:
10600 free(cwd);
10601 free(keyword_idstr);
10602 if (commit)
10603 got_object_commit_close(commit);
10604 free(commit_id_str);
10605 if (worktree)
10606 got_worktree_close(worktree);
10607 if (repo) {
10608 const struct got_error *close_err = got_repo_close(repo);
10609 if (error == NULL)
10610 error = close_err;
10612 if (pack_fds) {
10613 const struct got_error *pack_err =
10614 got_repo_pack_fds_close(pack_fds);
10615 if (error == NULL)
10616 error = pack_err;
10618 return error;
10621 __dead static void
10622 usage_rebase(void)
10624 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10625 exit(1);
10628 static void
10629 trim_logmsg(char *logmsg, int limit)
10631 char *nl;
10632 size_t len;
10634 len = strlen(logmsg);
10635 if (len > limit)
10636 len = limit;
10637 logmsg[len] = '\0';
10638 nl = strchr(logmsg, '\n');
10639 if (nl)
10640 *nl = '\0';
10643 static const struct got_error *
10644 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10646 const struct got_error *err;
10647 char *logmsg0 = NULL;
10648 const char *s;
10650 err = got_object_commit_get_logmsg(&logmsg0, commit);
10651 if (err)
10652 return err;
10654 s = logmsg0;
10655 while (isspace((unsigned char)s[0]))
10656 s++;
10658 *logmsg = strdup(s);
10659 if (*logmsg == NULL) {
10660 err = got_error_from_errno("strdup");
10661 goto done;
10664 trim_logmsg(*logmsg, limit);
10665 done:
10666 free(logmsg0);
10667 return err;
10670 static const struct got_error *
10671 show_rebase_merge_conflict(struct got_object_id *id,
10672 struct got_repository *repo)
10674 const struct got_error *err;
10675 struct got_commit_object *commit = NULL;
10676 char *id_str = NULL, *logmsg = NULL;
10678 err = got_object_open_as_commit(&commit, repo, id);
10679 if (err)
10680 return err;
10682 err = got_object_id_str(&id_str, id);
10683 if (err)
10684 goto done;
10686 id_str[12] = '\0';
10688 err = get_short_logmsg(&logmsg, 42, commit);
10689 if (err)
10690 goto done;
10692 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10693 done:
10694 free(id_str);
10695 got_object_commit_close(commit);
10696 free(logmsg);
10697 return err;
10700 static const struct got_error *
10701 show_rebase_progress(struct got_commit_object *commit,
10702 struct got_object_id *old_id, struct got_object_id *new_id)
10704 const struct got_error *err;
10705 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10707 err = got_object_id_str(&old_id_str, old_id);
10708 if (err)
10709 goto done;
10711 if (new_id) {
10712 err = got_object_id_str(&new_id_str, new_id);
10713 if (err)
10714 goto done;
10717 old_id_str[12] = '\0';
10718 if (new_id_str)
10719 new_id_str[12] = '\0';
10721 err = get_short_logmsg(&logmsg, 42, commit);
10722 if (err)
10723 goto done;
10725 printf("%s -> %s: %s\n", old_id_str,
10726 new_id_str ? new_id_str : "no-op change", logmsg);
10727 done:
10728 free(old_id_str);
10729 free(new_id_str);
10730 free(logmsg);
10731 return err;
10734 static const struct got_error *
10735 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10736 struct got_reference *branch, struct got_reference *tmp_branch,
10737 struct got_repository *repo, int create_backup)
10739 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10740 return got_worktree_rebase_complete(worktree, fileindex,
10741 tmp_branch, branch, repo, create_backup);
10744 static const struct got_error *
10745 rebase_commit(struct got_pathlist_head *merged_paths,
10746 struct got_worktree *worktree, struct got_fileindex *fileindex,
10747 struct got_reference *tmp_branch, const char *committer,
10748 struct got_object_id *commit_id, int allow_conflict,
10749 struct got_repository *repo)
10751 const struct got_error *error;
10752 struct got_commit_object *commit;
10753 struct got_object_id *new_commit_id;
10755 error = got_object_open_as_commit(&commit, repo, commit_id);
10756 if (error)
10757 return error;
10759 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10760 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10761 allow_conflict, repo);
10762 if (error) {
10763 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10764 goto done;
10765 error = show_rebase_progress(commit, commit_id, NULL);
10766 } else {
10767 error = show_rebase_progress(commit, commit_id, new_commit_id);
10768 free(new_commit_id);
10770 done:
10771 got_object_commit_close(commit);
10772 return error;
10775 struct check_path_prefix_arg {
10776 const char *path_prefix;
10777 size_t len;
10778 int errcode;
10781 static const struct got_error *
10782 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10783 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10784 struct got_object_id *id1, struct got_object_id *id2,
10785 const char *path1, const char *path2,
10786 mode_t mode1, mode_t mode2, struct got_repository *repo)
10788 struct check_path_prefix_arg *a = arg;
10790 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10791 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10792 return got_error(a->errcode);
10794 return NULL;
10797 static const struct got_error *
10798 check_path_prefix(struct got_object_id *parent_id,
10799 struct got_object_id *commit_id, const char *path_prefix,
10800 int errcode, struct got_repository *repo)
10802 const struct got_error *err;
10803 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10804 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10805 struct check_path_prefix_arg cpp_arg;
10807 if (got_path_is_root_dir(path_prefix))
10808 return NULL;
10810 err = got_object_open_as_commit(&commit, repo, commit_id);
10811 if (err)
10812 goto done;
10814 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10815 if (err)
10816 goto done;
10818 err = got_object_open_as_tree(&tree1, repo,
10819 got_object_commit_get_tree_id(parent_commit));
10820 if (err)
10821 goto done;
10823 err = got_object_open_as_tree(&tree2, repo,
10824 got_object_commit_get_tree_id(commit));
10825 if (err)
10826 goto done;
10828 cpp_arg.path_prefix = path_prefix;
10829 while (cpp_arg.path_prefix[0] == '/')
10830 cpp_arg.path_prefix++;
10831 cpp_arg.len = strlen(cpp_arg.path_prefix);
10832 cpp_arg.errcode = errcode;
10833 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10834 check_path_prefix_in_diff, &cpp_arg, 0);
10835 done:
10836 if (tree1)
10837 got_object_tree_close(tree1);
10838 if (tree2)
10839 got_object_tree_close(tree2);
10840 if (commit)
10841 got_object_commit_close(commit);
10842 if (parent_commit)
10843 got_object_commit_close(parent_commit);
10844 return err;
10847 static const struct got_error *
10848 collect_commits(struct got_object_id_queue *commits,
10849 struct got_object_id *initial_commit_id,
10850 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10851 const char *path_prefix, int path_prefix_errcode,
10852 struct got_repository *repo)
10854 const struct got_error *err = NULL;
10855 struct got_commit_graph *graph = NULL;
10856 struct got_object_id parent_id, commit_id;
10857 struct got_object_qid *qid;
10859 err = got_commit_graph_open(&graph, "/", 1);
10860 if (err)
10861 return err;
10863 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10864 check_cancelled, NULL);
10865 if (err)
10866 goto done;
10868 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10869 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10870 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10871 check_cancelled, NULL);
10872 if (err) {
10873 if (err->code == GOT_ERR_ITER_COMPLETED) {
10874 err = got_error_msg(GOT_ERR_ANCESTRY,
10875 "ran out of commits to rebase before "
10876 "youngest common ancestor commit has "
10877 "been reached?!?");
10879 goto done;
10880 } else {
10881 err = check_path_prefix(&parent_id, &commit_id,
10882 path_prefix, path_prefix_errcode, repo);
10883 if (err)
10884 goto done;
10886 err = got_object_qid_alloc(&qid, &commit_id);
10887 if (err)
10888 goto done;
10889 STAILQ_INSERT_HEAD(commits, qid, entry);
10891 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10894 done:
10895 got_commit_graph_close(graph);
10896 return err;
10899 static const struct got_error *
10900 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10902 const struct got_error *err = NULL;
10903 time_t committer_time;
10904 struct tm tm;
10905 char datebuf[11]; /* YYYY-MM-DD + NUL */
10906 char *author0 = NULL, *author, *smallerthan;
10907 char *logmsg0 = NULL, *logmsg, *newline;
10909 committer_time = got_object_commit_get_committer_time(commit);
10910 if (gmtime_r(&committer_time, &tm) == NULL)
10911 return got_error_from_errno("gmtime_r");
10912 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10913 return got_error(GOT_ERR_NO_SPACE);
10915 author0 = strdup(got_object_commit_get_author(commit));
10916 if (author0 == NULL)
10917 return got_error_from_errno("strdup");
10918 author = author0;
10919 smallerthan = strchr(author, '<');
10920 if (smallerthan && smallerthan[1] != '\0')
10921 author = smallerthan + 1;
10922 author[strcspn(author, "@>")] = '\0';
10924 err = got_object_commit_get_logmsg(&logmsg0, commit);
10925 if (err)
10926 goto done;
10927 logmsg = logmsg0;
10928 while (*logmsg == '\n')
10929 logmsg++;
10930 newline = strchr(logmsg, '\n');
10931 if (newline)
10932 *newline = '\0';
10934 if (asprintf(brief_str, "%s %s %s",
10935 datebuf, author, logmsg) == -1)
10936 err = got_error_from_errno("asprintf");
10937 done:
10938 free(author0);
10939 free(logmsg0);
10940 return err;
10943 static const struct got_error *
10944 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10945 struct got_repository *repo)
10947 const struct got_error *err;
10948 char *id_str;
10950 err = got_object_id_str(&id_str, id);
10951 if (err)
10952 return err;
10954 err = got_ref_delete(ref, repo);
10955 if (err)
10956 goto done;
10958 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10959 done:
10960 free(id_str);
10961 return err;
10964 static const struct got_error *
10965 print_backup_ref(const char *branch_name, const char *new_id_str,
10966 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10967 struct got_reflist_object_id_map *refs_idmap,
10968 struct got_repository *repo)
10970 const struct got_error *err = NULL;
10971 struct got_reflist_head *refs;
10972 char *refs_str = NULL;
10973 struct got_object_id *new_commit_id = NULL;
10974 struct got_commit_object *new_commit = NULL;
10975 char *new_commit_brief_str = NULL;
10976 struct got_object_id *yca_id = NULL;
10977 struct got_commit_object *yca_commit = NULL;
10978 char *yca_id_str = NULL, *yca_brief_str = NULL;
10979 char *custom_refs_str;
10981 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10982 return got_error_from_errno("asprintf");
10984 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10985 0, 0, refs_idmap, custom_refs_str, NULL);
10986 if (err)
10987 goto done;
10989 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10990 if (err)
10991 goto done;
10993 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10994 if (refs) {
10995 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10996 if (err)
10997 goto done;
11000 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11001 if (err)
11002 goto done;
11004 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11005 if (err)
11006 goto done;
11008 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11009 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
11010 if (err)
11011 goto done;
11013 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11014 refs_str ? " (" : "", refs_str ? refs_str : "",
11015 refs_str ? ")" : "", new_commit_brief_str);
11016 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11017 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11018 free(refs_str);
11019 refs_str = NULL;
11021 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11022 if (err)
11023 goto done;
11025 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11026 if (err)
11027 goto done;
11029 err = got_object_id_str(&yca_id_str, yca_id);
11030 if (err)
11031 goto done;
11033 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11034 if (refs) {
11035 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11036 if (err)
11037 goto done;
11039 printf("history forked at %s%s%s%s\n %s\n",
11040 yca_id_str,
11041 refs_str ? " (" : "", refs_str ? refs_str : "",
11042 refs_str ? ")" : "", yca_brief_str);
11044 done:
11045 free(custom_refs_str);
11046 free(new_commit_id);
11047 free(refs_str);
11048 free(yca_id);
11049 free(yca_id_str);
11050 free(yca_brief_str);
11051 if (new_commit)
11052 got_object_commit_close(new_commit);
11053 if (yca_commit)
11054 got_object_commit_close(yca_commit);
11056 return err;
11059 static const struct got_error *
11060 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11061 struct got_repository *repo)
11063 const struct got_error *err;
11064 struct got_reflist_head refs;
11065 struct got_reflist_entry *re;
11066 char *uuidstr = NULL;
11067 static char msg[160];
11069 TAILQ_INIT(&refs);
11071 err = got_worktree_get_uuid(&uuidstr, worktree);
11072 if (err)
11073 goto done;
11075 err = got_ref_list(&refs, repo, "refs/got/worktree",
11076 got_ref_cmp_by_name, repo);
11077 if (err)
11078 goto done;
11080 TAILQ_FOREACH(re, &refs, entry) {
11081 const char *cmd, *refname, *type;
11083 refname = got_ref_get_name(re->ref);
11085 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11086 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11087 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11088 cmd = "cherrypick";
11089 type = "cherrypicked";
11090 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11091 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11092 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11093 cmd = "backout";
11094 type = "backed-out";
11095 } else
11096 continue;
11098 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11099 continue;
11101 snprintf(msg, sizeof(msg),
11102 "work tree has references created by %s commits which "
11103 "must be removed with 'got %s -X' before running the %s "
11104 "command", type, cmd, caller);
11105 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11106 goto done;
11109 done:
11110 free(uuidstr);
11111 got_ref_list_free(&refs);
11112 return err;
11115 static const struct got_error *
11116 process_backup_refs(const char *backup_ref_prefix,
11117 const char *wanted_branch_name,
11118 int delete, struct got_repository *repo)
11120 const struct got_error *err;
11121 struct got_reflist_head refs, backup_refs;
11122 struct got_reflist_entry *re;
11123 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11124 struct got_object_id *old_commit_id = NULL;
11125 char *branch_name = NULL;
11126 struct got_commit_object *old_commit = NULL;
11127 struct got_reflist_object_id_map *refs_idmap = NULL;
11128 int wanted_branch_found = 0;
11130 TAILQ_INIT(&refs);
11131 TAILQ_INIT(&backup_refs);
11133 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11134 if (err)
11135 return err;
11137 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11138 if (err)
11139 goto done;
11141 if (wanted_branch_name) {
11142 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11143 wanted_branch_name += 11;
11146 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11147 got_ref_cmp_by_commit_timestamp_descending, repo);
11148 if (err)
11149 goto done;
11151 TAILQ_FOREACH(re, &backup_refs, entry) {
11152 const char *refname = got_ref_get_name(re->ref);
11153 char *slash;
11155 err = check_cancelled(NULL);
11156 if (err)
11157 break;
11159 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11160 if (err)
11161 break;
11163 err = got_object_open_as_commit(&old_commit, repo,
11164 old_commit_id);
11165 if (err)
11166 break;
11168 if (strncmp(backup_ref_prefix, refname,
11169 backup_ref_prefix_len) == 0)
11170 refname += backup_ref_prefix_len;
11172 while (refname[0] == '/')
11173 refname++;
11175 branch_name = strdup(refname);
11176 if (branch_name == NULL) {
11177 err = got_error_from_errno("strdup");
11178 break;
11180 slash = strrchr(branch_name, '/');
11181 if (slash) {
11182 *slash = '\0';
11183 refname += strlen(branch_name) + 1;
11186 if (wanted_branch_name == NULL ||
11187 strcmp(wanted_branch_name, branch_name) == 0) {
11188 wanted_branch_found = 1;
11189 if (delete) {
11190 err = delete_backup_ref(re->ref,
11191 old_commit_id, repo);
11192 } else {
11193 err = print_backup_ref(branch_name, refname,
11194 old_commit_id, old_commit, refs_idmap,
11195 repo);
11197 if (err)
11198 break;
11201 free(old_commit_id);
11202 old_commit_id = NULL;
11203 free(branch_name);
11204 branch_name = NULL;
11205 got_object_commit_close(old_commit);
11206 old_commit = NULL;
11209 if (wanted_branch_name && !wanted_branch_found) {
11210 err = got_error_fmt(GOT_ERR_NOT_REF,
11211 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11213 done:
11214 if (refs_idmap)
11215 got_reflist_object_id_map_free(refs_idmap);
11216 got_ref_list_free(&refs);
11217 got_ref_list_free(&backup_refs);
11218 free(old_commit_id);
11219 free(branch_name);
11220 if (old_commit)
11221 got_object_commit_close(old_commit);
11222 return err;
11225 static const struct got_error *
11226 abort_progress(void *arg, unsigned char status, const char *path)
11229 * Unversioned files should not clutter progress output when
11230 * an operation is aborted.
11232 if (status == GOT_STATUS_UNVERSIONED)
11233 return NULL;
11235 return update_progress(arg, status, path);
11238 static const struct got_error *
11239 cmd_rebase(int argc, char *argv[])
11241 const struct got_error *error = NULL;
11242 struct got_worktree *worktree = NULL;
11243 struct got_repository *repo = NULL;
11244 struct got_fileindex *fileindex = NULL;
11245 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11246 struct got_reference *branch = NULL;
11247 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11248 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11249 struct got_object_id *resume_commit_id = NULL;
11250 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11251 struct got_object_id *head_commit_id = NULL;
11252 struct got_reference *head_ref = NULL;
11253 struct got_commit_object *commit = NULL;
11254 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11255 int histedit_in_progress = 0, merge_in_progress = 0;
11256 int create_backup = 1, list_backups = 0, delete_backups = 0;
11257 int allow_conflict = 0;
11258 struct got_object_id_queue commits;
11259 struct got_pathlist_head merged_paths;
11260 const struct got_object_id_queue *parent_ids;
11261 struct got_object_qid *qid, *pid;
11262 struct got_update_progress_arg upa;
11263 int *pack_fds = NULL;
11265 STAILQ_INIT(&commits);
11266 TAILQ_INIT(&merged_paths);
11267 memset(&upa, 0, sizeof(upa));
11269 #ifndef PROFILE
11270 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11271 "unveil", NULL) == -1)
11272 err(1, "pledge");
11273 #endif
11275 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11276 switch (ch) {
11277 case 'a':
11278 abort_rebase = 1;
11279 break;
11280 case 'C':
11281 allow_conflict = 1;
11282 break;
11283 case 'c':
11284 continue_rebase = 1;
11285 break;
11286 case 'l':
11287 list_backups = 1;
11288 break;
11289 case 'X':
11290 delete_backups = 1;
11291 break;
11292 default:
11293 usage_rebase();
11294 /* NOTREACHED */
11298 argc -= optind;
11299 argv += optind;
11301 if (list_backups) {
11302 if (abort_rebase)
11303 option_conflict('l', 'a');
11304 if (allow_conflict)
11305 option_conflict('l', 'C');
11306 if (continue_rebase)
11307 option_conflict('l', 'c');
11308 if (delete_backups)
11309 option_conflict('l', 'X');
11310 if (argc != 0 && argc != 1)
11311 usage_rebase();
11312 } else if (delete_backups) {
11313 if (abort_rebase)
11314 option_conflict('X', 'a');
11315 if (allow_conflict)
11316 option_conflict('X', 'C');
11317 if (continue_rebase)
11318 option_conflict('X', 'c');
11319 if (list_backups)
11320 option_conflict('l', 'X');
11321 if (argc != 0 && argc != 1)
11322 usage_rebase();
11323 } else if (allow_conflict) {
11324 if (abort_rebase)
11325 option_conflict('C', 'a');
11326 if (!continue_rebase)
11327 errx(1, "-C option requires -c");
11328 } else {
11329 if (abort_rebase && continue_rebase)
11330 usage_rebase();
11331 else if (abort_rebase || continue_rebase) {
11332 if (argc != 0)
11333 usage_rebase();
11334 } else if (argc != 1)
11335 usage_rebase();
11338 cwd = getcwd(NULL, 0);
11339 if (cwd == NULL) {
11340 error = got_error_from_errno("getcwd");
11341 goto done;
11344 error = got_repo_pack_fds_open(&pack_fds);
11345 if (error != NULL)
11346 goto done;
11348 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11349 if (error) {
11350 if (list_backups || delete_backups) {
11351 if (error->code != GOT_ERR_NOT_WORKTREE)
11352 goto done;
11353 } else {
11354 if (error->code == GOT_ERR_NOT_WORKTREE)
11355 error = wrap_not_worktree_error(error,
11356 "rebase", cwd);
11357 goto done;
11361 error = get_gitconfig_path(&gitconfig_path);
11362 if (error)
11363 goto done;
11364 error = got_repo_open(&repo,
11365 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11366 gitconfig_path, pack_fds);
11367 if (error != NULL)
11368 goto done;
11370 if (worktree != NULL && !list_backups && !delete_backups) {
11371 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11372 if (error)
11373 goto done;
11376 error = get_author(&committer, repo, worktree);
11377 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11378 goto done;
11380 error = apply_unveil(got_repo_get_path(repo), 0,
11381 worktree ? got_worktree_get_root_path(worktree) : NULL);
11382 if (error)
11383 goto done;
11385 if (list_backups || delete_backups) {
11386 error = process_backup_refs(
11387 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11388 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11389 goto done; /* nothing else to do */
11392 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11393 worktree);
11394 if (error)
11395 goto done;
11396 if (histedit_in_progress) {
11397 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11398 goto done;
11401 error = got_worktree_merge_in_progress(&merge_in_progress,
11402 worktree, repo);
11403 if (error)
11404 goto done;
11405 if (merge_in_progress) {
11406 error = got_error(GOT_ERR_MERGE_BUSY);
11407 goto done;
11410 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11411 if (error)
11412 goto done;
11414 if (abort_rebase) {
11415 if (!rebase_in_progress) {
11416 error = got_error(GOT_ERR_NOT_REBASING);
11417 goto done;
11419 error = got_worktree_rebase_continue(&resume_commit_id,
11420 &new_base_branch, &tmp_branch, &branch, &fileindex,
11421 worktree, repo);
11422 if (error)
11423 goto done;
11424 printf("Switching work tree to %s\n",
11425 got_ref_get_symref_target(new_base_branch));
11426 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11427 new_base_branch, abort_progress, &upa);
11428 if (error)
11429 goto done;
11430 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11431 print_merge_progress_stats(&upa);
11432 goto done; /* nothing else to do */
11435 if (continue_rebase) {
11436 if (!rebase_in_progress) {
11437 error = got_error(GOT_ERR_NOT_REBASING);
11438 goto done;
11440 error = got_worktree_rebase_continue(&resume_commit_id,
11441 &new_base_branch, &tmp_branch, &branch, &fileindex,
11442 worktree, repo);
11443 if (error)
11444 goto done;
11446 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11447 committer, resume_commit_id, allow_conflict, repo);
11448 if (error)
11449 goto done;
11451 yca_id = got_object_id_dup(resume_commit_id);
11452 if (yca_id == NULL) {
11453 error = got_error_from_errno("got_object_id_dup");
11454 goto done;
11456 } else {
11457 error = got_ref_open(&branch, repo, argv[0], 0);
11458 if (error != NULL)
11459 goto done;
11460 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11461 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11462 "will not rebase a branch which lives outside "
11463 "the \"refs/heads/\" reference namespace");
11464 goto done;
11468 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11469 if (error)
11470 goto done;
11472 if (!continue_rebase) {
11473 struct got_object_id *base_commit_id;
11475 error = got_ref_open(&head_ref, repo,
11476 got_worktree_get_head_ref_name(worktree), 0);
11477 if (error)
11478 goto done;
11479 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11480 if (error)
11481 goto done;
11482 base_commit_id = got_worktree_get_base_commit_id(worktree);
11483 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11484 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11485 goto done;
11488 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11489 base_commit_id, branch_head_commit_id, 1, repo,
11490 check_cancelled, NULL);
11491 if (error) {
11492 if (error->code == GOT_ERR_ANCESTRY) {
11493 error = got_error_msg(GOT_ERR_ANCESTRY,
11494 "specified branch shares no common "
11495 "ancestry with work tree's branch");
11497 goto done;
11500 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11501 struct got_pathlist_head paths;
11502 printf("%s is already based on %s\n",
11503 got_ref_get_name(branch),
11504 got_worktree_get_head_ref_name(worktree));
11505 error = switch_head_ref(branch, branch_head_commit_id,
11506 worktree, repo);
11507 if (error)
11508 goto done;
11509 error = got_worktree_set_base_commit_id(worktree, repo,
11510 branch_head_commit_id);
11511 if (error)
11512 goto done;
11513 TAILQ_INIT(&paths);
11514 error = got_pathlist_append(&paths, "", NULL);
11515 if (error)
11516 goto done;
11517 error = got_worktree_checkout_files(worktree,
11518 &paths, repo, update_progress, &upa,
11519 check_cancelled, NULL);
11520 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11521 if (error)
11522 goto done;
11523 if (upa.did_something) {
11524 char *id_str;
11525 error = got_object_id_str(&id_str,
11526 branch_head_commit_id);
11527 if (error)
11528 goto done;
11529 printf("Updated to %s: %s\n",
11530 got_worktree_get_head_ref_name(worktree),
11531 id_str);
11532 free(id_str);
11533 } else
11534 printf("Already up-to-date\n");
11535 print_update_progress_stats(&upa);
11536 goto done;
11540 commit_id = branch_head_commit_id;
11541 error = got_object_open_as_commit(&commit, repo, commit_id);
11542 if (error)
11543 goto done;
11545 parent_ids = got_object_commit_get_parent_ids(commit);
11546 pid = STAILQ_FIRST(parent_ids);
11547 if (pid) {
11548 error = collect_commits(&commits, commit_id, &pid->id,
11549 yca_id, got_worktree_get_path_prefix(worktree),
11550 GOT_ERR_REBASE_PATH, repo);
11551 if (error)
11552 goto done;
11555 got_object_commit_close(commit);
11556 commit = NULL;
11558 if (!continue_rebase) {
11559 error = got_worktree_rebase_prepare(&new_base_branch,
11560 &tmp_branch, &fileindex, worktree, branch, repo);
11561 if (error)
11562 goto done;
11565 if (STAILQ_EMPTY(&commits)) {
11566 if (continue_rebase) {
11567 error = rebase_complete(worktree, fileindex,
11568 branch, tmp_branch, repo, create_backup);
11569 goto done;
11570 } else {
11571 /* Fast-forward the reference of the branch. */
11572 struct got_object_id *new_head_commit_id;
11573 char *id_str;
11574 error = got_ref_resolve(&new_head_commit_id, repo,
11575 new_base_branch);
11576 if (error)
11577 goto done;
11578 error = got_object_id_str(&id_str, new_head_commit_id);
11579 if (error)
11580 goto done;
11581 printf("Forwarding %s to commit %s\n",
11582 got_ref_get_name(branch), id_str);
11583 free(id_str);
11584 error = got_ref_change_ref(branch,
11585 new_head_commit_id);
11586 if (error)
11587 goto done;
11588 /* No backup needed since objects did not change. */
11589 create_backup = 0;
11593 pid = NULL;
11594 STAILQ_FOREACH(qid, &commits, entry) {
11596 commit_id = &qid->id;
11597 parent_id = pid ? &pid->id : yca_id;
11598 pid = qid;
11600 memset(&upa, 0, sizeof(upa));
11601 error = got_worktree_rebase_merge_files(&merged_paths,
11602 worktree, fileindex, parent_id, commit_id, repo,
11603 update_progress, &upa, check_cancelled, NULL);
11604 if (error)
11605 goto done;
11607 print_merge_progress_stats(&upa);
11608 if (upa.conflicts > 0 || upa.missing > 0 ||
11609 upa.not_deleted > 0 || upa.unversioned > 0) {
11610 if (upa.conflicts > 0) {
11611 error = show_rebase_merge_conflict(&qid->id,
11612 repo);
11613 if (error)
11614 goto done;
11616 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11617 break;
11620 error = rebase_commit(&merged_paths, worktree, fileindex,
11621 tmp_branch, committer, commit_id, 0, repo);
11622 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11623 if (error)
11624 goto done;
11627 if (upa.conflicts > 0 || upa.missing > 0 ||
11628 upa.not_deleted > 0 || upa.unversioned > 0) {
11629 error = got_worktree_rebase_postpone(worktree, fileindex);
11630 if (error)
11631 goto done;
11632 if (upa.conflicts > 0 && upa.missing == 0 &&
11633 upa.not_deleted == 0 && upa.unversioned == 0) {
11634 error = got_error_msg(GOT_ERR_CONFLICTS,
11635 "conflicts must be resolved before rebasing "
11636 "can continue");
11637 } else if (upa.conflicts > 0) {
11638 error = got_error_msg(GOT_ERR_CONFLICTS,
11639 "conflicts must be resolved before rebasing "
11640 "can continue; changes destined for some "
11641 "files were not yet merged and should be "
11642 "merged manually if required before the "
11643 "rebase operation is continued");
11644 } else {
11645 error = got_error_msg(GOT_ERR_CONFLICTS,
11646 "changes destined for some files were not "
11647 "yet merged and should be merged manually "
11648 "if required before the rebase operation "
11649 "is continued");
11651 } else
11652 error = rebase_complete(worktree, fileindex, branch,
11653 tmp_branch, repo, create_backup);
11654 done:
11655 free(cwd);
11656 free(committer);
11657 free(gitconfig_path);
11658 got_object_id_queue_free(&commits);
11659 free(branch_head_commit_id);
11660 free(resume_commit_id);
11661 free(head_commit_id);
11662 free(yca_id);
11663 if (commit)
11664 got_object_commit_close(commit);
11665 if (branch)
11666 got_ref_close(branch);
11667 if (new_base_branch)
11668 got_ref_close(new_base_branch);
11669 if (tmp_branch)
11670 got_ref_close(tmp_branch);
11671 if (head_ref)
11672 got_ref_close(head_ref);
11673 if (worktree)
11674 got_worktree_close(worktree);
11675 if (repo) {
11676 const struct got_error *close_err = got_repo_close(repo);
11677 if (error == NULL)
11678 error = close_err;
11680 if (pack_fds) {
11681 const struct got_error *pack_err =
11682 got_repo_pack_fds_close(pack_fds);
11683 if (error == NULL)
11684 error = pack_err;
11686 return error;
11689 __dead static void
11690 usage_histedit(void)
11692 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11693 "[branch]\n", getprogname());
11694 exit(1);
11697 #define GOT_HISTEDIT_PICK 'p'
11698 #define GOT_HISTEDIT_EDIT 'e'
11699 #define GOT_HISTEDIT_FOLD 'f'
11700 #define GOT_HISTEDIT_DROP 'd'
11701 #define GOT_HISTEDIT_MESG 'm'
11703 static const struct got_histedit_cmd {
11704 unsigned char code;
11705 const char *name;
11706 const char *desc;
11707 } got_histedit_cmds[] = {
11708 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11709 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11710 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11711 "be used" },
11712 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11713 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11716 struct got_histedit_list_entry {
11717 TAILQ_ENTRY(got_histedit_list_entry) entry;
11718 struct got_object_id *commit_id;
11719 const struct got_histedit_cmd *cmd;
11720 char *logmsg;
11722 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11724 static const struct got_error *
11725 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11726 FILE *f, struct got_repository *repo)
11728 const struct got_error *err = NULL;
11729 char *logmsg = NULL, *id_str = NULL;
11730 struct got_commit_object *commit = NULL;
11731 int n;
11733 err = got_object_open_as_commit(&commit, repo, commit_id);
11734 if (err)
11735 goto done;
11737 err = get_short_logmsg(&logmsg, 34, commit);
11738 if (err)
11739 goto done;
11741 err = got_object_id_str(&id_str, commit_id);
11742 if (err)
11743 goto done;
11745 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11746 if (n < 0)
11747 err = got_ferror(f, GOT_ERR_IO);
11748 done:
11749 if (commit)
11750 got_object_commit_close(commit);
11751 free(id_str);
11752 free(logmsg);
11753 return err;
11756 static const struct got_error *
11757 histedit_write_commit_list(struct got_object_id_queue *commits,
11758 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11759 int edit_only, struct got_repository *repo)
11761 const struct got_error *err = NULL;
11762 struct got_object_qid *qid;
11763 const char *histedit_cmd = NULL;
11765 if (STAILQ_EMPTY(commits))
11766 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11768 STAILQ_FOREACH(qid, commits, entry) {
11769 histedit_cmd = got_histedit_cmds[0].name;
11770 if (drop_only)
11771 histedit_cmd = "drop";
11772 else if (edit_only)
11773 histedit_cmd = "edit";
11774 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11775 histedit_cmd = "fold";
11776 else if (edit_logmsg_only)
11777 histedit_cmd = "mesg";
11778 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11779 if (err)
11780 break;
11783 return err;
11786 static const struct got_error *
11787 write_cmd_list(FILE *f, const char *branch_name,
11788 struct got_object_id_queue *commits)
11790 const struct got_error *err = NULL;
11791 size_t i;
11792 int n;
11793 char *id_str;
11794 struct got_object_qid *qid;
11796 qid = STAILQ_FIRST(commits);
11797 err = got_object_id_str(&id_str, &qid->id);
11798 if (err)
11799 return err;
11801 n = fprintf(f,
11802 "# Editing the history of branch '%s' starting at\n"
11803 "# commit %s\n"
11804 "# Commits will be processed in order from top to "
11805 "bottom of this file.\n", branch_name, id_str);
11806 if (n < 0) {
11807 err = got_ferror(f, GOT_ERR_IO);
11808 goto done;
11811 n = fprintf(f, "# Available histedit commands:\n");
11812 if (n < 0) {
11813 err = got_ferror(f, GOT_ERR_IO);
11814 goto done;
11817 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11818 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11819 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11820 cmd->desc);
11821 if (n < 0) {
11822 err = got_ferror(f, GOT_ERR_IO);
11823 break;
11826 done:
11827 free(id_str);
11828 return err;
11831 static const struct got_error *
11832 histedit_syntax_error(int lineno)
11834 static char msg[42];
11835 int ret;
11837 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11838 lineno);
11839 if (ret < 0 || (size_t)ret >= sizeof(msg))
11840 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11842 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11845 static const struct got_error *
11846 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11847 char *logmsg, struct got_repository *repo)
11849 const struct got_error *err;
11850 struct got_commit_object *folded_commit = NULL;
11851 char *id_str, *folded_logmsg = NULL;
11853 err = got_object_id_str(&id_str, hle->commit_id);
11854 if (err)
11855 return err;
11857 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11858 if (err)
11859 goto done;
11861 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11862 if (err)
11863 goto done;
11864 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11865 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11866 folded_logmsg) == -1) {
11867 err = got_error_from_errno("asprintf");
11869 done:
11870 if (folded_commit)
11871 got_object_commit_close(folded_commit);
11872 free(id_str);
11873 free(folded_logmsg);
11874 return err;
11877 static struct got_histedit_list_entry *
11878 get_folded_commits(struct got_histedit_list_entry *hle)
11880 struct got_histedit_list_entry *prev, *folded = NULL;
11882 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11883 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11884 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11885 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11886 folded = prev;
11887 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11890 return folded;
11893 static const struct got_error *
11894 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11895 struct got_repository *repo)
11897 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11898 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11899 const struct got_error *err = NULL;
11900 struct got_commit_object *commit = NULL;
11901 int logmsg_len;
11902 int fd = -1;
11903 struct got_histedit_list_entry *folded = NULL;
11905 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11906 if (err)
11907 return err;
11909 folded = get_folded_commits(hle);
11910 if (folded) {
11911 while (folded != hle) {
11912 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11913 folded = TAILQ_NEXT(folded, entry);
11914 continue;
11916 err = append_folded_commit_msg(&new_msg, folded,
11917 logmsg, repo);
11918 if (err)
11919 goto done;
11920 free(logmsg);
11921 logmsg = new_msg;
11922 folded = TAILQ_NEXT(folded, entry);
11926 err = got_object_id_str(&id_str, hle->commit_id);
11927 if (err)
11928 goto done;
11929 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11930 if (err)
11931 goto done;
11932 logmsg_len = asprintf(&new_msg,
11933 "%s\n# original log message of commit %s: %s",
11934 logmsg ? logmsg : "", id_str, orig_logmsg);
11935 if (logmsg_len == -1) {
11936 err = got_error_from_errno("asprintf");
11937 goto done;
11939 free(logmsg);
11940 logmsg = new_msg;
11942 err = got_object_id_str(&id_str, hle->commit_id);
11943 if (err)
11944 goto done;
11946 err = got_opentemp_named_fd(&logmsg_path, &fd,
11947 GOT_TMPDIR_STR "/got-logmsg", "");
11948 if (err)
11949 goto done;
11951 if (write(fd, logmsg, logmsg_len) == -1) {
11952 err = got_error_from_errno2("write", logmsg_path);
11953 goto done;
11955 if (close(fd) == -1) {
11956 err = got_error_from_errno2("close", logmsg_path);
11957 goto done;
11959 fd = -1;
11961 err = get_editor(&editor);
11962 if (err)
11963 goto done;
11965 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11966 logmsg_len, 0);
11967 if (err) {
11968 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11969 goto done;
11970 err = NULL;
11971 hle->logmsg = strdup(new_msg);
11972 if (hle->logmsg == NULL)
11973 err = got_error_from_errno("strdup");
11975 done:
11976 if (fd != -1 && close(fd) == -1 && err == NULL)
11977 err = got_error_from_errno2("close", logmsg_path);
11978 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11979 err = got_error_from_errno2("unlink", logmsg_path);
11980 free(logmsg_path);
11981 free(logmsg);
11982 free(orig_logmsg);
11983 free(editor);
11984 if (commit)
11985 got_object_commit_close(commit);
11986 return err;
11989 static const struct got_error *
11990 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11991 FILE *f, struct got_repository *repo)
11993 const struct got_error *err = NULL;
11994 char *line = NULL, *p, *end;
11995 size_t i, linesize = 0;
11996 ssize_t linelen;
11997 int lineno = 0;
11998 const struct got_histedit_cmd *cmd;
11999 struct got_object_id *commit_id = NULL;
12000 struct got_histedit_list_entry *hle = NULL;
12002 for (;;) {
12003 linelen = getline(&line, &linesize, f);
12004 if (linelen == -1) {
12005 const struct got_error *getline_err;
12006 if (feof(f))
12007 break;
12008 getline_err = got_error_from_errno("getline");
12009 err = got_ferror(f, getline_err->code);
12010 break;
12012 lineno++;
12013 p = line;
12014 while (isspace((unsigned char)p[0]))
12015 p++;
12016 if (p[0] == '#' || p[0] == '\0')
12017 continue;
12018 cmd = NULL;
12019 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12020 cmd = &got_histedit_cmds[i];
12021 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12022 isspace((unsigned char)p[strlen(cmd->name)])) {
12023 p += strlen(cmd->name);
12024 break;
12026 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12027 p++;
12028 break;
12031 if (i == nitems(got_histedit_cmds)) {
12032 err = histedit_syntax_error(lineno);
12033 break;
12035 while (isspace((unsigned char)p[0]))
12036 p++;
12037 end = p;
12038 while (end[0] && !isspace((unsigned char)end[0]))
12039 end++;
12040 *end = '\0';
12041 err = got_object_resolve_id_str(&commit_id, repo, p);
12042 if (err) {
12043 /* override error code */
12044 err = histedit_syntax_error(lineno);
12045 break;
12047 hle = malloc(sizeof(*hle));
12048 if (hle == NULL) {
12049 err = got_error_from_errno("malloc");
12050 break;
12052 hle->cmd = cmd;
12053 hle->commit_id = commit_id;
12054 hle->logmsg = NULL;
12055 commit_id = NULL;
12056 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12059 free(line);
12060 free(commit_id);
12061 return err;
12064 static const struct got_error *
12065 histedit_check_script(struct got_histedit_list *histedit_cmds,
12066 struct got_object_id_queue *commits, struct got_repository *repo)
12068 const struct got_error *err = NULL;
12069 struct got_object_qid *qid;
12070 struct got_histedit_list_entry *hle;
12071 static char msg[92];
12072 char *id_str;
12074 if (TAILQ_EMPTY(histedit_cmds))
12075 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12076 "histedit script contains no commands");
12077 if (STAILQ_EMPTY(commits))
12078 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12080 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12081 struct got_histedit_list_entry *hle2;
12082 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12083 if (hle == hle2)
12084 continue;
12085 if (got_object_id_cmp(hle->commit_id,
12086 hle2->commit_id) != 0)
12087 continue;
12088 err = got_object_id_str(&id_str, hle->commit_id);
12089 if (err)
12090 return err;
12091 snprintf(msg, sizeof(msg), "commit %s is listed "
12092 "more than once in histedit script", id_str);
12093 free(id_str);
12094 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12098 STAILQ_FOREACH(qid, commits, entry) {
12099 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12100 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12101 break;
12103 if (hle == NULL) {
12104 err = got_object_id_str(&id_str, &qid->id);
12105 if (err)
12106 return err;
12107 snprintf(msg, sizeof(msg),
12108 "commit %s missing from histedit script", id_str);
12109 free(id_str);
12110 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12114 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12115 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12116 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12117 "last commit in histedit script cannot be folded");
12119 return NULL;
12122 static const struct got_error *
12123 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12124 const char *path, struct got_object_id_queue *commits,
12125 struct got_repository *repo)
12127 const struct got_error *err = NULL;
12128 struct stat st, st2;
12129 struct timespec timeout;
12130 char *editor;
12131 FILE *f = NULL;
12133 err = get_editor(&editor);
12134 if (err)
12135 return err;
12137 if (stat(path, &st) == -1) {
12138 err = got_error_from_errno2("stat", path);
12139 goto done;
12142 if (spawn_editor(editor, path) == -1) {
12143 err = got_error_from_errno("failed spawning editor");
12144 goto done;
12147 timeout.tv_sec = 0;
12148 timeout.tv_nsec = 1;
12149 nanosleep(&timeout, NULL);
12151 if (stat(path, &st2) == -1) {
12152 err = got_error_from_errno2("stat", path);
12153 goto done;
12156 if (st.st_size == st2.st_size &&
12157 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12158 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12159 "no changes made to histedit script, aborting");
12160 goto done;
12163 f = fopen(path, "re");
12164 if (f == NULL) {
12165 err = got_error_from_errno("fopen");
12166 goto done;
12168 err = histedit_parse_list(histedit_cmds, f, repo);
12169 if (err)
12170 goto done;
12172 err = histedit_check_script(histedit_cmds, commits, repo);
12173 done:
12174 if (f && fclose(f) == EOF && err == NULL)
12175 err = got_error_from_errno("fclose");
12176 free(editor);
12177 return err;
12180 static const struct got_error *
12181 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12182 struct got_object_id_queue *, const char *, const char *,
12183 struct got_repository *);
12185 static const struct got_error *
12186 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12187 struct got_object_id_queue *commits, const char *branch_name,
12188 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12189 struct got_repository *repo)
12191 const struct got_error *err;
12192 FILE *f = NULL;
12193 char *path = NULL;
12195 err = got_opentemp_named(&path, &f, "got-histedit", "");
12196 if (err)
12197 return err;
12199 err = write_cmd_list(f, branch_name, commits);
12200 if (err)
12201 goto done;
12203 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12204 fold_only, drop_only, edit_only, repo);
12205 if (err)
12206 goto done;
12208 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12209 rewind(f);
12210 err = histedit_parse_list(histedit_cmds, f, repo);
12211 } else {
12212 if (fclose(f) == EOF) {
12213 err = got_error_from_errno("fclose");
12214 goto done;
12216 f = NULL;
12217 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12218 if (err) {
12219 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12220 err->code != GOT_ERR_HISTEDIT_CMD)
12221 goto done;
12222 err = histedit_edit_list_retry(histedit_cmds, err,
12223 commits, path, branch_name, repo);
12226 done:
12227 if (f && fclose(f) == EOF && err == NULL)
12228 err = got_error_from_errno("fclose");
12229 if (path && unlink(path) != 0 && err == NULL)
12230 err = got_error_from_errno2("unlink", path);
12231 free(path);
12232 return err;
12235 static const struct got_error *
12236 histedit_save_list(struct got_histedit_list *histedit_cmds,
12237 struct got_worktree *worktree, struct got_repository *repo)
12239 const struct got_error *err = NULL;
12240 char *path = NULL;
12241 FILE *f = NULL;
12242 struct got_histedit_list_entry *hle;
12244 err = got_worktree_get_histedit_script_path(&path, worktree);
12245 if (err)
12246 return err;
12248 f = fopen(path, "we");
12249 if (f == NULL) {
12250 err = got_error_from_errno2("fopen", path);
12251 goto done;
12253 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12254 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12255 repo);
12256 if (err)
12257 break;
12259 done:
12260 if (f && fclose(f) == EOF && err == NULL)
12261 err = got_error_from_errno("fclose");
12262 free(path);
12263 return err;
12266 static void
12267 histedit_free_list(struct got_histedit_list *histedit_cmds)
12269 struct got_histedit_list_entry *hle;
12271 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12272 TAILQ_REMOVE(histedit_cmds, hle, entry);
12273 free(hle);
12277 static const struct got_error *
12278 histedit_load_list(struct got_histedit_list *histedit_cmds,
12279 const char *path, struct got_repository *repo)
12281 const struct got_error *err = NULL;
12282 FILE *f = NULL;
12284 f = fopen(path, "re");
12285 if (f == NULL) {
12286 err = got_error_from_errno2("fopen", path);
12287 goto done;
12290 err = histedit_parse_list(histedit_cmds, f, repo);
12291 done:
12292 if (f && fclose(f) == EOF && err == NULL)
12293 err = got_error_from_errno("fclose");
12294 return err;
12297 static const struct got_error *
12298 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12299 const struct got_error *edit_err, struct got_object_id_queue *commits,
12300 const char *path, const char *branch_name, struct got_repository *repo)
12302 const struct got_error *err = NULL, *prev_err = edit_err;
12303 int resp = ' ';
12305 while (resp != 'c' && resp != 'r' && resp != 'a') {
12306 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12307 "or (a)bort: ", getprogname(), prev_err->msg);
12308 resp = getchar();
12309 if (resp == '\n')
12310 resp = getchar();
12311 if (resp == 'c') {
12312 histedit_free_list(histedit_cmds);
12313 err = histedit_run_editor(histedit_cmds, path, commits,
12314 repo);
12315 if (err) {
12316 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12317 err->code != GOT_ERR_HISTEDIT_CMD)
12318 break;
12319 prev_err = err;
12320 resp = ' ';
12321 continue;
12323 break;
12324 } else if (resp == 'r') {
12325 histedit_free_list(histedit_cmds);
12326 err = histedit_edit_script(histedit_cmds,
12327 commits, branch_name, 0, 0, 0, 0, repo);
12328 if (err) {
12329 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12330 err->code != GOT_ERR_HISTEDIT_CMD)
12331 break;
12332 prev_err = err;
12333 resp = ' ';
12334 continue;
12336 break;
12337 } else if (resp == 'a') {
12338 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12339 break;
12340 } else
12341 printf("invalid response '%c'\n", resp);
12344 return err;
12347 static const struct got_error *
12348 histedit_complete(struct got_worktree *worktree,
12349 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12350 struct got_reference *branch, struct got_repository *repo)
12352 printf("Switching work tree to %s\n",
12353 got_ref_get_symref_target(branch));
12354 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12355 branch, repo);
12358 static const struct got_error *
12359 show_histedit_progress(struct got_commit_object *commit,
12360 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12362 const struct got_error *err;
12363 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12365 err = got_object_id_str(&old_id_str, hle->commit_id);
12366 if (err)
12367 goto done;
12369 if (new_id) {
12370 err = got_object_id_str(&new_id_str, new_id);
12371 if (err)
12372 goto done;
12375 old_id_str[12] = '\0';
12376 if (new_id_str)
12377 new_id_str[12] = '\0';
12379 if (hle->logmsg) {
12380 logmsg = strdup(hle->logmsg);
12381 if (logmsg == NULL) {
12382 err = got_error_from_errno("strdup");
12383 goto done;
12385 trim_logmsg(logmsg, 42);
12386 } else {
12387 err = get_short_logmsg(&logmsg, 42, commit);
12388 if (err)
12389 goto done;
12392 switch (hle->cmd->code) {
12393 case GOT_HISTEDIT_PICK:
12394 case GOT_HISTEDIT_EDIT:
12395 case GOT_HISTEDIT_MESG:
12396 printf("%s -> %s: %s\n", old_id_str,
12397 new_id_str ? new_id_str : "no-op change", logmsg);
12398 break;
12399 case GOT_HISTEDIT_DROP:
12400 case GOT_HISTEDIT_FOLD:
12401 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12402 logmsg);
12403 break;
12404 default:
12405 break;
12407 done:
12408 free(old_id_str);
12409 free(new_id_str);
12410 return err;
12413 static const struct got_error *
12414 histedit_commit(struct got_pathlist_head *merged_paths,
12415 struct got_worktree *worktree, struct got_fileindex *fileindex,
12416 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12417 const char *committer, int allow_conflict, struct got_repository *repo)
12419 const struct got_error *err;
12420 struct got_commit_object *commit;
12421 struct got_object_id *new_commit_id;
12423 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12424 && hle->logmsg == NULL) {
12425 err = histedit_edit_logmsg(hle, repo);
12426 if (err)
12427 return err;
12430 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12431 if (err)
12432 return err;
12434 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12435 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12436 hle->logmsg, allow_conflict, repo);
12437 if (err) {
12438 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12439 goto done;
12440 err = show_histedit_progress(commit, hle, NULL);
12441 } else {
12442 err = show_histedit_progress(commit, hle, new_commit_id);
12443 free(new_commit_id);
12445 done:
12446 got_object_commit_close(commit);
12447 return err;
12450 static const struct got_error *
12451 histedit_skip_commit(struct got_histedit_list_entry *hle,
12452 struct got_worktree *worktree, struct got_repository *repo)
12454 const struct got_error *error;
12455 struct got_commit_object *commit;
12457 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12458 repo);
12459 if (error)
12460 return error;
12462 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12463 if (error)
12464 return error;
12466 error = show_histedit_progress(commit, hle, NULL);
12467 got_object_commit_close(commit);
12468 return error;
12471 static const struct got_error *
12472 check_local_changes(void *arg, unsigned char status,
12473 unsigned char staged_status, const char *path,
12474 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12475 struct got_object_id *commit_id, int dirfd, const char *de_name)
12477 int *have_local_changes = arg;
12479 switch (status) {
12480 case GOT_STATUS_ADD:
12481 case GOT_STATUS_DELETE:
12482 case GOT_STATUS_MODIFY:
12483 case GOT_STATUS_CONFLICT:
12484 *have_local_changes = 1;
12485 return got_error(GOT_ERR_CANCELLED);
12486 default:
12487 break;
12490 switch (staged_status) {
12491 case GOT_STATUS_ADD:
12492 case GOT_STATUS_DELETE:
12493 case GOT_STATUS_MODIFY:
12494 *have_local_changes = 1;
12495 return got_error(GOT_ERR_CANCELLED);
12496 default:
12497 break;
12500 return NULL;
12503 static const struct got_error *
12504 cmd_histedit(int argc, char *argv[])
12506 const struct got_error *error = NULL;
12507 struct got_worktree *worktree = NULL;
12508 struct got_fileindex *fileindex = NULL;
12509 struct got_repository *repo = NULL;
12510 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12511 struct got_reference *branch = NULL;
12512 struct got_reference *tmp_branch = NULL;
12513 struct got_object_id *resume_commit_id = NULL;
12514 struct got_object_id *base_commit_id = NULL;
12515 struct got_object_id *head_commit_id = NULL;
12516 struct got_commit_object *commit = NULL;
12517 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12518 struct got_update_progress_arg upa;
12519 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12520 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12521 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12522 const char *edit_script_path = NULL;
12523 struct got_object_id_queue commits;
12524 struct got_pathlist_head merged_paths;
12525 const struct got_object_id_queue *parent_ids;
12526 struct got_object_qid *pid;
12527 struct got_histedit_list histedit_cmds;
12528 struct got_histedit_list_entry *hle;
12529 int *pack_fds = NULL;
12531 STAILQ_INIT(&commits);
12532 TAILQ_INIT(&histedit_cmds);
12533 TAILQ_INIT(&merged_paths);
12534 memset(&upa, 0, sizeof(upa));
12536 #ifndef PROFILE
12537 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12538 "unveil", NULL) == -1)
12539 err(1, "pledge");
12540 #endif
12542 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12543 switch (ch) {
12544 case 'a':
12545 abort_edit = 1;
12546 break;
12547 case 'C':
12548 allow_conflict = 1;
12549 break;
12550 case 'c':
12551 continue_edit = 1;
12552 break;
12553 case 'd':
12554 drop_only = 1;
12555 break;
12556 case 'e':
12557 edit_only = 1;
12558 break;
12559 case 'F':
12560 edit_script_path = optarg;
12561 break;
12562 case 'f':
12563 fold_only = 1;
12564 break;
12565 case 'l':
12566 list_backups = 1;
12567 break;
12568 case 'm':
12569 edit_logmsg_only = 1;
12570 break;
12571 case 'X':
12572 delete_backups = 1;
12573 break;
12574 default:
12575 usage_histedit();
12576 /* NOTREACHED */
12580 argc -= optind;
12581 argv += optind;
12583 if (abort_edit && allow_conflict)
12584 option_conflict('a', 'C');
12585 if (abort_edit && continue_edit)
12586 option_conflict('a', 'c');
12587 if (edit_script_path && allow_conflict)
12588 option_conflict('F', 'C');
12589 if (edit_script_path && edit_logmsg_only)
12590 option_conflict('F', 'm');
12591 if (abort_edit && edit_logmsg_only)
12592 option_conflict('a', 'm');
12593 if (edit_logmsg_only && allow_conflict)
12594 option_conflict('m', 'C');
12595 if (continue_edit && edit_logmsg_only)
12596 option_conflict('c', 'm');
12597 if (abort_edit && fold_only)
12598 option_conflict('a', 'f');
12599 if (fold_only && allow_conflict)
12600 option_conflict('f', 'C');
12601 if (continue_edit && fold_only)
12602 option_conflict('c', 'f');
12603 if (fold_only && edit_logmsg_only)
12604 option_conflict('f', 'm');
12605 if (edit_script_path && fold_only)
12606 option_conflict('F', 'f');
12607 if (abort_edit && edit_only)
12608 option_conflict('a', 'e');
12609 if (continue_edit && edit_only)
12610 option_conflict('c', 'e');
12611 if (edit_only && edit_logmsg_only)
12612 option_conflict('e', 'm');
12613 if (edit_script_path && edit_only)
12614 option_conflict('F', 'e');
12615 if (fold_only && edit_only)
12616 option_conflict('f', 'e');
12617 if (drop_only && abort_edit)
12618 option_conflict('d', 'a');
12619 if (drop_only && allow_conflict)
12620 option_conflict('d', 'C');
12621 if (drop_only && continue_edit)
12622 option_conflict('d', 'c');
12623 if (drop_only && edit_logmsg_only)
12624 option_conflict('d', 'm');
12625 if (drop_only && edit_only)
12626 option_conflict('d', 'e');
12627 if (drop_only && edit_script_path)
12628 option_conflict('d', 'F');
12629 if (drop_only && fold_only)
12630 option_conflict('d', 'f');
12631 if (list_backups) {
12632 if (abort_edit)
12633 option_conflict('l', 'a');
12634 if (allow_conflict)
12635 option_conflict('l', 'C');
12636 if (continue_edit)
12637 option_conflict('l', 'c');
12638 if (edit_script_path)
12639 option_conflict('l', 'F');
12640 if (edit_logmsg_only)
12641 option_conflict('l', 'm');
12642 if (drop_only)
12643 option_conflict('l', 'd');
12644 if (fold_only)
12645 option_conflict('l', 'f');
12646 if (edit_only)
12647 option_conflict('l', 'e');
12648 if (delete_backups)
12649 option_conflict('l', 'X');
12650 if (argc != 0 && argc != 1)
12651 usage_histedit();
12652 } else if (delete_backups) {
12653 if (abort_edit)
12654 option_conflict('X', 'a');
12655 if (allow_conflict)
12656 option_conflict('X', 'C');
12657 if (continue_edit)
12658 option_conflict('X', 'c');
12659 if (drop_only)
12660 option_conflict('X', 'd');
12661 if (edit_script_path)
12662 option_conflict('X', 'F');
12663 if (edit_logmsg_only)
12664 option_conflict('X', 'm');
12665 if (fold_only)
12666 option_conflict('X', 'f');
12667 if (edit_only)
12668 option_conflict('X', 'e');
12669 if (list_backups)
12670 option_conflict('X', 'l');
12671 if (argc != 0 && argc != 1)
12672 usage_histedit();
12673 } else if (allow_conflict && !continue_edit)
12674 errx(1, "-C option requires -c");
12675 else if (argc != 0)
12676 usage_histedit();
12679 * This command cannot apply unveil(2) in all cases because the
12680 * user may choose to run an editor to edit the histedit script
12681 * and to edit individual commit log messages.
12682 * unveil(2) traverses exec(2); if an editor is used we have to
12683 * apply unveil after edit script and log messages have been written.
12684 * XXX TODO: Make use of unveil(2) where possible.
12687 cwd = getcwd(NULL, 0);
12688 if (cwd == NULL) {
12689 error = got_error_from_errno("getcwd");
12690 goto done;
12693 error = got_repo_pack_fds_open(&pack_fds);
12694 if (error != NULL)
12695 goto done;
12697 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12698 if (error) {
12699 if (list_backups || delete_backups) {
12700 if (error->code != GOT_ERR_NOT_WORKTREE)
12701 goto done;
12702 } else {
12703 if (error->code == GOT_ERR_NOT_WORKTREE)
12704 error = wrap_not_worktree_error(error,
12705 "histedit", cwd);
12706 goto done;
12710 if (list_backups || delete_backups) {
12711 error = got_repo_open(&repo,
12712 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12713 NULL, pack_fds);
12714 if (error != NULL)
12715 goto done;
12716 error = apply_unveil(got_repo_get_path(repo), 0,
12717 worktree ? got_worktree_get_root_path(worktree) : NULL);
12718 if (error)
12719 goto done;
12720 error = process_backup_refs(
12721 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12722 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12723 goto done; /* nothing else to do */
12726 error = get_gitconfig_path(&gitconfig_path);
12727 if (error)
12728 goto done;
12729 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12730 gitconfig_path, pack_fds);
12731 if (error != NULL)
12732 goto done;
12734 if (worktree != NULL && !list_backups && !delete_backups) {
12735 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12736 if (error)
12737 goto done;
12740 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12741 if (error)
12742 goto done;
12743 if (rebase_in_progress) {
12744 error = got_error(GOT_ERR_REBASING);
12745 goto done;
12748 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12749 repo);
12750 if (error)
12751 goto done;
12752 if (merge_in_progress) {
12753 error = got_error(GOT_ERR_MERGE_BUSY);
12754 goto done;
12757 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12758 if (error)
12759 goto done;
12761 if (edit_in_progress && edit_logmsg_only) {
12762 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12763 "histedit operation is in progress in this "
12764 "work tree and must be continued or aborted "
12765 "before the -m option can be used");
12766 goto done;
12768 if (edit_in_progress && drop_only) {
12769 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12770 "histedit operation is in progress in this "
12771 "work tree and must be continued or aborted "
12772 "before the -d option can be used");
12773 goto done;
12775 if (edit_in_progress && fold_only) {
12776 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12777 "histedit operation is in progress in this "
12778 "work tree and must be continued or aborted "
12779 "before the -f option can be used");
12780 goto done;
12782 if (edit_in_progress && edit_only) {
12783 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12784 "histedit operation is in progress in this "
12785 "work tree and must be continued or aborted "
12786 "before the -e option can be used");
12787 goto done;
12790 if (edit_in_progress && abort_edit) {
12791 error = got_worktree_histedit_continue(&resume_commit_id,
12792 &tmp_branch, &branch, &base_commit_id, &fileindex,
12793 worktree, repo);
12794 if (error)
12795 goto done;
12796 printf("Switching work tree to %s\n",
12797 got_ref_get_symref_target(branch));
12798 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12799 branch, base_commit_id, abort_progress, &upa);
12800 if (error)
12801 goto done;
12802 printf("Histedit of %s aborted\n",
12803 got_ref_get_symref_target(branch));
12804 print_merge_progress_stats(&upa);
12805 goto done; /* nothing else to do */
12806 } else if (abort_edit) {
12807 error = got_error(GOT_ERR_NOT_HISTEDIT);
12808 goto done;
12811 error = get_author(&committer, repo, worktree);
12812 if (error)
12813 goto done;
12815 if (continue_edit) {
12816 char *path;
12818 if (!edit_in_progress) {
12819 error = got_error(GOT_ERR_NOT_HISTEDIT);
12820 goto done;
12823 error = got_worktree_get_histedit_script_path(&path, worktree);
12824 if (error)
12825 goto done;
12827 error = histedit_load_list(&histedit_cmds, path, repo);
12828 free(path);
12829 if (error)
12830 goto done;
12832 error = got_worktree_histedit_continue(&resume_commit_id,
12833 &tmp_branch, &branch, &base_commit_id, &fileindex,
12834 worktree, repo);
12835 if (error)
12836 goto done;
12838 error = got_ref_resolve(&head_commit_id, repo, branch);
12839 if (error)
12840 goto done;
12842 error = got_object_open_as_commit(&commit, repo,
12843 head_commit_id);
12844 if (error)
12845 goto done;
12846 parent_ids = got_object_commit_get_parent_ids(commit);
12847 pid = STAILQ_FIRST(parent_ids);
12848 if (pid == NULL) {
12849 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12850 goto done;
12852 error = collect_commits(&commits, head_commit_id, &pid->id,
12853 base_commit_id, got_worktree_get_path_prefix(worktree),
12854 GOT_ERR_HISTEDIT_PATH, repo);
12855 got_object_commit_close(commit);
12856 commit = NULL;
12857 if (error)
12858 goto done;
12859 } else {
12860 if (edit_in_progress) {
12861 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12862 goto done;
12865 error = got_ref_open(&branch, repo,
12866 got_worktree_get_head_ref_name(worktree), 0);
12867 if (error != NULL)
12868 goto done;
12870 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12871 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12872 "will not edit commit history of a branch outside "
12873 "the \"refs/heads/\" reference namespace");
12874 goto done;
12877 error = got_ref_resolve(&head_commit_id, repo, branch);
12878 got_ref_close(branch);
12879 branch = NULL;
12880 if (error)
12881 goto done;
12883 error = got_object_open_as_commit(&commit, repo,
12884 head_commit_id);
12885 if (error)
12886 goto done;
12887 parent_ids = got_object_commit_get_parent_ids(commit);
12888 pid = STAILQ_FIRST(parent_ids);
12889 if (pid == NULL) {
12890 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12891 goto done;
12893 error = collect_commits(&commits, head_commit_id, &pid->id,
12894 got_worktree_get_base_commit_id(worktree),
12895 got_worktree_get_path_prefix(worktree),
12896 GOT_ERR_HISTEDIT_PATH, repo);
12897 got_object_commit_close(commit);
12898 commit = NULL;
12899 if (error)
12900 goto done;
12902 if (STAILQ_EMPTY(&commits)) {
12903 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12904 goto done;
12907 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12908 &base_commit_id, &fileindex, worktree, repo);
12909 if (error)
12910 goto done;
12912 if (edit_script_path) {
12913 error = histedit_load_list(&histedit_cmds,
12914 edit_script_path, repo);
12915 if (error) {
12916 got_worktree_histedit_abort(worktree, fileindex,
12917 repo, branch, base_commit_id,
12918 abort_progress, &upa);
12919 print_merge_progress_stats(&upa);
12920 goto done;
12922 } else {
12923 const char *branch_name;
12924 branch_name = got_ref_get_symref_target(branch);
12925 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12926 branch_name += 11;
12927 error = histedit_edit_script(&histedit_cmds, &commits,
12928 branch_name, edit_logmsg_only, fold_only,
12929 drop_only, edit_only, repo);
12930 if (error) {
12931 got_worktree_histedit_abort(worktree, fileindex,
12932 repo, branch, base_commit_id,
12933 abort_progress, &upa);
12934 print_merge_progress_stats(&upa);
12935 goto done;
12940 error = histedit_save_list(&histedit_cmds, worktree,
12941 repo);
12942 if (error) {
12943 got_worktree_histedit_abort(worktree, fileindex,
12944 repo, branch, base_commit_id,
12945 abort_progress, &upa);
12946 print_merge_progress_stats(&upa);
12947 goto done;
12952 error = histedit_check_script(&histedit_cmds, &commits, repo);
12953 if (error)
12954 goto done;
12956 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12957 if (resume_commit_id) {
12958 if (got_object_id_cmp(hle->commit_id,
12959 resume_commit_id) != 0)
12960 continue;
12962 resume_commit_id = NULL;
12963 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12964 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12965 error = histedit_skip_commit(hle, worktree,
12966 repo);
12967 if (error)
12968 goto done;
12969 } else {
12970 struct got_pathlist_head paths;
12971 int have_changes = 0;
12973 TAILQ_INIT(&paths);
12974 error = got_pathlist_append(&paths, "", NULL);
12975 if (error)
12976 goto done;
12977 error = got_worktree_status(worktree, &paths,
12978 repo, 0, check_local_changes, &have_changes,
12979 check_cancelled, NULL);
12980 got_pathlist_free(&paths,
12981 GOT_PATHLIST_FREE_NONE);
12982 if (error) {
12983 if (error->code != GOT_ERR_CANCELLED)
12984 goto done;
12985 if (sigint_received || sigpipe_received)
12986 goto done;
12988 if (have_changes) {
12989 error = histedit_commit(NULL, worktree,
12990 fileindex, tmp_branch, hle,
12991 committer, allow_conflict, repo);
12992 if (error)
12993 goto done;
12994 } else {
12995 error = got_object_open_as_commit(
12996 &commit, repo, hle->commit_id);
12997 if (error)
12998 goto done;
12999 error = show_histedit_progress(commit,
13000 hle, NULL);
13001 got_object_commit_close(commit);
13002 commit = NULL;
13003 if (error)
13004 goto done;
13007 continue;
13010 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13011 error = histedit_skip_commit(hle, worktree, repo);
13012 if (error)
13013 goto done;
13014 continue;
13016 error = got_object_open_as_commit(&commit, repo,
13017 hle->commit_id);
13018 if (error)
13019 goto done;
13020 parent_ids = got_object_commit_get_parent_ids(commit);
13021 pid = STAILQ_FIRST(parent_ids);
13023 error = got_worktree_histedit_merge_files(&merged_paths,
13024 worktree, fileindex, &pid->id, hle->commit_id, repo,
13025 update_progress, &upa, check_cancelled, NULL);
13026 if (error)
13027 goto done;
13028 got_object_commit_close(commit);
13029 commit = NULL;
13031 print_merge_progress_stats(&upa);
13032 if (upa.conflicts > 0 || upa.missing > 0 ||
13033 upa.not_deleted > 0 || upa.unversioned > 0) {
13034 if (upa.conflicts > 0) {
13035 error = show_rebase_merge_conflict(
13036 hle->commit_id, repo);
13037 if (error)
13038 goto done;
13040 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13041 break;
13044 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13045 char *id_str;
13046 error = got_object_id_str(&id_str, hle->commit_id);
13047 if (error)
13048 goto done;
13049 printf("Stopping histedit for amending commit %s\n",
13050 id_str);
13051 free(id_str);
13052 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13053 error = got_worktree_histedit_postpone(worktree,
13054 fileindex);
13055 goto done;
13056 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13057 error = histedit_skip_commit(hle, worktree, repo);
13058 if (error)
13059 goto done;
13060 continue;
13061 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13062 error = histedit_edit_logmsg(hle, repo);
13063 if (error)
13064 goto done;
13067 error = histedit_commit(&merged_paths, worktree, fileindex,
13068 tmp_branch, hle, committer, allow_conflict, repo);
13069 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13070 if (error)
13071 goto done;
13074 if (upa.conflicts > 0 || upa.missing > 0 ||
13075 upa.not_deleted > 0 || upa.unversioned > 0) {
13076 error = got_worktree_histedit_postpone(worktree, fileindex);
13077 if (error)
13078 goto done;
13079 if (upa.conflicts > 0 && upa.missing == 0 &&
13080 upa.not_deleted == 0 && upa.unversioned == 0) {
13081 error = got_error_msg(GOT_ERR_CONFLICTS,
13082 "conflicts must be resolved before histedit "
13083 "can continue");
13084 } else if (upa.conflicts > 0) {
13085 error = got_error_msg(GOT_ERR_CONFLICTS,
13086 "conflicts must be resolved before histedit "
13087 "can continue; changes destined for some "
13088 "files were not yet merged and should be "
13089 "merged manually if required before the "
13090 "histedit operation is continued");
13091 } else {
13092 error = got_error_msg(GOT_ERR_CONFLICTS,
13093 "changes destined for some files were not "
13094 "yet merged and should be merged manually "
13095 "if required before the histedit operation "
13096 "is continued");
13098 } else
13099 error = histedit_complete(worktree, fileindex, tmp_branch,
13100 branch, repo);
13101 done:
13102 free(cwd);
13103 free(committer);
13104 free(gitconfig_path);
13105 got_object_id_queue_free(&commits);
13106 histedit_free_list(&histedit_cmds);
13107 free(head_commit_id);
13108 free(base_commit_id);
13109 free(resume_commit_id);
13110 if (commit)
13111 got_object_commit_close(commit);
13112 if (branch)
13113 got_ref_close(branch);
13114 if (tmp_branch)
13115 got_ref_close(tmp_branch);
13116 if (worktree)
13117 got_worktree_close(worktree);
13118 if (repo) {
13119 const struct got_error *close_err = got_repo_close(repo);
13120 if (error == NULL)
13121 error = close_err;
13123 if (pack_fds) {
13124 const struct got_error *pack_err =
13125 got_repo_pack_fds_close(pack_fds);
13126 if (error == NULL)
13127 error = pack_err;
13129 return error;
13132 __dead static void
13133 usage_integrate(void)
13135 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13136 exit(1);
13139 static const struct got_error *
13140 cmd_integrate(int argc, char *argv[])
13142 const struct got_error *error = NULL;
13143 struct got_repository *repo = NULL;
13144 struct got_worktree *worktree = NULL;
13145 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13146 const char *branch_arg = NULL;
13147 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13148 struct got_fileindex *fileindex = NULL;
13149 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13150 int ch;
13151 struct got_update_progress_arg upa;
13152 int *pack_fds = NULL;
13154 #ifndef PROFILE
13155 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13156 "unveil", NULL) == -1)
13157 err(1, "pledge");
13158 #endif
13160 while ((ch = getopt(argc, argv, "")) != -1) {
13161 switch (ch) {
13162 default:
13163 usage_integrate();
13164 /* NOTREACHED */
13168 argc -= optind;
13169 argv += optind;
13171 if (argc != 1)
13172 usage_integrate();
13173 branch_arg = argv[0];
13175 cwd = getcwd(NULL, 0);
13176 if (cwd == NULL) {
13177 error = got_error_from_errno("getcwd");
13178 goto done;
13181 error = got_repo_pack_fds_open(&pack_fds);
13182 if (error != NULL)
13183 goto done;
13185 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13186 if (error) {
13187 if (error->code == GOT_ERR_NOT_WORKTREE)
13188 error = wrap_not_worktree_error(error, "integrate",
13189 cwd);
13190 goto done;
13193 error = check_rebase_or_histedit_in_progress(worktree);
13194 if (error)
13195 goto done;
13197 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13198 NULL, pack_fds);
13199 if (error != NULL)
13200 goto done;
13202 error = apply_unveil(got_repo_get_path(repo), 0,
13203 got_worktree_get_root_path(worktree));
13204 if (error)
13205 goto done;
13207 error = check_merge_in_progress(worktree, repo);
13208 if (error)
13209 goto done;
13211 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13212 error = got_error_from_errno("asprintf");
13213 goto done;
13216 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13217 &base_branch_ref, worktree, refname, repo);
13218 if (error)
13219 goto done;
13221 refname = strdup(got_ref_get_name(branch_ref));
13222 if (refname == NULL) {
13223 error = got_error_from_errno("strdup");
13224 got_worktree_integrate_abort(worktree, fileindex, repo,
13225 branch_ref, base_branch_ref);
13226 goto done;
13228 base_refname = strdup(got_ref_get_name(base_branch_ref));
13229 if (base_refname == NULL) {
13230 error = got_error_from_errno("strdup");
13231 got_worktree_integrate_abort(worktree, fileindex, repo,
13232 branch_ref, base_branch_ref);
13233 goto done;
13235 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13236 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13237 got_worktree_integrate_abort(worktree, fileindex, repo,
13238 branch_ref, base_branch_ref);
13239 goto done;
13242 error = got_ref_resolve(&commit_id, repo, branch_ref);
13243 if (error)
13244 goto done;
13246 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13247 if (error)
13248 goto done;
13250 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13251 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13252 "specified branch has already been integrated");
13253 got_worktree_integrate_abort(worktree, fileindex, repo,
13254 branch_ref, base_branch_ref);
13255 goto done;
13258 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13259 if (error) {
13260 if (error->code == GOT_ERR_ANCESTRY)
13261 error = got_error(GOT_ERR_REBASE_REQUIRED);
13262 got_worktree_integrate_abort(worktree, fileindex, repo,
13263 branch_ref, base_branch_ref);
13264 goto done;
13267 memset(&upa, 0, sizeof(upa));
13268 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13269 branch_ref, base_branch_ref, update_progress, &upa,
13270 check_cancelled, NULL);
13271 if (error)
13272 goto done;
13274 printf("Integrated %s into %s\n", refname, base_refname);
13275 print_update_progress_stats(&upa);
13276 done:
13277 if (repo) {
13278 const struct got_error *close_err = got_repo_close(repo);
13279 if (error == NULL)
13280 error = close_err;
13282 if (worktree)
13283 got_worktree_close(worktree);
13284 if (pack_fds) {
13285 const struct got_error *pack_err =
13286 got_repo_pack_fds_close(pack_fds);
13287 if (error == NULL)
13288 error = pack_err;
13290 free(cwd);
13291 free(base_commit_id);
13292 free(commit_id);
13293 free(refname);
13294 free(base_refname);
13295 return error;
13298 __dead static void
13299 usage_merge(void)
13301 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13302 exit(1);
13305 static const struct got_error *
13306 cmd_merge(int argc, char *argv[])
13308 const struct got_error *error = NULL;
13309 struct got_worktree *worktree = NULL;
13310 struct got_repository *repo = NULL;
13311 struct got_fileindex *fileindex = NULL;
13312 char *cwd = NULL, *id_str = NULL, *author = NULL;
13313 char *gitconfig_path = NULL;
13314 struct got_reference *branch = NULL, *wt_branch = NULL;
13315 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13316 struct got_object_id *wt_branch_tip = NULL;
13317 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13318 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13319 struct got_update_progress_arg upa;
13320 struct got_object_id *merge_commit_id = NULL;
13321 char *branch_name = NULL;
13322 int *pack_fds = NULL;
13324 memset(&upa, 0, sizeof(upa));
13326 #ifndef PROFILE
13327 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13328 "unveil", NULL) == -1)
13329 err(1, "pledge");
13330 #endif
13332 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13333 switch (ch) {
13334 case 'a':
13335 abort_merge = 1;
13336 break;
13337 case 'C':
13338 allow_conflict = 1;
13339 break;
13340 case 'c':
13341 continue_merge = 1;
13342 break;
13343 case 'M':
13344 prefer_fast_forward = 0;
13345 break;
13346 case 'n':
13347 interrupt_merge = 1;
13348 break;
13349 default:
13350 usage_merge();
13351 /* NOTREACHED */
13355 argc -= optind;
13356 argv += optind;
13358 if (abort_merge) {
13359 if (continue_merge)
13360 option_conflict('a', 'c');
13361 if (!prefer_fast_forward)
13362 option_conflict('a', 'M');
13363 if (interrupt_merge)
13364 option_conflict('a', 'n');
13365 } else if (continue_merge) {
13366 if (!prefer_fast_forward)
13367 option_conflict('c', 'M');
13368 if (interrupt_merge)
13369 option_conflict('c', 'n');
13371 if (allow_conflict) {
13372 if (!continue_merge)
13373 errx(1, "-C option requires -c");
13375 if (abort_merge || continue_merge) {
13376 if (argc != 0)
13377 usage_merge();
13378 } else if (argc != 1)
13379 usage_merge();
13381 cwd = getcwd(NULL, 0);
13382 if (cwd == NULL) {
13383 error = got_error_from_errno("getcwd");
13384 goto done;
13387 error = got_repo_pack_fds_open(&pack_fds);
13388 if (error != NULL)
13389 goto done;
13391 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13392 if (error) {
13393 if (error->code == GOT_ERR_NOT_WORKTREE)
13394 error = wrap_not_worktree_error(error,
13395 "merge", cwd);
13396 goto done;
13399 error = get_gitconfig_path(&gitconfig_path);
13400 if (error)
13401 goto done;
13402 error = got_repo_open(&repo,
13403 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13404 gitconfig_path, pack_fds);
13405 if (error != NULL)
13406 goto done;
13408 if (worktree != NULL) {
13409 error = worktree_has_logmsg_ref("merge", worktree, repo);
13410 if (error)
13411 goto done;
13414 error = apply_unveil(got_repo_get_path(repo), 0,
13415 worktree ? got_worktree_get_root_path(worktree) : NULL);
13416 if (error)
13417 goto done;
13419 error = check_rebase_or_histedit_in_progress(worktree);
13420 if (error)
13421 goto done;
13423 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13424 repo);
13425 if (error)
13426 goto done;
13428 if (merge_in_progress && !(abort_merge || continue_merge)) {
13429 error = got_error(GOT_ERR_MERGE_BUSY);
13430 goto done;
13433 if (!merge_in_progress && (abort_merge || continue_merge)) {
13434 error = got_error(GOT_ERR_NOT_MERGING);
13435 goto done;
13438 if (abort_merge) {
13439 error = got_worktree_merge_continue(&branch_name,
13440 &branch_tip, &fileindex, worktree, repo);
13441 if (error)
13442 goto done;
13443 error = got_worktree_merge_abort(worktree, fileindex, repo,
13444 abort_progress, &upa);
13445 if (error)
13446 goto done;
13447 printf("Merge of %s aborted\n", branch_name);
13448 goto done; /* nothing else to do */
13451 if (strncmp(got_worktree_get_head_ref_name(worktree),
13452 "refs/heads/", 11) != 0) {
13453 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13454 "work tree's current branch %s is outside the "
13455 "\"refs/heads/\" reference namespace; "
13456 "update -b required",
13457 got_worktree_get_head_ref_name(worktree));
13458 goto done;
13461 error = get_author(&author, repo, worktree);
13462 if (error)
13463 goto done;
13465 error = got_ref_open(&wt_branch, repo,
13466 got_worktree_get_head_ref_name(worktree), 0);
13467 if (error)
13468 goto done;
13469 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13470 if (error)
13471 goto done;
13473 if (continue_merge) {
13474 struct got_object_id *base_commit_id;
13475 base_commit_id = got_worktree_get_base_commit_id(worktree);
13476 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13477 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13478 goto done;
13480 error = got_worktree_merge_continue(&branch_name,
13481 &branch_tip, &fileindex, worktree, repo);
13482 if (error)
13483 goto done;
13484 } else {
13485 error = got_ref_open(&branch, repo, argv[0], 0);
13486 if (error != NULL)
13487 goto done;
13488 branch_name = strdup(got_ref_get_name(branch));
13489 if (branch_name == NULL) {
13490 error = got_error_from_errno("strdup");
13491 goto done;
13493 error = got_ref_resolve(&branch_tip, repo, branch);
13494 if (error)
13495 goto done;
13498 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13499 wt_branch_tip, branch_tip, 0, repo,
13500 check_cancelled, NULL);
13501 if (error && error->code != GOT_ERR_ANCESTRY)
13502 goto done;
13504 if (!continue_merge) {
13505 error = check_path_prefix(wt_branch_tip, branch_tip,
13506 got_worktree_get_path_prefix(worktree),
13507 GOT_ERR_MERGE_PATH, repo);
13508 if (error)
13509 goto done;
13510 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13511 if (error)
13512 goto done;
13513 if (prefer_fast_forward && yca_id &&
13514 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13515 struct got_pathlist_head paths;
13516 if (interrupt_merge) {
13517 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13518 "there are no changes to merge since %s "
13519 "is already based on %s; merge cannot be "
13520 "interrupted for amending; -n",
13521 branch_name, got_ref_get_name(wt_branch));
13522 goto done;
13524 printf("Forwarding %s to %s\n",
13525 got_ref_get_name(wt_branch), branch_name);
13526 error = got_ref_change_ref(wt_branch, branch_tip);
13527 if (error)
13528 goto done;
13529 error = got_ref_write(wt_branch, repo);
13530 if (error)
13531 goto done;
13532 error = got_worktree_set_base_commit_id(worktree, repo,
13533 branch_tip);
13534 if (error)
13535 goto done;
13536 TAILQ_INIT(&paths);
13537 error = got_pathlist_append(&paths, "", NULL);
13538 if (error)
13539 goto done;
13540 error = got_worktree_checkout_files(worktree,
13541 &paths, repo, update_progress, &upa,
13542 check_cancelled, NULL);
13543 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13544 if (error)
13545 goto done;
13546 if (upa.did_something) {
13547 char *id_str;
13548 error = got_object_id_str(&id_str, branch_tip);
13549 if (error)
13550 goto done;
13551 printf("Updated to commit %s\n", id_str);
13552 free(id_str);
13553 } else
13554 printf("Already up-to-date\n");
13555 print_update_progress_stats(&upa);
13556 goto done;
13558 error = got_worktree_merge_write_refs(worktree, branch, repo);
13559 if (error)
13560 goto done;
13562 error = got_worktree_merge_branch(worktree, fileindex,
13563 yca_id, branch_tip, repo, update_progress, &upa,
13564 check_cancelled, NULL);
13565 if (error)
13566 goto done;
13567 print_merge_progress_stats(&upa);
13568 if (!upa.did_something) {
13569 error = got_worktree_merge_abort(worktree, fileindex,
13570 repo, abort_progress, &upa);
13571 if (error)
13572 goto done;
13573 printf("Already up-to-date\n");
13574 goto done;
13578 if (interrupt_merge) {
13579 error = got_worktree_merge_postpone(worktree, fileindex);
13580 if (error)
13581 goto done;
13582 printf("Merge of %s interrupted on request\n", branch_name);
13583 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13584 upa.not_deleted > 0 || upa.unversioned > 0) {
13585 error = got_worktree_merge_postpone(worktree, fileindex);
13586 if (error)
13587 goto done;
13588 if (upa.conflicts > 0 && upa.missing == 0 &&
13589 upa.not_deleted == 0 && upa.unversioned == 0) {
13590 error = got_error_msg(GOT_ERR_CONFLICTS,
13591 "conflicts must be resolved before merging "
13592 "can continue");
13593 } else if (upa.conflicts > 0) {
13594 error = got_error_msg(GOT_ERR_CONFLICTS,
13595 "conflicts must be resolved before merging "
13596 "can continue; changes destined for some "
13597 "files were not yet merged and "
13598 "should be merged manually if required before the "
13599 "merge operation is continued");
13600 } else {
13601 error = got_error_msg(GOT_ERR_CONFLICTS,
13602 "changes destined for some "
13603 "files were not yet merged and should be "
13604 "merged manually if required before the "
13605 "merge operation is continued");
13607 goto done;
13608 } else {
13609 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13610 fileindex, author, NULL, 1, branch_tip, branch_name,
13611 allow_conflict, repo, continue_merge ? print_status : NULL,
13612 NULL);
13613 if (error)
13614 goto done;
13615 error = got_worktree_merge_complete(worktree, fileindex, repo);
13616 if (error)
13617 goto done;
13618 error = got_object_id_str(&id_str, merge_commit_id);
13619 if (error)
13620 goto done;
13621 printf("Merged %s into %s: %s\n", branch_name,
13622 got_worktree_get_head_ref_name(worktree),
13623 id_str);
13626 done:
13627 free(gitconfig_path);
13628 free(id_str);
13629 free(merge_commit_id);
13630 free(author);
13631 free(branch_tip);
13632 free(branch_name);
13633 free(yca_id);
13634 if (branch)
13635 got_ref_close(branch);
13636 if (wt_branch)
13637 got_ref_close(wt_branch);
13638 if (worktree)
13639 got_worktree_close(worktree);
13640 if (repo) {
13641 const struct got_error *close_err = got_repo_close(repo);
13642 if (error == NULL)
13643 error = close_err;
13645 if (pack_fds) {
13646 const struct got_error *pack_err =
13647 got_repo_pack_fds_close(pack_fds);
13648 if (error == NULL)
13649 error = pack_err;
13651 return error;
13654 __dead static void
13655 usage_stage(void)
13657 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13658 "[path ...]\n", getprogname());
13659 exit(1);
13662 static const struct got_error *
13663 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13664 const char *path, struct got_object_id *blob_id,
13665 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13666 int dirfd, const char *de_name)
13668 const struct got_error *err = NULL;
13669 char *id_str = NULL;
13671 if (staged_status != GOT_STATUS_ADD &&
13672 staged_status != GOT_STATUS_MODIFY &&
13673 staged_status != GOT_STATUS_DELETE)
13674 return NULL;
13676 if (staged_status == GOT_STATUS_ADD ||
13677 staged_status == GOT_STATUS_MODIFY)
13678 err = got_object_id_str(&id_str, staged_blob_id);
13679 else
13680 err = got_object_id_str(&id_str, blob_id);
13681 if (err)
13682 return err;
13684 printf("%s %c %s\n", id_str, staged_status, path);
13685 free(id_str);
13686 return NULL;
13689 static const struct got_error *
13690 cmd_stage(int argc, char *argv[])
13692 const struct got_error *error = NULL;
13693 struct got_repository *repo = NULL;
13694 struct got_worktree *worktree = NULL;
13695 char *cwd = NULL;
13696 struct got_pathlist_head paths;
13697 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13698 FILE *patch_script_file = NULL;
13699 const char *patch_script_path = NULL;
13700 struct choose_patch_arg cpa;
13701 int *pack_fds = NULL;
13703 TAILQ_INIT(&paths);
13705 #ifndef PROFILE
13706 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13707 "unveil", NULL) == -1)
13708 err(1, "pledge");
13709 #endif
13711 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13712 switch (ch) {
13713 case 'F':
13714 patch_script_path = optarg;
13715 break;
13716 case 'l':
13717 list_stage = 1;
13718 break;
13719 case 'p':
13720 pflag = 1;
13721 break;
13722 case 'S':
13723 allow_bad_symlinks = 1;
13724 break;
13725 default:
13726 usage_stage();
13727 /* NOTREACHED */
13731 argc -= optind;
13732 argv += optind;
13734 if (list_stage && (pflag || patch_script_path))
13735 errx(1, "-l option cannot be used with other options");
13736 if (patch_script_path && !pflag)
13737 errx(1, "-F option can only be used together with -p option");
13739 cwd = getcwd(NULL, 0);
13740 if (cwd == NULL) {
13741 error = got_error_from_errno("getcwd");
13742 goto done;
13745 error = got_repo_pack_fds_open(&pack_fds);
13746 if (error != NULL)
13747 goto done;
13749 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13750 if (error) {
13751 if (error->code == GOT_ERR_NOT_WORKTREE)
13752 error = wrap_not_worktree_error(error, "stage", cwd);
13753 goto done;
13756 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13757 NULL, pack_fds);
13758 if (error != NULL)
13759 goto done;
13761 if (patch_script_path) {
13762 patch_script_file = fopen(patch_script_path, "re");
13763 if (patch_script_file == NULL) {
13764 error = got_error_from_errno2("fopen",
13765 patch_script_path);
13766 goto done;
13769 error = apply_unveil(got_repo_get_path(repo), 0,
13770 got_worktree_get_root_path(worktree));
13771 if (error)
13772 goto done;
13774 error = check_merge_in_progress(worktree, repo);
13775 if (error)
13776 goto done;
13778 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13779 if (error)
13780 goto done;
13782 if (list_stage)
13783 error = got_worktree_status(worktree, &paths, repo, 0,
13784 print_stage, NULL, check_cancelled, NULL);
13785 else {
13786 cpa.patch_script_file = patch_script_file;
13787 cpa.action = "stage";
13788 error = got_worktree_stage(worktree, &paths,
13789 pflag ? NULL : print_status, NULL,
13790 pflag ? choose_patch : NULL, &cpa,
13791 allow_bad_symlinks, repo);
13793 done:
13794 if (patch_script_file && fclose(patch_script_file) == EOF &&
13795 error == NULL)
13796 error = got_error_from_errno2("fclose", patch_script_path);
13797 if (repo) {
13798 const struct got_error *close_err = got_repo_close(repo);
13799 if (error == NULL)
13800 error = close_err;
13802 if (worktree)
13803 got_worktree_close(worktree);
13804 if (pack_fds) {
13805 const struct got_error *pack_err =
13806 got_repo_pack_fds_close(pack_fds);
13807 if (error == NULL)
13808 error = pack_err;
13810 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13811 free(cwd);
13812 return error;
13815 __dead static void
13816 usage_unstage(void)
13818 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13819 "[path ...]\n", getprogname());
13820 exit(1);
13824 static const struct got_error *
13825 cmd_unstage(int argc, char *argv[])
13827 const struct got_error *error = NULL;
13828 struct got_repository *repo = NULL;
13829 struct got_worktree *worktree = NULL;
13830 char *cwd = NULL;
13831 struct got_pathlist_head paths;
13832 int ch, pflag = 0;
13833 struct got_update_progress_arg upa;
13834 FILE *patch_script_file = NULL;
13835 const char *patch_script_path = NULL;
13836 struct choose_patch_arg cpa;
13837 int *pack_fds = NULL;
13839 TAILQ_INIT(&paths);
13841 #ifndef PROFILE
13842 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13843 "unveil", NULL) == -1)
13844 err(1, "pledge");
13845 #endif
13847 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13848 switch (ch) {
13849 case 'F':
13850 patch_script_path = optarg;
13851 break;
13852 case 'p':
13853 pflag = 1;
13854 break;
13855 default:
13856 usage_unstage();
13857 /* NOTREACHED */
13861 argc -= optind;
13862 argv += optind;
13864 if (patch_script_path && !pflag)
13865 errx(1, "-F option can only be used together with -p option");
13867 cwd = getcwd(NULL, 0);
13868 if (cwd == NULL) {
13869 error = got_error_from_errno("getcwd");
13870 goto done;
13873 error = got_repo_pack_fds_open(&pack_fds);
13874 if (error != NULL)
13875 goto done;
13877 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13878 if (error) {
13879 if (error->code == GOT_ERR_NOT_WORKTREE)
13880 error = wrap_not_worktree_error(error, "unstage", cwd);
13881 goto done;
13884 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13885 NULL, pack_fds);
13886 if (error != NULL)
13887 goto done;
13889 if (patch_script_path) {
13890 patch_script_file = fopen(patch_script_path, "re");
13891 if (patch_script_file == NULL) {
13892 error = got_error_from_errno2("fopen",
13893 patch_script_path);
13894 goto done;
13898 error = apply_unveil(got_repo_get_path(repo), 0,
13899 got_worktree_get_root_path(worktree));
13900 if (error)
13901 goto done;
13903 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13904 if (error)
13905 goto done;
13907 cpa.patch_script_file = patch_script_file;
13908 cpa.action = "unstage";
13909 memset(&upa, 0, sizeof(upa));
13910 error = got_worktree_unstage(worktree, &paths, update_progress,
13911 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13912 if (!error)
13913 print_merge_progress_stats(&upa);
13914 done:
13915 if (patch_script_file && fclose(patch_script_file) == EOF &&
13916 error == NULL)
13917 error = got_error_from_errno2("fclose", patch_script_path);
13918 if (repo) {
13919 const struct got_error *close_err = got_repo_close(repo);
13920 if (error == NULL)
13921 error = close_err;
13923 if (worktree)
13924 got_worktree_close(worktree);
13925 if (pack_fds) {
13926 const struct got_error *pack_err =
13927 got_repo_pack_fds_close(pack_fds);
13928 if (error == NULL)
13929 error = pack_err;
13931 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13932 free(cwd);
13933 return error;
13936 __dead static void
13937 usage_cat(void)
13939 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13940 "arg ...\n", getprogname());
13941 exit(1);
13944 static const struct got_error *
13945 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13947 const struct got_error *err;
13948 struct got_blob_object *blob;
13949 int fd = -1;
13951 fd = got_opentempfd();
13952 if (fd == -1)
13953 return got_error_from_errno("got_opentempfd");
13955 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13956 if (err)
13957 goto done;
13959 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13960 done:
13961 if (fd != -1 && close(fd) == -1 && err == NULL)
13962 err = got_error_from_errno("close");
13963 if (blob)
13964 got_object_blob_close(blob);
13965 return err;
13968 static const struct got_error *
13969 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13971 const struct got_error *err;
13972 struct got_tree_object *tree;
13973 int nentries, i;
13975 err = got_object_open_as_tree(&tree, repo, id);
13976 if (err)
13977 return err;
13979 nentries = got_object_tree_get_nentries(tree);
13980 for (i = 0; i < nentries; i++) {
13981 struct got_tree_entry *te;
13982 char *id_str;
13983 if (sigint_received || sigpipe_received)
13984 break;
13985 te = got_object_tree_get_entry(tree, i);
13986 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13987 if (err)
13988 break;
13989 fprintf(outfile, "%s %.7o %s\n", id_str,
13990 got_tree_entry_get_mode(te),
13991 got_tree_entry_get_name(te));
13992 free(id_str);
13995 got_object_tree_close(tree);
13996 return err;
13999 static const struct got_error *
14000 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14002 const struct got_error *err;
14003 struct got_commit_object *commit;
14004 const struct got_object_id_queue *parent_ids;
14005 struct got_object_qid *pid;
14006 char *id_str = NULL;
14007 const char *logmsg = NULL;
14008 char gmtoff[6];
14010 err = got_object_open_as_commit(&commit, repo, id);
14011 if (err)
14012 return err;
14014 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14015 if (err)
14016 goto done;
14018 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14019 parent_ids = got_object_commit_get_parent_ids(commit);
14020 fprintf(outfile, "numparents %d\n",
14021 got_object_commit_get_nparents(commit));
14022 STAILQ_FOREACH(pid, parent_ids, entry) {
14023 char *pid_str;
14024 err = got_object_id_str(&pid_str, &pid->id);
14025 if (err)
14026 goto done;
14027 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14028 free(pid_str);
14030 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14031 got_object_commit_get_author_gmtoff(commit));
14032 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14033 got_object_commit_get_author(commit),
14034 (long long)got_object_commit_get_author_time(commit),
14035 gmtoff);
14037 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14038 got_object_commit_get_committer_gmtoff(commit));
14039 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14040 got_object_commit_get_committer(commit),
14041 (long long)got_object_commit_get_committer_time(commit),
14042 gmtoff);
14044 logmsg = got_object_commit_get_logmsg_raw(commit);
14045 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14046 fprintf(outfile, "%s", logmsg);
14047 done:
14048 free(id_str);
14049 got_object_commit_close(commit);
14050 return err;
14053 static const struct got_error *
14054 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14056 const struct got_error *err;
14057 struct got_tag_object *tag;
14058 char *id_str = NULL;
14059 const char *tagmsg = NULL;
14060 char gmtoff[6];
14062 err = got_object_open_as_tag(&tag, repo, id);
14063 if (err)
14064 return err;
14066 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14067 if (err)
14068 goto done;
14070 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14072 switch (got_object_tag_get_object_type(tag)) {
14073 case GOT_OBJ_TYPE_BLOB:
14074 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14075 GOT_OBJ_LABEL_BLOB);
14076 break;
14077 case GOT_OBJ_TYPE_TREE:
14078 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14079 GOT_OBJ_LABEL_TREE);
14080 break;
14081 case GOT_OBJ_TYPE_COMMIT:
14082 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14083 GOT_OBJ_LABEL_COMMIT);
14084 break;
14085 case GOT_OBJ_TYPE_TAG:
14086 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14087 GOT_OBJ_LABEL_TAG);
14088 break;
14089 default:
14090 break;
14093 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14094 got_object_tag_get_name(tag));
14096 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14097 got_object_tag_get_tagger_gmtoff(tag));
14098 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14099 got_object_tag_get_tagger(tag),
14100 (long long)got_object_tag_get_tagger_time(tag),
14101 gmtoff);
14103 tagmsg = got_object_tag_get_message(tag);
14104 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14105 fprintf(outfile, "%s", tagmsg);
14106 done:
14107 free(id_str);
14108 got_object_tag_close(tag);
14109 return err;
14112 static const struct got_error *
14113 cmd_cat(int argc, char *argv[])
14115 const struct got_error *error;
14116 struct got_repository *repo = NULL;
14117 struct got_worktree *worktree = NULL;
14118 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14119 char *keyword_idstr = NULL;
14120 const char *commit_id_str = NULL;
14121 struct got_object_id *id = NULL, *commit_id = NULL;
14122 struct got_commit_object *commit = NULL;
14123 int ch, obj_type, i, force_path = 0;
14124 struct got_reflist_head refs;
14125 int *pack_fds = NULL;
14127 TAILQ_INIT(&refs);
14129 #ifndef PROFILE
14130 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14131 NULL) == -1)
14132 err(1, "pledge");
14133 #endif
14135 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14136 switch (ch) {
14137 case 'c':
14138 commit_id_str = optarg;
14139 break;
14140 case 'P':
14141 force_path = 1;
14142 break;
14143 case 'r':
14144 repo_path = realpath(optarg, NULL);
14145 if (repo_path == NULL)
14146 return got_error_from_errno2("realpath",
14147 optarg);
14148 got_path_strip_trailing_slashes(repo_path);
14149 break;
14150 default:
14151 usage_cat();
14152 /* NOTREACHED */
14156 argc -= optind;
14157 argv += optind;
14159 cwd = getcwd(NULL, 0);
14160 if (cwd == NULL) {
14161 error = got_error_from_errno("getcwd");
14162 goto done;
14165 error = got_repo_pack_fds_open(&pack_fds);
14166 if (error != NULL)
14167 goto done;
14169 if (repo_path == NULL) {
14170 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14171 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14172 goto done;
14173 if (worktree) {
14174 repo_path = strdup(
14175 got_worktree_get_repo_path(worktree));
14176 if (repo_path == NULL) {
14177 error = got_error_from_errno("strdup");
14178 goto done;
14181 if (commit_id_str == NULL) {
14182 /* Release work tree lock. */
14183 got_worktree_close(worktree);
14184 worktree = NULL;
14189 if (repo_path == NULL) {
14190 repo_path = strdup(cwd);
14191 if (repo_path == NULL)
14192 return got_error_from_errno("strdup");
14195 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14196 free(repo_path);
14197 if (error != NULL)
14198 goto done;
14200 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14201 if (error)
14202 goto done;
14204 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14205 if (error)
14206 goto done;
14208 if (commit_id_str != NULL) {
14209 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14210 repo, worktree);
14211 if (error != NULL)
14212 goto done;
14213 if (keyword_idstr != NULL)
14214 commit_id_str = keyword_idstr;
14215 if (worktree != NULL) {
14216 got_worktree_close(worktree);
14217 worktree = NULL;
14219 } else
14220 commit_id_str = GOT_REF_HEAD;
14221 error = got_repo_match_object_id(&commit_id, NULL,
14222 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14223 if (error)
14224 goto done;
14226 error = got_object_open_as_commit(&commit, repo, commit_id);
14227 if (error)
14228 goto done;
14230 for (i = 0; i < argc; i++) {
14231 if (force_path) {
14232 error = got_object_id_by_path(&id, repo, commit,
14233 argv[i]);
14234 if (error)
14235 break;
14236 } else {
14237 error = got_repo_match_object_id(&id, &label, argv[i],
14238 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14239 repo);
14240 if (error) {
14241 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14242 error->code != GOT_ERR_NOT_REF)
14243 break;
14244 error = got_object_id_by_path(&id, repo,
14245 commit, argv[i]);
14246 if (error)
14247 break;
14251 error = got_object_get_type(&obj_type, repo, id);
14252 if (error)
14253 break;
14255 switch (obj_type) {
14256 case GOT_OBJ_TYPE_BLOB:
14257 error = cat_blob(id, repo, stdout);
14258 break;
14259 case GOT_OBJ_TYPE_TREE:
14260 error = cat_tree(id, repo, stdout);
14261 break;
14262 case GOT_OBJ_TYPE_COMMIT:
14263 error = cat_commit(id, repo, stdout);
14264 break;
14265 case GOT_OBJ_TYPE_TAG:
14266 error = cat_tag(id, repo, stdout);
14267 break;
14268 default:
14269 error = got_error(GOT_ERR_OBJ_TYPE);
14270 break;
14272 if (error)
14273 break;
14274 free(label);
14275 label = NULL;
14276 free(id);
14277 id = NULL;
14279 done:
14280 free(label);
14281 free(id);
14282 free(commit_id);
14283 free(keyword_idstr);
14284 if (commit)
14285 got_object_commit_close(commit);
14286 if (worktree)
14287 got_worktree_close(worktree);
14288 if (repo) {
14289 const struct got_error *close_err = got_repo_close(repo);
14290 if (error == NULL)
14291 error = close_err;
14293 if (pack_fds) {
14294 const struct got_error *pack_err =
14295 got_repo_pack_fds_close(pack_fds);
14296 if (error == NULL)
14297 error = pack_err;
14300 got_ref_list_free(&refs);
14301 return error;
14304 __dead static void
14305 usage_info(void)
14307 fprintf(stderr, "usage: %s info [path ...]\n",
14308 getprogname());
14309 exit(1);
14312 static const struct got_error *
14313 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14314 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14315 struct got_object_id *commit_id)
14317 const struct got_error *err = NULL;
14318 char *id_str = NULL;
14319 char datebuf[128];
14320 struct tm mytm, *tm;
14321 struct got_pathlist_head *paths = arg;
14322 struct got_pathlist_entry *pe;
14325 * Clear error indication from any of the path arguments which
14326 * would cause this file index entry to be displayed.
14328 TAILQ_FOREACH(pe, paths, entry) {
14329 if (got_path_cmp(path, pe->path, strlen(path),
14330 pe->path_len) == 0 ||
14331 got_path_is_child(path, pe->path, pe->path_len))
14332 pe->data = NULL; /* no error */
14335 printf(GOT_COMMIT_SEP_STR);
14336 if (S_ISLNK(mode))
14337 printf("symlink: %s\n", path);
14338 else if (S_ISREG(mode)) {
14339 printf("file: %s\n", path);
14340 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14341 } else if (S_ISDIR(mode))
14342 printf("directory: %s\n", path);
14343 else
14344 printf("something: %s\n", path);
14346 tm = localtime_r(&mtime, &mytm);
14347 if (tm == NULL)
14348 return NULL;
14349 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14350 return got_error(GOT_ERR_NO_SPACE);
14351 printf("timestamp: %s\n", datebuf);
14353 if (blob_id) {
14354 err = got_object_id_str(&id_str, blob_id);
14355 if (err)
14356 return err;
14357 printf("based on blob: %s\n", id_str);
14358 free(id_str);
14361 if (staged_blob_id) {
14362 err = got_object_id_str(&id_str, staged_blob_id);
14363 if (err)
14364 return err;
14365 printf("based on staged blob: %s\n", id_str);
14366 free(id_str);
14369 if (commit_id) {
14370 err = got_object_id_str(&id_str, commit_id);
14371 if (err)
14372 return err;
14373 printf("based on commit: %s\n", id_str);
14374 free(id_str);
14377 return NULL;
14380 static const struct got_error *
14381 cmd_info(int argc, char *argv[])
14383 const struct got_error *error = NULL;
14384 struct got_worktree *worktree = NULL;
14385 char *cwd = NULL, *id_str = NULL;
14386 struct got_pathlist_head paths;
14387 char *uuidstr = NULL;
14388 int ch, show_files = 0;
14390 TAILQ_INIT(&paths);
14392 #ifndef PROFILE
14393 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14394 NULL) == -1)
14395 err(1, "pledge");
14396 #endif
14398 while ((ch = getopt(argc, argv, "")) != -1) {
14399 switch (ch) {
14400 default:
14401 usage_info();
14402 /* NOTREACHED */
14406 argc -= optind;
14407 argv += optind;
14409 cwd = getcwd(NULL, 0);
14410 if (cwd == NULL) {
14411 error = got_error_from_errno("getcwd");
14412 goto done;
14415 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14416 if (error) {
14417 if (error->code == GOT_ERR_NOT_WORKTREE)
14418 error = wrap_not_worktree_error(error, "info", cwd);
14419 goto done;
14422 #ifndef PROFILE
14423 /* Remove "wpath cpath proc exec sendfd" promises. */
14424 if (pledge("stdio rpath flock unveil", NULL) == -1)
14425 err(1, "pledge");
14426 #endif
14427 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14428 if (error)
14429 goto done;
14431 if (argc >= 1) {
14432 error = get_worktree_paths_from_argv(&paths, argc, argv,
14433 worktree);
14434 if (error)
14435 goto done;
14436 show_files = 1;
14439 error = got_object_id_str(&id_str,
14440 got_worktree_get_base_commit_id(worktree));
14441 if (error)
14442 goto done;
14444 error = got_worktree_get_uuid(&uuidstr, worktree);
14445 if (error)
14446 goto done;
14448 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14449 printf("work tree base commit: %s\n", id_str);
14450 printf("work tree path prefix: %s\n",
14451 got_worktree_get_path_prefix(worktree));
14452 printf("work tree branch reference: %s\n",
14453 got_worktree_get_head_ref_name(worktree));
14454 printf("work tree UUID: %s\n", uuidstr);
14455 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14457 if (show_files) {
14458 struct got_pathlist_entry *pe;
14459 TAILQ_FOREACH(pe, &paths, entry) {
14460 if (pe->path_len == 0)
14461 continue;
14463 * Assume this path will fail. This will be corrected
14464 * in print_path_info() in case the path does suceeed.
14466 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14468 error = got_worktree_path_info(worktree, &paths,
14469 print_path_info, &paths, check_cancelled, NULL);
14470 if (error)
14471 goto done;
14472 TAILQ_FOREACH(pe, &paths, entry) {
14473 if (pe->data != NULL) {
14474 const struct got_error *perr;
14476 perr = pe->data;
14477 error = got_error_fmt(perr->code, "%s",
14478 pe->path);
14479 break;
14483 done:
14484 if (worktree)
14485 got_worktree_close(worktree);
14486 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14487 free(cwd);
14488 free(id_str);
14489 free(uuidstr);
14490 return error;