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, *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 struct got_pathlist_entry *pe;
2298 struct got_reflist_head remote_refs;
2299 struct got_reflist_entry *re;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL, have_bflag = 0;
2307 const char *remote_head = NULL, *worktree_branch = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&remote_refs);
2312 TAILQ_INIT(&wanted_branches);
2313 TAILQ_INIT(&wanted_refs);
2315 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2316 switch (ch) {
2317 case 'a':
2318 fetch_all_branches = 1;
2319 break;
2320 case 'b':
2321 error = got_pathlist_append(&wanted_branches,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 have_bflag = 1;
2326 break;
2327 case 'd':
2328 delete_refs = 1;
2329 break;
2330 case 'l':
2331 list_refs_only = 1;
2332 break;
2333 case 'q':
2334 verbosity = -1;
2335 break;
2336 case 'R':
2337 error = got_pathlist_append(&wanted_refs,
2338 optarg, NULL);
2339 if (error)
2340 return error;
2341 break;
2342 case 'r':
2343 repo_path = realpath(optarg, NULL);
2344 if (repo_path == NULL)
2345 return got_error_from_errno2("realpath",
2346 optarg);
2347 got_path_strip_trailing_slashes(repo_path);
2348 break;
2349 case 't':
2350 replace_tags = 1;
2351 break;
2352 case 'v':
2353 if (verbosity < 0)
2354 verbosity = 0;
2355 else if (verbosity < 3)
2356 verbosity++;
2357 break;
2358 case 'X':
2359 delete_remote = 1;
2360 break;
2361 default:
2362 usage_fetch();
2363 break;
2366 argc -= optind;
2367 argv += optind;
2369 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('a', 'b');
2371 if (list_refs_only) {
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('l', 'b');
2374 if (fetch_all_branches)
2375 option_conflict('l', 'a');
2376 if (delete_refs)
2377 option_conflict('l', 'd');
2378 if (delete_remote)
2379 option_conflict('l', 'X');
2381 if (delete_remote) {
2382 if (fetch_all_branches)
2383 option_conflict('X', 'a');
2384 if (!TAILQ_EMPTY(&wanted_branches))
2385 option_conflict('X', 'b');
2386 if (delete_refs)
2387 option_conflict('X', 'd');
2388 if (replace_tags)
2389 option_conflict('X', 't');
2390 if (!TAILQ_EMPTY(&wanted_refs))
2391 option_conflict('X', 'R');
2394 if (argc == 0) {
2395 if (delete_remote)
2396 errx(1, "-X option requires a remote name");
2397 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2398 } else if (argc == 1)
2399 remote_name = argv[0];
2400 else
2401 usage_fetch();
2403 cwd = getcwd(NULL, 0);
2404 if (cwd == NULL) {
2405 error = got_error_from_errno("getcwd");
2406 goto done;
2409 error = got_repo_pack_fds_open(&pack_fds);
2410 if (error != NULL)
2411 goto done;
2413 if (repo_path == NULL) {
2414 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2416 goto done;
2417 else
2418 error = NULL;
2419 if (worktree) {
2420 repo_path =
2421 strdup(got_worktree_get_repo_path(worktree));
2422 if (repo_path == NULL)
2423 error = got_error_from_errno("strdup");
2424 if (error)
2425 goto done;
2426 } else {
2427 repo_path = strdup(cwd);
2428 if (repo_path == NULL) {
2429 error = got_error_from_errno("strdup");
2430 goto done;
2435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2436 if (error)
2437 goto done;
2439 if (delete_remote) {
2440 error = delete_refs_for_remote(repo, remote_name);
2441 goto done; /* nothing else to do */
2444 if (worktree) {
2445 worktree_conf = got_worktree_get_gotconfig(worktree);
2446 if (worktree_conf) {
2447 got_gotconfig_get_remotes(&nremotes, &remotes,
2448 worktree_conf);
2449 for (i = 0; i < nremotes; i++) {
2450 if (strcmp(remotes[i].name, remote_name) == 0) {
2451 remote = &remotes[i];
2452 break;
2457 if (remote == NULL) {
2458 repo_conf = got_repo_get_gotconfig(repo);
2459 if (repo_conf) {
2460 got_gotconfig_get_remotes(&nremotes, &remotes,
2461 repo_conf);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2470 if (remote == NULL) {
2471 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 remote = &remotes[i];
2475 break;
2479 if (remote == NULL) {
2480 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_branches)) {
2485 if (!fetch_all_branches)
2486 fetch_all_branches = remote->fetch_all_branches;
2487 for (i = 0; i < remote->nfetch_branches; i++) {
2488 error = got_pathlist_append(&wanted_branches,
2489 remote->fetch_branches[i], NULL);
2490 if (error)
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_refs)) {
2495 for (i = 0; i < remote->nfetch_refs; i++) {
2496 error = got_pathlist_append(&wanted_refs,
2497 remote->fetch_refs[i], NULL);
2498 if (error)
2499 goto done;
2503 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2504 &repo_name, remote->fetch_url);
2505 if (error)
2506 goto done;
2508 if (strcmp(proto, "git") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd dns inet unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "git+ssh") == 0 ||
2515 strcmp(proto, "ssh") == 0) {
2516 #ifndef PROFILE
2517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2518 "sendfd unveil", NULL) == -1)
2519 err(1, "pledge");
2520 #endif
2521 } else if (strcmp(proto, "http") == 0 ||
2522 strcmp(proto, "git+http") == 0) {
2523 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2524 goto done;
2525 } else {
2526 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2527 goto done;
2530 error = got_dial_apply_unveil(proto);
2531 if (error)
2532 goto done;
2534 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2535 if (error)
2536 goto done;
2538 if (verbosity >= 0) {
2539 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2540 remote->name, proto, host,
2541 port ? ":" : "", port ? port : "",
2542 *server_path == '/' ? "" : "/", server_path);
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 if (!have_bflag) {
2552 * If set, get this remote's HEAD ref target so
2553 * if it has changed on the server we can fetch it.
2555 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2556 got_ref_cmp_by_name, repo);
2557 if (error)
2558 goto done;
2560 TAILQ_FOREACH(re, &remote_refs, entry) {
2561 const char *remote_refname, *remote_target;
2562 size_t remote_name_len;
2564 if (!got_ref_is_symbolic(re->ref))
2565 continue;
2567 remote_name_len = strlen(remote->name);
2568 remote_refname = got_ref_get_name(re->ref);
2570 /* we only want refs/remotes/$remote->name/HEAD */
2571 if (strncmp(remote_refname + 13, remote->name,
2572 remote_name_len) != 0)
2573 continue;
2575 if (strcmp(remote_refname + remote_name_len + 14,
2576 GOT_REF_HEAD) != 0)
2577 continue;
2580 * Take the name itself because we already
2581 * only match with refs/heads/ in fetch_pack().
2583 remote_target = got_ref_get_symref_target(re->ref);
2584 remote_head = remote_target + remote_name_len + 14;
2585 break;
2588 if (worktree) {
2589 const char *refname;
2591 refname = got_worktree_get_head_ref_name(worktree);
2592 if (strncmp(refname, "refs/heads/", 11) == 0)
2593 worktree_branch = refname;
2597 fpa.last_scaled_size[0] = '\0';
2598 fpa.last_p_indexed = -1;
2599 fpa.last_p_resolved = -1;
2600 fpa.verbosity = verbosity;
2601 fpa.repo = repo;
2602 fpa.create_configs = 0;
2603 fpa.configs_created = 0;
2604 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2606 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2607 remote->mirror_references, fetch_all_branches, &wanted_branches,
2608 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2609 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2610 if (error)
2611 goto done;
2613 if (list_refs_only) {
2614 error = list_remote_refs(&symrefs, &refs);
2615 goto done;
2618 if (pack_hash == NULL) {
2619 if (verbosity >= 0)
2620 printf("Already up-to-date\n");
2621 } else if (verbosity >= 0) {
2622 error = got_object_id_str(&id_str, pack_hash);
2623 if (error)
2624 goto done;
2625 printf("\nFetched %s.pack\n", id_str);
2626 free(id_str);
2627 id_str = NULL;
2630 /* Update references provided with the pack file. */
2631 TAILQ_FOREACH(pe, &refs, entry) {
2632 const char *refname = pe->path;
2633 struct got_object_id *id = pe->data;
2634 struct got_reference *ref;
2635 char *remote_refname;
2637 if (is_wanted_ref(&wanted_refs, refname) &&
2638 !remote->mirror_references) {
2639 error = update_wanted_ref(refname, id,
2640 remote->name, verbosity, repo);
2641 if (error)
2642 goto done;
2643 continue;
2646 if (remote->mirror_references ||
2647 strncmp("refs/tags/", refname, 10) == 0) {
2648 error = got_ref_open(&ref, repo, refname, 1);
2649 if (error) {
2650 if (error->code != GOT_ERR_NOT_REF)
2651 goto done;
2652 error = create_ref(refname, id, verbosity,
2653 repo);
2654 if (error)
2655 goto done;
2656 } else {
2657 error = update_ref(ref, id, replace_tags,
2658 verbosity, repo);
2659 unlock_err = got_ref_unlock(ref);
2660 if (unlock_err && error == NULL)
2661 error = unlock_err;
2662 got_ref_close(ref);
2663 if (error)
2664 goto done;
2666 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2667 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2668 remote_name, refname + 11) == -1) {
2669 error = got_error_from_errno("asprintf");
2670 goto done;
2673 error = got_ref_open(&ref, repo, remote_refname, 1);
2674 if (error) {
2675 if (error->code != GOT_ERR_NOT_REF)
2676 goto done;
2677 error = create_ref(remote_refname, id,
2678 verbosity, repo);
2679 if (error)
2680 goto done;
2681 } else {
2682 error = update_ref(ref, id, replace_tags,
2683 verbosity, repo);
2684 unlock_err = got_ref_unlock(ref);
2685 if (unlock_err && error == NULL)
2686 error = unlock_err;
2687 got_ref_close(ref);
2688 if (error)
2689 goto done;
2692 /* Also create a local branch if none exists yet. */
2693 error = got_ref_open(&ref, repo, refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(refname, id, verbosity,
2698 repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2709 if (delete_refs) {
2710 error = delete_missing_refs(&refs, &symrefs, remote,
2711 verbosity, repo);
2712 if (error)
2713 goto done;
2716 if (!remote->mirror_references) {
2717 /* Update remote HEAD reference if the server provided one. */
2718 TAILQ_FOREACH(pe, &symrefs, entry) {
2719 struct got_reference *target_ref;
2720 const char *refname = pe->path;
2721 const char *target = pe->data;
2722 char *remote_refname = NULL, *remote_target = NULL;
2724 if (strcmp(refname, GOT_REF_HEAD) != 0)
2725 continue;
2727 if (strncmp("refs/heads/", target, 11) != 0)
2728 continue;
2730 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2731 remote->name, refname) == -1) {
2732 error = got_error_from_errno("asprintf");
2733 goto done;
2735 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2736 remote->name, target + 11) == -1) {
2737 error = got_error_from_errno("asprintf");
2738 free(remote_refname);
2739 goto done;
2742 error = got_ref_open(&target_ref, repo, remote_target,
2743 0);
2744 if (error) {
2745 free(remote_refname);
2746 free(remote_target);
2747 if (error->code == GOT_ERR_NOT_REF) {
2748 error = NULL;
2749 continue;
2751 goto done;
2753 error = update_symref(remote_refname, target_ref,
2754 verbosity, repo);
2755 free(remote_refname);
2756 free(remote_target);
2757 got_ref_close(target_ref);
2758 if (error)
2759 goto done;
2762 done:
2763 if (fetchpid > 0) {
2764 if (kill(fetchpid, SIGTERM) == -1)
2765 error = got_error_from_errno("kill");
2766 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2767 error = got_error_from_errno("waitpid");
2769 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2770 error = got_error_from_errno("close");
2771 if (repo) {
2772 const struct got_error *close_err = got_repo_close(repo);
2773 if (error == NULL)
2774 error = close_err;
2776 if (worktree)
2777 got_worktree_close(worktree);
2778 if (pack_fds) {
2779 const struct got_error *pack_err =
2780 got_repo_pack_fds_close(pack_fds);
2781 if (error == NULL)
2782 error = pack_err;
2784 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2787 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2788 got_ref_list_free(&remote_refs);
2789 free(id_str);
2790 free(cwd);
2791 free(repo_path);
2792 free(pack_hash);
2793 free(proto);
2794 free(host);
2795 free(port);
2796 free(server_path);
2797 free(repo_name);
2798 return error;
2802 __dead static void
2803 usage_checkout(void)
2805 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2806 "[-p path-prefix] repository-path [work-tree-path]\n",
2807 getprogname());
2808 exit(1);
2811 static void
2812 show_worktree_base_ref_warning(void)
2814 fprintf(stderr, "%s: warning: could not create a reference "
2815 "to the work tree's base commit; the commit could be "
2816 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2817 "repository writable and running 'got update' will prevent this\n",
2818 getprogname());
2821 struct got_checkout_progress_arg {
2822 const char *worktree_path;
2823 int had_base_commit_ref_error;
2824 int verbosity;
2827 static const struct got_error *
2828 checkout_progress(void *arg, unsigned char status, const char *path)
2830 struct got_checkout_progress_arg *a = arg;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_BASE_REF_ERR) {
2837 a->had_base_commit_ref_error = 1;
2838 return NULL;
2841 while (path[0] == '/')
2842 path++;
2844 if (a->verbosity >= 0)
2845 printf("%c %s/%s\n", status, a->worktree_path, path);
2847 return NULL;
2850 static const struct got_error *
2851 check_cancelled(void *arg)
2853 if (sigint_received || sigpipe_received)
2854 return got_error(GOT_ERR_CANCELLED);
2855 return NULL;
2858 static const struct got_error *
2859 check_linear_ancestry(struct got_object_id *commit_id,
2860 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2861 struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct got_object_id *yca_id;
2866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2867 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2868 if (err)
2869 return err;
2871 if (yca_id == NULL)
2872 return got_error(GOT_ERR_ANCESTRY);
2875 * Require a straight line of history between the target commit
2876 * and the work tree's base commit.
2878 * Non-linear situations such as this require a rebase:
2880 * (commit) D F (base_commit)
2881 * \ /
2882 * C E
2883 * \ /
2884 * B (yca)
2885 * |
2886 * A
2888 * 'got update' only handles linear cases:
2889 * Update forwards in time: A (base/yca) - B - C - D (commit)
2890 * Update backwards in time: D (base) - C - B - A (commit/yca)
2892 if (allow_forwards_in_time_only) {
2893 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2894 return got_error(GOT_ERR_ANCESTRY);
2895 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2896 got_object_id_cmp(base_commit_id, yca_id) != 0)
2897 return got_error(GOT_ERR_ANCESTRY);
2899 free(yca_id);
2900 return NULL;
2903 static const struct got_error *
2904 check_same_branch(struct got_object_id *commit_id,
2905 struct got_reference *head_ref, struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2911 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2912 if (err)
2913 goto done;
2915 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2916 goto done;
2918 err = got_commit_graph_open(&graph, "/", 1);
2919 if (err)
2920 goto done;
2922 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2923 check_cancelled, NULL);
2924 if (err)
2925 goto done;
2927 for (;;) {
2928 struct got_object_id id;
2930 err = got_commit_graph_iter_next(&id, graph, repo,
2931 check_cancelled, NULL);
2932 if (err) {
2933 if (err->code == GOT_ERR_ITER_COMPLETED)
2934 err = got_error(GOT_ERR_ANCESTRY);
2935 break;
2938 if (got_object_id_cmp(&id, commit_id) == 0)
2939 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL, *keyword_idstr = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 #ifndef PROFILE
2994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2995 "unveil", NULL) == -1)
2996 err(1, "pledge");
2997 #endif
2999 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3000 switch (ch) {
3001 case 'b':
3002 branch_name = optarg;
3003 break;
3004 case 'c':
3005 commit_id_str = strdup(optarg);
3006 if (commit_id_str == NULL)
3007 return got_error_from_errno("strdup");
3008 break;
3009 case 'E':
3010 allow_nonempty = 1;
3011 break;
3012 case 'p':
3013 path_prefix = optarg;
3014 break;
3015 case 'q':
3016 verbosity = -1;
3017 break;
3018 default:
3019 usage_checkout();
3020 /* NOTREACHED */
3024 argc -= optind;
3025 argv += optind;
3027 if (argc == 1) {
3028 char *base, *dotgit;
3029 const char *path;
3030 repo_path = realpath(argv[0], NULL);
3031 if (repo_path == NULL)
3032 return got_error_from_errno2("realpath", argv[0]);
3033 cwd = getcwd(NULL, 0);
3034 if (cwd == NULL) {
3035 error = got_error_from_errno("getcwd");
3036 goto done;
3038 if (path_prefix[0])
3039 path = path_prefix;
3040 else
3041 path = repo_path;
3042 error = got_path_basename(&base, path);
3043 if (error)
3044 goto done;
3045 dotgit = strstr(base, ".git");
3046 if (dotgit)
3047 *dotgit = '\0';
3048 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3049 error = got_error_from_errno("asprintf");
3050 free(base);
3051 goto done;
3053 free(base);
3054 } else if (argc == 2) {
3055 repo_path = realpath(argv[0], NULL);
3056 if (repo_path == NULL) {
3057 error = got_error_from_errno2("realpath", argv[0]);
3058 goto done;
3060 worktree_path = realpath(argv[1], NULL);
3061 if (worktree_path == NULL) {
3062 if (errno != ENOENT) {
3063 error = got_error_from_errno2("realpath",
3064 argv[1]);
3065 goto done;
3067 worktree_path = strdup(argv[1]);
3068 if (worktree_path == NULL) {
3069 error = got_error_from_errno("strdup");
3070 goto done;
3073 } else
3074 usage_checkout();
3076 got_path_strip_trailing_slashes(repo_path);
3077 got_path_strip_trailing_slashes(worktree_path);
3079 error = got_repo_pack_fds_open(&pack_fds);
3080 if (error != NULL)
3081 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 /* Pre-create work tree path for unveil(2) */
3088 error = got_path_mkdir(worktree_path);
3089 if (error) {
3090 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3091 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3092 goto done;
3093 if (!allow_nonempty &&
3094 !got_path_dir_is_empty(worktree_path)) {
3095 error = got_error_path(worktree_path,
3096 GOT_ERR_DIR_NOT_EMPTY);
3097 goto done;
3101 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3102 if (error)
3103 goto done;
3105 error = got_ref_open(&head_ref, repo, branch_name, 0);
3106 if (error != NULL)
3107 goto done;
3109 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3110 GOT_WORKTREE_GOT_DIR, repo);
3111 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3112 goto done;
3114 error = got_worktree_open(&worktree, worktree_path,
3115 GOT_WORKTREE_GOT_DIR);
3116 if (error != NULL)
3117 goto done;
3119 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3120 path_prefix);
3121 if (error != NULL)
3122 goto done;
3123 if (!same_path_prefix) {
3124 error = got_error(GOT_ERR_PATH_PREFIX);
3125 goto done;
3128 if (commit_id_str) {
3129 struct got_reflist_head refs;
3130 TAILQ_INIT(&refs);
3131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3132 NULL);
3133 if (error)
3134 goto done;
3136 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3137 repo, worktree);
3138 if (error != NULL)
3139 goto done;
3140 if (keyword_idstr != NULL) {
3141 free(commit_id_str);
3142 commit_id_str = keyword_idstr;
3145 error = got_repo_match_object_id(&commit_id, NULL,
3146 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3147 got_ref_list_free(&refs);
3148 if (error)
3149 goto done;
3150 error = check_linear_ancestry(commit_id,
3151 got_worktree_get_base_commit_id(worktree), 0, repo);
3152 if (error != NULL) {
3153 if (error->code == GOT_ERR_ANCESTRY) {
3154 error = checkout_ancestry_error(
3155 head_ref, commit_id_str);
3157 goto done;
3159 error = check_same_branch(commit_id, head_ref, repo);
3160 if (error) {
3161 if (error->code == GOT_ERR_ANCESTRY) {
3162 error = checkout_ancestry_error(
3163 head_ref, commit_id_str);
3165 goto done;
3167 error = got_worktree_set_base_commit_id(worktree, repo,
3168 commit_id);
3169 if (error)
3170 goto done;
3171 /* Expand potentially abbreviated commit ID string. */
3172 free(commit_id_str);
3173 error = got_object_id_str(&commit_id_str, commit_id);
3174 if (error)
3175 goto done;
3176 } else {
3177 commit_id = got_object_id_dup(
3178 got_worktree_get_base_commit_id(worktree));
3179 if (commit_id == NULL) {
3180 error = got_error_from_errno("got_object_id_dup");
3181 goto done;
3183 error = got_object_id_str(&commit_id_str, commit_id);
3184 if (error)
3185 goto done;
3188 error = got_pathlist_append(&paths, "", NULL);
3189 if (error)
3190 goto done;
3191 cpa.worktree_path = worktree_path;
3192 cpa.had_base_commit_ref_error = 0;
3193 cpa.verbosity = verbosity;
3194 error = got_worktree_checkout_files(worktree, &paths, repo,
3195 checkout_progress, &cpa, check_cancelled, NULL);
3196 if (error != NULL)
3197 goto done;
3199 if (got_ref_is_symbolic(head_ref)) {
3200 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3201 if (error)
3202 goto done;
3203 refname = got_ref_get_name(ref);
3204 } else
3205 refname = got_ref_get_name(head_ref);
3206 printf("Checked out %s: %s\n", refname, commit_id_str);
3207 printf("Now shut up and hack\n");
3208 if (cpa.had_base_commit_ref_error)
3209 show_worktree_base_ref_warning();
3210 done:
3211 if (pack_fds) {
3212 const struct got_error *pack_err =
3213 got_repo_pack_fds_close(pack_fds);
3214 if (error == NULL)
3215 error = pack_err;
3217 if (head_ref)
3218 got_ref_close(head_ref);
3219 if (ref)
3220 got_ref_close(ref);
3221 if (repo) {
3222 const struct got_error *close_err = got_repo_close(repo);
3223 if (error == NULL)
3224 error = close_err;
3226 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3227 free(commit_id_str);
3228 free(commit_id);
3229 free(repo_path);
3230 free(worktree_path);
3231 free(cwd);
3232 return error;
3235 struct got_update_progress_arg {
3236 int did_something;
3237 int conflicts;
3238 int obstructed;
3239 int not_updated;
3240 int missing;
3241 int not_deleted;
3242 int unversioned;
3243 int verbosity;
3246 static void
3247 print_update_progress_stats(struct got_update_progress_arg *upa)
3249 if (!upa->did_something)
3250 return;
3252 if (upa->conflicts > 0)
3253 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3254 if (upa->obstructed > 0)
3255 printf("File paths obstructed by a non-regular file: %d\n",
3256 upa->obstructed);
3257 if (upa->not_updated > 0)
3258 printf("Files not updated because of existing merge "
3259 "conflicts: %d\n", upa->not_updated);
3263 * The meaning of some status codes differs between merge-style operations and
3264 * update operations. For example, the ! status code means "file was missing"
3265 * if changes were merged into the work tree, and "missing file was restored"
3266 * if the work tree was updated. This function should be used by any operation
3267 * which merges changes into the work tree without updating the work tree.
3269 static void
3270 print_merge_progress_stats(struct got_update_progress_arg *upa)
3272 if (!upa->did_something)
3273 return;
3275 if (upa->conflicts > 0)
3276 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3277 if (upa->obstructed > 0)
3278 printf("File paths obstructed by a non-regular file: %d\n",
3279 upa->obstructed);
3280 if (upa->missing > 0)
3281 printf("Files which had incoming changes but could not be "
3282 "found in the work tree: %d\n", upa->missing);
3283 if (upa->not_deleted > 0)
3284 printf("Files not deleted due to differences in deleted "
3285 "content: %d\n", upa->not_deleted);
3286 if (upa->unversioned > 0)
3287 printf("Files not merged because an unversioned file was "
3288 "found in the work tree: %d\n", upa->unversioned);
3291 __dead static void
3292 usage_update(void)
3294 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3295 "[path ...]\n", getprogname());
3296 exit(1);
3299 static const struct got_error *
3300 update_progress(void *arg, unsigned char status, const char *path)
3302 struct got_update_progress_arg *upa = arg;
3304 if (status == GOT_STATUS_EXISTS ||
3305 status == GOT_STATUS_BASE_REF_ERR)
3306 return NULL;
3308 upa->did_something = 1;
3310 /* Base commit bump happens silently. */
3311 if (status == GOT_STATUS_BUMP_BASE)
3312 return NULL;
3314 if (status == GOT_STATUS_CONFLICT)
3315 upa->conflicts++;
3316 if (status == GOT_STATUS_OBSTRUCTED)
3317 upa->obstructed++;
3318 if (status == GOT_STATUS_CANNOT_UPDATE)
3319 upa->not_updated++;
3320 if (status == GOT_STATUS_MISSING)
3321 upa->missing++;
3322 if (status == GOT_STATUS_CANNOT_DELETE)
3323 upa->not_deleted++;
3324 if (status == GOT_STATUS_UNVERSIONED)
3325 upa->unversioned++;
3327 while (path[0] == '/')
3328 path++;
3329 if (upa->verbosity >= 0)
3330 printf("%c %s\n", status, path);
3332 return NULL;
3335 static const struct got_error *
3336 switch_head_ref(struct got_reference *head_ref,
3337 struct got_object_id *commit_id, struct got_worktree *worktree,
3338 struct got_repository *repo)
3340 const struct got_error *err = NULL;
3341 char *base_id_str;
3342 int ref_has_moved = 0;
3344 /* Trivial case: switching between two different references. */
3345 if (strcmp(got_ref_get_name(head_ref),
3346 got_worktree_get_head_ref_name(worktree)) != 0) {
3347 printf("Switching work tree from %s to %s\n",
3348 got_worktree_get_head_ref_name(worktree),
3349 got_ref_get_name(head_ref));
3350 return got_worktree_set_head_ref(worktree, head_ref);
3353 err = check_linear_ancestry(commit_id,
3354 got_worktree_get_base_commit_id(worktree), 0, repo);
3355 if (err) {
3356 if (err->code != GOT_ERR_ANCESTRY)
3357 return err;
3358 ref_has_moved = 1;
3360 if (!ref_has_moved)
3361 return NULL;
3363 /* Switching to a rebased branch with the same reference name. */
3364 err = got_object_id_str(&base_id_str,
3365 got_worktree_get_base_commit_id(worktree));
3366 if (err)
3367 return err;
3368 printf("Reference %s now points at a different branch\n",
3369 got_worktree_get_head_ref_name(worktree));
3370 printf("Switching work tree from %s to %s\n", base_id_str,
3371 got_worktree_get_head_ref_name(worktree));
3372 return NULL;
3375 static const struct got_error *
3376 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3378 const struct got_error *err;
3379 int in_progress;
3381 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3382 if (err)
3383 return err;
3384 if (in_progress)
3385 return got_error(GOT_ERR_REBASING);
3387 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3388 if (err)
3389 return err;
3390 if (in_progress)
3391 return got_error(GOT_ERR_HISTEDIT_BUSY);
3393 return NULL;
3396 static const struct got_error *
3397 check_merge_in_progress(struct got_worktree *worktree,
3398 struct got_repository *repo)
3400 const struct got_error *err;
3401 int in_progress;
3403 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3404 if (err)
3405 return err;
3406 if (in_progress)
3407 return got_error(GOT_ERR_MERGE_BUSY);
3409 return NULL;
3412 static const struct got_error *
3413 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3414 char *argv[], struct got_worktree *worktree)
3416 const struct got_error *err = NULL;
3417 char *path;
3418 struct got_pathlist_entry *new;
3419 int i;
3421 if (argc == 0) {
3422 path = strdup("");
3423 if (path == NULL)
3424 return got_error_from_errno("strdup");
3425 return got_pathlist_append(paths, path, NULL);
3428 for (i = 0; i < argc; i++) {
3429 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3430 if (err)
3431 break;
3432 err = got_pathlist_insert(&new, paths, path, NULL);
3433 if (err || new == NULL /* duplicate */) {
3434 free(path);
3435 if (err)
3436 break;
3440 return err;
3443 static const struct got_error *
3444 wrap_not_worktree_error(const struct got_error *orig_err,
3445 const char *cmdname, const char *path)
3447 const struct got_error *err;
3448 struct got_repository *repo;
3449 static char msg[512];
3450 int *pack_fds = NULL;
3452 err = got_repo_pack_fds_open(&pack_fds);
3453 if (err)
3454 return err;
3456 err = got_repo_open(&repo, path, NULL, pack_fds);
3457 if (err)
3458 return orig_err;
3460 snprintf(msg, sizeof(msg),
3461 "'got %s' needs a work tree in addition to a git repository\n"
3462 "Work trees can be checked out from this Git repository with "
3463 "'got checkout'.\n"
3464 "The got(1) manual page contains more information.", cmdname);
3465 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3466 if (repo) {
3467 const struct got_error *close_err = got_repo_close(repo);
3468 if (err == NULL)
3469 err = close_err;
3471 if (pack_fds) {
3472 const struct got_error *pack_err =
3473 got_repo_pack_fds_close(pack_fds);
3474 if (err == NULL)
3475 err = pack_err;
3477 return err;
3480 static const struct got_error *
3481 cmd_update(int argc, char *argv[])
3483 const struct got_error *error = NULL;
3484 struct got_repository *repo = NULL;
3485 struct got_worktree *worktree = NULL;
3486 char *worktree_path = NULL;
3487 struct got_object_id *commit_id = NULL;
3488 char *commit_id_str = NULL;
3489 const char *branch_name = NULL;
3490 struct got_reference *head_ref = NULL;
3491 struct got_pathlist_head paths;
3492 struct got_pathlist_entry *pe;
3493 int ch, verbosity = 0;
3494 struct got_update_progress_arg upa;
3495 int *pack_fds = NULL;
3497 TAILQ_INIT(&paths);
3499 #ifndef PROFILE
3500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3501 "unveil", NULL) == -1)
3502 err(1, "pledge");
3503 #endif
3505 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3506 switch (ch) {
3507 case 'b':
3508 branch_name = optarg;
3509 break;
3510 case 'c':
3511 commit_id_str = strdup(optarg);
3512 if (commit_id_str == NULL)
3513 return got_error_from_errno("strdup");
3514 break;
3515 case 'q':
3516 verbosity = -1;
3517 break;
3518 default:
3519 usage_update();
3520 /* NOTREACHED */
3524 argc -= optind;
3525 argv += optind;
3527 worktree_path = getcwd(NULL, 0);
3528 if (worktree_path == NULL) {
3529 error = got_error_from_errno("getcwd");
3530 goto done;
3533 error = got_repo_pack_fds_open(&pack_fds);
3534 if (error != NULL)
3535 goto done;
3537 error = got_worktree_open(&worktree, worktree_path,
3538 GOT_WORKTREE_GOT_DIR);
3539 if (error) {
3540 if (error->code == GOT_ERR_NOT_WORKTREE)
3541 error = wrap_not_worktree_error(error, "update",
3542 worktree_path);
3543 goto done;
3546 error = check_rebase_or_histedit_in_progress(worktree);
3547 if (error)
3548 goto done;
3550 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3551 NULL, pack_fds);
3552 if (error != NULL)
3553 goto done;
3555 error = apply_unveil(got_repo_get_path(repo), 0,
3556 got_worktree_get_root_path(worktree));
3557 if (error)
3558 goto done;
3560 error = check_merge_in_progress(worktree, repo);
3561 if (error)
3562 goto done;
3564 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3565 if (error)
3566 goto done;
3568 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3569 got_worktree_get_head_ref_name(worktree), 0);
3570 if (error != NULL)
3571 goto done;
3572 if (commit_id_str == NULL) {
3573 error = got_ref_resolve(&commit_id, repo, head_ref);
3574 if (error != NULL)
3575 goto done;
3576 error = got_object_id_str(&commit_id_str, commit_id);
3577 if (error != NULL)
3578 goto done;
3579 } else {
3580 struct got_reflist_head refs;
3581 char *keyword_idstr = NULL;
3583 TAILQ_INIT(&refs);
3585 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3586 NULL);
3587 if (error)
3588 goto done;
3590 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3591 repo, worktree);
3592 if (error != NULL)
3593 goto done;
3594 if (keyword_idstr != NULL) {
3595 free(commit_id_str);
3596 commit_id_str = keyword_idstr;
3599 error = got_repo_match_object_id(&commit_id, NULL,
3600 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3601 got_ref_list_free(&refs);
3602 free(commit_id_str);
3603 commit_id_str = NULL;
3604 if (error)
3605 goto done;
3606 error = got_object_id_str(&commit_id_str, commit_id);
3607 if (error)
3608 goto done;
3611 if (branch_name) {
3612 struct got_object_id *head_commit_id;
3613 TAILQ_FOREACH(pe, &paths, entry) {
3614 if (pe->path_len == 0)
3615 continue;
3616 error = got_error_msg(GOT_ERR_BAD_PATH,
3617 "switching between branches requires that "
3618 "the entire work tree gets updated");
3619 goto done;
3621 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3622 if (error)
3623 goto done;
3624 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3625 repo);
3626 free(head_commit_id);
3627 if (error != NULL)
3628 goto done;
3629 error = check_same_branch(commit_id, head_ref, repo);
3630 if (error)
3631 goto done;
3632 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3633 if (error)
3634 goto done;
3635 } else {
3636 error = check_linear_ancestry(commit_id,
3637 got_worktree_get_base_commit_id(worktree), 0, repo);
3638 if (error != NULL) {
3639 if (error->code == GOT_ERR_ANCESTRY)
3640 error = got_error(GOT_ERR_BRANCH_MOVED);
3641 goto done;
3643 error = check_same_branch(commit_id, head_ref, repo);
3644 if (error)
3645 goto done;
3648 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3649 commit_id) != 0) {
3650 error = got_worktree_set_base_commit_id(worktree, repo,
3651 commit_id);
3652 if (error)
3653 goto done;
3656 memset(&upa, 0, sizeof(upa));
3657 upa.verbosity = verbosity;
3658 error = got_worktree_checkout_files(worktree, &paths, repo,
3659 update_progress, &upa, check_cancelled, NULL);
3660 if (error != NULL)
3661 goto done;
3663 if (upa.did_something) {
3664 printf("Updated to %s: %s\n",
3665 got_worktree_get_head_ref_name(worktree), commit_id_str);
3666 } else
3667 printf("Already up-to-date\n");
3669 print_update_progress_stats(&upa);
3670 done:
3671 if (pack_fds) {
3672 const struct got_error *pack_err =
3673 got_repo_pack_fds_close(pack_fds);
3674 if (error == NULL)
3675 error = pack_err;
3677 if (repo) {
3678 const struct got_error *close_err = got_repo_close(repo);
3679 if (error == NULL)
3680 error = close_err;
3682 if (head_ref != NULL)
3683 got_ref_close(head_ref);
3684 free(worktree_path);
3685 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3686 free(commit_id);
3687 free(commit_id_str);
3688 return error;
3691 static const struct got_error *
3692 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3693 const char *path, int diff_context, int ignore_whitespace,
3694 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3695 struct got_repository *repo, FILE *outfile)
3697 const struct got_error *err = NULL;
3698 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3699 FILE *f1 = NULL, *f2 = NULL;
3700 int fd1 = -1, fd2 = -1;
3702 fd1 = got_opentempfd();
3703 if (fd1 == -1)
3704 return got_error_from_errno("got_opentempfd");
3705 fd2 = got_opentempfd();
3706 if (fd2 == -1) {
3707 err = got_error_from_errno("got_opentempfd");
3708 goto done;
3711 if (blob_id1) {
3712 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3713 fd1);
3714 if (err)
3715 goto done;
3718 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3719 if (err)
3720 goto done;
3722 f1 = got_opentemp();
3723 if (f1 == NULL) {
3724 err = got_error_from_errno("got_opentemp");
3725 goto done;
3727 f2 = got_opentemp();
3728 if (f2 == NULL) {
3729 err = got_error_from_errno("got_opentemp");
3730 goto done;
3733 while (path[0] == '/')
3734 path++;
3735 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3736 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3737 force_text_diff, dsa, outfile);
3738 done:
3739 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3740 err = got_error_from_errno("close");
3741 if (blob1)
3742 got_object_blob_close(blob1);
3743 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3744 err = got_error_from_errno("close");
3745 if (blob2)
3746 got_object_blob_close(blob2);
3747 if (f1 && fclose(f1) == EOF && err == NULL)
3748 err = got_error_from_errno("fclose");
3749 if (f2 && fclose(f2) == EOF && err == NULL)
3750 err = got_error_from_errno("fclose");
3751 return err;
3754 static const struct got_error *
3755 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3756 const char *path, int diff_context, int ignore_whitespace,
3757 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3758 struct got_repository *repo, FILE *outfile)
3760 const struct got_error *err = NULL;
3761 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3762 struct got_diff_blob_output_unidiff_arg arg;
3763 FILE *f1 = NULL, *f2 = NULL;
3764 int fd1 = -1, fd2 = -1;
3766 if (tree_id1) {
3767 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3768 if (err)
3769 goto done;
3770 fd1 = got_opentempfd();
3771 if (fd1 == -1) {
3772 err = got_error_from_errno("got_opentempfd");
3773 goto done;
3777 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3778 if (err)
3779 goto done;
3781 f1 = got_opentemp();
3782 if (f1 == NULL) {
3783 err = got_error_from_errno("got_opentemp");
3784 goto done;
3787 f2 = got_opentemp();
3788 if (f2 == NULL) {
3789 err = got_error_from_errno("got_opentemp");
3790 goto done;
3792 fd2 = got_opentempfd();
3793 if (fd2 == -1) {
3794 err = got_error_from_errno("got_opentempfd");
3795 goto done;
3797 arg.diff_context = diff_context;
3798 arg.ignore_whitespace = ignore_whitespace;
3799 arg.force_text_diff = force_text_diff;
3800 arg.diffstat = dsa;
3801 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3802 arg.outfile = outfile;
3803 arg.lines = NULL;
3804 arg.nlines = 0;
3805 while (path[0] == '/')
3806 path++;
3807 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3808 got_diff_blob_output_unidiff, &arg, 1);
3809 done:
3810 if (tree1)
3811 got_object_tree_close(tree1);
3812 if (tree2)
3813 got_object_tree_close(tree2);
3814 if (f1 && fclose(f1) == EOF && err == NULL)
3815 err = got_error_from_errno("fclose");
3816 if (f2 && fclose(f2) == EOF && err == NULL)
3817 err = got_error_from_errno("fclose");
3818 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3819 err = got_error_from_errno("close");
3820 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3821 err = got_error_from_errno("close");
3822 return err;
3825 static const struct got_error *
3826 get_changed_paths(struct got_pathlist_head *paths,
3827 struct got_commit_object *commit, struct got_repository *repo,
3828 struct got_diffstat_cb_arg *dsa)
3830 const struct got_error *err = NULL;
3831 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3832 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3833 struct got_object_qid *qid;
3834 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3835 FILE *f1 = NULL, *f2 = NULL;
3836 int fd1 = -1, fd2 = -1;
3838 if (dsa) {
3839 cb = got_diff_tree_compute_diffstat;
3841 f1 = got_opentemp();
3842 if (f1 == NULL) {
3843 err = got_error_from_errno("got_opentemp");
3844 goto done;
3846 f2 = got_opentemp();
3847 if (f2 == NULL) {
3848 err = got_error_from_errno("got_opentemp");
3849 goto done;
3851 fd1 = got_opentempfd();
3852 if (fd1 == -1) {
3853 err = got_error_from_errno("got_opentempfd");
3854 goto done;
3856 fd2 = got_opentempfd();
3857 if (fd2 == -1) {
3858 err = got_error_from_errno("got_opentempfd");
3859 goto done;
3863 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3864 if (qid != NULL) {
3865 struct got_commit_object *pcommit;
3866 err = got_object_open_as_commit(&pcommit, repo,
3867 &qid->id);
3868 if (err)
3869 return err;
3871 tree_id1 = got_object_id_dup(
3872 got_object_commit_get_tree_id(pcommit));
3873 if (tree_id1 == NULL) {
3874 got_object_commit_close(pcommit);
3875 return got_error_from_errno("got_object_id_dup");
3877 got_object_commit_close(pcommit);
3881 if (tree_id1) {
3882 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3883 if (err)
3884 goto done;
3887 tree_id2 = got_object_commit_get_tree_id(commit);
3888 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3889 if (err)
3890 goto done;
3892 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3893 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3894 done:
3895 if (tree1)
3896 got_object_tree_close(tree1);
3897 if (tree2)
3898 got_object_tree_close(tree2);
3899 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3900 err = got_error_from_errno("close");
3901 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3902 err = got_error_from_errno("close");
3903 if (f1 && fclose(f1) == EOF && err == NULL)
3904 err = got_error_from_errno("fclose");
3905 if (f2 && fclose(f2) == EOF && err == NULL)
3906 err = got_error_from_errno("fclose");
3907 free(tree_id1);
3908 return err;
3911 static const struct got_error *
3912 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3913 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3914 struct got_repository *repo, FILE *outfile)
3916 const struct got_error *err = NULL;
3917 struct got_commit_object *pcommit = NULL;
3918 char *id_str1 = NULL, *id_str2 = NULL;
3919 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3920 struct got_object_qid *qid;
3922 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3923 if (qid != NULL) {
3924 err = got_object_open_as_commit(&pcommit, repo,
3925 &qid->id);
3926 if (err)
3927 return err;
3928 err = got_object_id_str(&id_str1, &qid->id);
3929 if (err)
3930 goto done;
3933 err = got_object_id_str(&id_str2, id);
3934 if (err)
3935 goto done;
3937 if (path && path[0] != '\0') {
3938 int obj_type;
3939 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3940 if (err)
3941 goto done;
3942 if (pcommit) {
3943 err = got_object_id_by_path(&obj_id1, repo,
3944 pcommit, path);
3945 if (err) {
3946 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3947 free(obj_id2);
3948 goto done;
3952 err = got_object_get_type(&obj_type, repo, obj_id2);
3953 if (err) {
3954 free(obj_id2);
3955 goto done;
3957 fprintf(outfile,
3958 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3959 fprintf(outfile, "commit - %s\n",
3960 id_str1 ? id_str1 : "/dev/null");
3961 fprintf(outfile, "commit + %s\n", id_str2);
3962 switch (obj_type) {
3963 case GOT_OBJ_TYPE_BLOB:
3964 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3965 0, 0, dsa, repo, outfile);
3966 break;
3967 case GOT_OBJ_TYPE_TREE:
3968 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3969 0, 0, dsa, repo, outfile);
3970 break;
3971 default:
3972 err = got_error(GOT_ERR_OBJ_TYPE);
3973 break;
3975 free(obj_id1);
3976 free(obj_id2);
3977 } else {
3978 obj_id2 = got_object_commit_get_tree_id(commit);
3979 if (pcommit)
3980 obj_id1 = got_object_commit_get_tree_id(pcommit);
3981 fprintf(outfile,
3982 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3983 fprintf(outfile, "commit - %s\n",
3984 id_str1 ? id_str1 : "/dev/null");
3985 fprintf(outfile, "commit + %s\n", id_str2);
3986 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3987 dsa, repo, outfile);
3989 done:
3990 free(id_str1);
3991 free(id_str2);
3992 if (pcommit)
3993 got_object_commit_close(pcommit);
3994 return err;
3997 static char *
3998 get_datestr(time_t *time, char *datebuf)
4000 struct tm mytm, *tm;
4001 char *p, *s;
4003 tm = gmtime_r(time, &mytm);
4004 if (tm == NULL)
4005 return NULL;
4006 s = asctime_r(tm, datebuf);
4007 if (s == NULL)
4008 return NULL;
4009 p = strchr(s, '\n');
4010 if (p)
4011 *p = '\0';
4012 return s;
4015 static const struct got_error *
4016 match_commit(int *have_match, struct got_object_id *id,
4017 struct got_commit_object *commit, regex_t *regex)
4019 const struct got_error *err = NULL;
4020 regmatch_t regmatch;
4021 char *id_str = NULL, *logmsg = NULL;
4023 *have_match = 0;
4025 err = got_object_id_str(&id_str, id);
4026 if (err)
4027 return err;
4029 err = got_object_commit_get_logmsg(&logmsg, commit);
4030 if (err)
4031 goto done;
4033 if (regexec(regex, got_object_commit_get_author(commit), 1,
4034 &regmatch, 0) == 0 ||
4035 regexec(regex, got_object_commit_get_committer(commit), 1,
4036 &regmatch, 0) == 0 ||
4037 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4038 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4039 *have_match = 1;
4040 done:
4041 free(id_str);
4042 free(logmsg);
4043 return err;
4046 static void
4047 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4048 regex_t *regex)
4050 regmatch_t regmatch;
4051 struct got_pathlist_entry *pe;
4053 *have_match = 0;
4055 TAILQ_FOREACH(pe, changed_paths, entry) {
4056 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4057 *have_match = 1;
4058 break;
4063 static const struct got_error *
4064 match_patch(int *have_match, struct got_commit_object *commit,
4065 struct got_object_id *id, const char *path, int diff_context,
4066 struct got_repository *repo, regex_t *regex, FILE *f)
4068 const struct got_error *err = NULL;
4069 char *line = NULL;
4070 size_t linesize = 0;
4071 regmatch_t regmatch;
4073 *have_match = 0;
4075 err = got_opentemp_truncate(f);
4076 if (err)
4077 return err;
4079 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4080 if (err)
4081 goto done;
4083 if (fseeko(f, 0L, SEEK_SET) == -1) {
4084 err = got_error_from_errno("fseeko");
4085 goto done;
4088 while (getline(&line, &linesize, f) != -1) {
4089 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4090 *have_match = 1;
4091 break;
4094 done:
4095 free(line);
4096 return err;
4099 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4101 static const struct got_error*
4102 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4103 struct got_object_id *id, struct got_repository *repo,
4104 int local_only)
4106 static const struct got_error *err = NULL;
4107 struct got_reflist_entry *re;
4108 char *s;
4109 const char *name;
4111 *refs_str = NULL;
4113 TAILQ_FOREACH(re, refs, entry) {
4114 struct got_tag_object *tag = NULL;
4115 struct got_object_id *ref_id;
4116 int cmp;
4118 name = got_ref_get_name(re->ref);
4119 if (strcmp(name, GOT_REF_HEAD) == 0)
4120 continue;
4121 if (strncmp(name, "refs/", 5) == 0)
4122 name += 5;
4123 if (strncmp(name, "got/", 4) == 0)
4124 continue;
4125 if (strncmp(name, "heads/", 6) == 0)
4126 name += 6;
4127 if (strncmp(name, "remotes/", 8) == 0) {
4128 if (local_only)
4129 continue;
4130 name += 8;
4131 s = strstr(name, "/" GOT_REF_HEAD);
4132 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4133 continue;
4135 err = got_ref_resolve(&ref_id, repo, re->ref);
4136 if (err)
4137 break;
4138 if (strncmp(name, "tags/", 5) == 0) {
4139 err = got_object_open_as_tag(&tag, repo, ref_id);
4140 if (err) {
4141 if (err->code != GOT_ERR_OBJ_TYPE) {
4142 free(ref_id);
4143 break;
4145 /* Ref points at something other than a tag. */
4146 err = NULL;
4147 tag = NULL;
4150 cmp = got_object_id_cmp(tag ?
4151 got_object_tag_get_object_id(tag) : ref_id, id);
4152 free(ref_id);
4153 if (tag)
4154 got_object_tag_close(tag);
4155 if (cmp != 0)
4156 continue;
4157 s = *refs_str;
4158 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4159 s ? ", " : "", name) == -1) {
4160 err = got_error_from_errno("asprintf");
4161 free(s);
4162 *refs_str = NULL;
4163 break;
4165 free(s);
4168 return err;
4171 static const struct got_error *
4172 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4173 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4175 const struct got_error *err = NULL;
4176 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4177 char *comma, *s, *nl;
4178 struct got_reflist_head *refs;
4179 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4180 struct tm tm;
4181 time_t committer_time;
4183 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4184 if (refs) {
4185 err = build_refs_str(&ref_str, refs, id, repo, 1);
4186 if (err)
4187 return err;
4189 /* Display the first matching ref only. */
4190 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4191 *comma = '\0';
4194 if (ref_str == NULL) {
4195 err = got_object_id_str(&id_str, id);
4196 if (err)
4197 return err;
4200 committer_time = got_object_commit_get_committer_time(commit);
4201 if (gmtime_r(&committer_time, &tm) == NULL) {
4202 err = got_error_from_errno("gmtime_r");
4203 goto done;
4205 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4206 err = got_error(GOT_ERR_NO_SPACE);
4207 goto done;
4210 err = got_object_commit_get_logmsg(&logmsg0, commit);
4211 if (err)
4212 goto done;
4214 s = logmsg0;
4215 while (isspace((unsigned char)s[0]))
4216 s++;
4218 nl = strchr(s, '\n');
4219 if (nl) {
4220 *nl = '\0';
4223 if (ref_str)
4224 printf("%s%-7s %s\n", datebuf, ref_str, s);
4225 else
4226 printf("%s%.7s %s\n", datebuf, id_str, s);
4228 if (fflush(stdout) != 0 && err == NULL)
4229 err = got_error_from_errno("fflush");
4230 done:
4231 free(id_str);
4232 free(ref_str);
4233 free(logmsg0);
4234 return err;
4237 static const struct got_error *
4238 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4240 struct got_pathlist_entry *pe;
4242 if (header != NULL)
4243 printf("%s\n", header);
4245 TAILQ_FOREACH(pe, dsa->paths, entry) {
4246 struct got_diff_changed_path *cp = pe->data;
4247 int pad = dsa->max_path_len - pe->path_len + 1;
4249 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4250 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4252 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4253 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4254 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4256 if (fflush(stdout) != 0)
4257 return got_error_from_errno("fflush");
4259 return NULL;
4262 static const struct got_error *
4263 printfile(FILE *f)
4265 char buf[8192];
4266 size_t r;
4268 if (fseeko(f, 0L, SEEK_SET) == -1)
4269 return got_error_from_errno("fseek");
4271 for (;;) {
4272 r = fread(buf, 1, sizeof(buf), f);
4273 if (r == 0) {
4274 if (ferror(f))
4275 return got_error_from_errno("fread");
4276 if (feof(f))
4277 break;
4279 if (fwrite(buf, 1, r, stdout) != r)
4280 return got_ferror(stdout, GOT_ERR_IO);
4283 return NULL;
4286 static const struct got_error *
4287 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4288 struct got_repository *repo, const char *path,
4289 struct got_pathlist_head *changed_paths,
4290 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4291 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4292 const char *prefix)
4294 const struct got_error *err = NULL;
4295 FILE *f = NULL;
4296 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4297 char datebuf[26];
4298 time_t committer_time;
4299 const char *author, *committer;
4300 char *refs_str = NULL;
4302 err = got_object_id_str(&id_str, id);
4303 if (err)
4304 return err;
4306 if (custom_refs_str == NULL) {
4307 struct got_reflist_head *refs;
4308 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4309 if (refs) {
4310 err = build_refs_str(&refs_str, refs, id, repo, 0);
4311 if (err)
4312 goto done;
4316 printf(GOT_COMMIT_SEP_STR);
4317 if (custom_refs_str)
4318 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4319 custom_refs_str);
4320 else
4321 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4322 refs_str ? " (" : "", refs_str ? refs_str : "",
4323 refs_str ? ")" : "");
4324 free(id_str);
4325 id_str = NULL;
4326 free(refs_str);
4327 refs_str = NULL;
4328 printf("from: %s\n", got_object_commit_get_author(commit));
4329 author = got_object_commit_get_author(commit);
4330 committer = got_object_commit_get_committer(commit);
4331 if (strcmp(author, committer) != 0)
4332 printf("via: %s\n", committer);
4333 committer_time = got_object_commit_get_committer_time(commit);
4334 datestr = get_datestr(&committer_time, datebuf);
4335 if (datestr)
4336 printf("date: %s UTC\n", datestr);
4337 if (got_object_commit_get_nparents(commit) > 1) {
4338 const struct got_object_id_queue *parent_ids;
4339 struct got_object_qid *qid;
4340 int n = 1;
4341 parent_ids = got_object_commit_get_parent_ids(commit);
4342 STAILQ_FOREACH(qid, parent_ids, entry) {
4343 err = got_object_id_str(&id_str, &qid->id);
4344 if (err)
4345 goto done;
4346 printf("parent %d: %s\n", n++, id_str);
4347 free(id_str);
4348 id_str = NULL;
4352 err = got_object_commit_get_logmsg(&logmsg0, commit);
4353 if (err)
4354 goto done;
4356 logmsg = logmsg0;
4357 do {
4358 line = strsep(&logmsg, "\n");
4359 if (line)
4360 printf(" %s\n", line);
4361 } while (line);
4362 free(logmsg0);
4364 if (changed_paths && diffstat == NULL) {
4365 struct got_pathlist_entry *pe;
4367 TAILQ_FOREACH(pe, changed_paths, entry) {
4368 struct got_diff_changed_path *cp = pe->data;
4370 printf(" %c %s\n", cp->status, pe->path);
4372 printf("\n");
4374 if (show_patch) {
4375 if (diffstat) {
4376 f = got_opentemp();
4377 if (f == NULL) {
4378 err = got_error_from_errno("got_opentemp");
4379 goto done;
4383 err = print_patch(commit, id, path, diff_context, diffstat,
4384 repo, diffstat == NULL ? stdout : f);
4385 if (err)
4386 goto done;
4388 if (diffstat) {
4389 err = print_diffstat(diffstat, NULL);
4390 if (err)
4391 goto done;
4392 if (show_patch) {
4393 err = printfile(f);
4394 if (err)
4395 goto done;
4398 if (show_patch)
4399 printf("\n");
4401 if (fflush(stdout) != 0 && err == NULL)
4402 err = got_error_from_errno("fflush");
4403 done:
4404 if (f && fclose(f) == EOF && err == NULL)
4405 err = got_error_from_errno("fclose");
4406 free(id_str);
4407 free(refs_str);
4408 return err;
4411 static const struct got_error *
4412 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4413 struct got_repository *repo, const char *path, int show_changed_paths,
4414 int show_diffstat, int show_patch, const char *search_pattern,
4415 int diff_context, int limit, int log_branches, int reverse_display_order,
4416 struct got_reflist_object_id_map *refs_idmap, int one_line,
4417 FILE *tmpfile)
4419 const struct got_error *err;
4420 struct got_commit_graph *graph;
4421 regex_t regex;
4422 int have_match;
4423 struct got_object_id_queue reversed_commits;
4424 struct got_object_qid *qid;
4425 struct got_commit_object *commit;
4426 struct got_pathlist_head changed_paths;
4428 STAILQ_INIT(&reversed_commits);
4429 TAILQ_INIT(&changed_paths);
4431 if (search_pattern && regcomp(&regex, search_pattern,
4432 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4433 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4435 err = got_commit_graph_open(&graph, path, !log_branches);
4436 if (err)
4437 return err;
4438 err = got_commit_graph_iter_start(graph, root_id, repo,
4439 check_cancelled, NULL);
4440 if (err)
4441 goto done;
4442 for (;;) {
4443 struct got_object_id id;
4444 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4445 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4447 if (sigint_received || sigpipe_received)
4448 break;
4450 err = got_commit_graph_iter_next(&id, graph, repo,
4451 check_cancelled, NULL);
4452 if (err) {
4453 if (err->code == GOT_ERR_ITER_COMPLETED)
4454 err = NULL;
4455 break;
4458 err = got_object_open_as_commit(&commit, repo, &id);
4459 if (err)
4460 break;
4462 if ((show_changed_paths || (show_diffstat && !show_patch))
4463 && !reverse_display_order) {
4464 err = get_changed_paths(&changed_paths, commit, repo,
4465 show_diffstat ? &dsa : NULL);
4466 if (err)
4467 break;
4470 if (search_pattern) {
4471 err = match_commit(&have_match, &id, commit, &regex);
4472 if (err) {
4473 got_object_commit_close(commit);
4474 break;
4476 if (have_match == 0 && show_changed_paths)
4477 match_changed_paths(&have_match,
4478 &changed_paths, &regex);
4479 if (have_match == 0 && show_patch) {
4480 err = match_patch(&have_match, commit, &id,
4481 path, diff_context, repo, &regex, tmpfile);
4482 if (err)
4483 break;
4485 if (have_match == 0) {
4486 got_object_commit_close(commit);
4487 got_pathlist_free(&changed_paths,
4488 GOT_PATHLIST_FREE_ALL);
4489 continue;
4493 if (reverse_display_order) {
4494 err = got_object_qid_alloc(&qid, &id);
4495 if (err)
4496 break;
4497 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4498 got_object_commit_close(commit);
4499 } else {
4500 if (one_line)
4501 err = print_commit_oneline(commit, &id,
4502 repo, refs_idmap);
4503 else
4504 err = print_commit(commit, &id, repo, path,
4505 (show_changed_paths || show_diffstat) ?
4506 &changed_paths : NULL,
4507 show_diffstat ? &dsa : NULL, show_patch,
4508 diff_context, refs_idmap, NULL, NULL);
4509 got_object_commit_close(commit);
4510 if (err)
4511 break;
4513 if ((limit && --limit == 0) ||
4514 (end_id && got_object_id_cmp(&id, end_id) == 0))
4515 break;
4517 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4519 if (reverse_display_order) {
4520 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4521 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4522 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4524 err = got_object_open_as_commit(&commit, repo,
4525 &qid->id);
4526 if (err)
4527 break;
4528 if (show_changed_paths ||
4529 (show_diffstat && !show_patch)) {
4530 err = get_changed_paths(&changed_paths, commit,
4531 repo, show_diffstat ? &dsa : NULL);
4532 if (err)
4533 break;
4535 if (one_line)
4536 err = print_commit_oneline(commit, &qid->id,
4537 repo, refs_idmap);
4538 else
4539 err = print_commit(commit, &qid->id, repo, path,
4540 (show_changed_paths || show_diffstat) ?
4541 &changed_paths : NULL,
4542 show_diffstat ? &dsa : NULL, show_patch,
4543 diff_context, refs_idmap, NULL, NULL);
4544 got_object_commit_close(commit);
4545 if (err)
4546 break;
4547 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4550 done:
4551 while (!STAILQ_EMPTY(&reversed_commits)) {
4552 qid = STAILQ_FIRST(&reversed_commits);
4553 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4554 got_object_qid_free(qid);
4556 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4557 if (search_pattern)
4558 regfree(&regex);
4559 got_commit_graph_close(graph);
4560 return err;
4563 __dead static void
4564 usage_log(void)
4566 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4567 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4568 "[path]\n", getprogname());
4569 exit(1);
4572 static int
4573 get_default_log_limit(void)
4575 const char *got_default_log_limit;
4576 long long n;
4577 const char *errstr;
4579 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4580 if (got_default_log_limit == NULL)
4581 return 0;
4582 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4583 if (errstr != NULL)
4584 return 0;
4585 return n;
4588 static const struct got_error *
4589 cmd_log(int argc, char *argv[])
4591 const struct got_error *error;
4592 struct got_repository *repo = NULL;
4593 struct got_worktree *worktree = NULL;
4594 struct got_object_id *start_id = NULL, *end_id = NULL;
4595 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4596 const char *start_commit = NULL, *end_commit = NULL;
4597 const char *search_pattern = NULL;
4598 int diff_context = -1, ch;
4599 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4600 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4601 const char *errstr;
4602 struct got_reflist_head refs;
4603 struct got_reflist_object_id_map *refs_idmap = NULL;
4604 FILE *tmpfile = NULL;
4605 int *pack_fds = NULL;
4607 TAILQ_INIT(&refs);
4609 #ifndef PROFILE
4610 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4611 NULL)
4612 == -1)
4613 err(1, "pledge");
4614 #endif
4616 limit = get_default_log_limit();
4618 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4619 switch (ch) {
4620 case 'b':
4621 log_branches = 1;
4622 break;
4623 case 'C':
4624 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4625 &errstr);
4626 if (errstr != NULL)
4627 errx(1, "number of context lines is %s: %s",
4628 errstr, optarg);
4629 break;
4630 case 'c':
4631 start_commit = optarg;
4632 break;
4633 case 'd':
4634 show_diffstat = 1;
4635 break;
4636 case 'l':
4637 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4638 if (errstr != NULL)
4639 errx(1, "number of commits is %s: %s",
4640 errstr, optarg);
4641 break;
4642 case 'P':
4643 show_changed_paths = 1;
4644 break;
4645 case 'p':
4646 show_patch = 1;
4647 break;
4648 case 'R':
4649 reverse_display_order = 1;
4650 break;
4651 case 'r':
4652 repo_path = realpath(optarg, NULL);
4653 if (repo_path == NULL)
4654 return got_error_from_errno2("realpath",
4655 optarg);
4656 got_path_strip_trailing_slashes(repo_path);
4657 break;
4658 case 'S':
4659 search_pattern = optarg;
4660 break;
4661 case 's':
4662 one_line = 1;
4663 break;
4664 case 'x':
4665 end_commit = optarg;
4666 break;
4667 default:
4668 usage_log();
4669 /* NOTREACHED */
4673 argc -= optind;
4674 argv += optind;
4676 if (diff_context == -1)
4677 diff_context = 3;
4678 else if (!show_patch)
4679 errx(1, "-C requires -p");
4681 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4682 errx(1, "cannot use -s with -d, -p or -P");
4684 cwd = getcwd(NULL, 0);
4685 if (cwd == NULL) {
4686 error = got_error_from_errno("getcwd");
4687 goto done;
4690 error = got_repo_pack_fds_open(&pack_fds);
4691 if (error != NULL)
4692 goto done;
4694 if (repo_path == NULL) {
4695 error = got_worktree_open(&worktree, cwd,
4696 GOT_WORKTREE_GOT_DIR);
4697 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4698 goto done;
4699 error = NULL;
4702 if (argc == 1) {
4703 if (worktree) {
4704 error = got_worktree_resolve_path(&path, worktree,
4705 argv[0]);
4706 if (error)
4707 goto done;
4708 } else {
4709 path = strdup(argv[0]);
4710 if (path == NULL) {
4711 error = got_error_from_errno("strdup");
4712 goto done;
4715 } else if (argc != 0)
4716 usage_log();
4718 if (repo_path == NULL) {
4719 repo_path = worktree ?
4720 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4722 if (repo_path == NULL) {
4723 error = got_error_from_errno("strdup");
4724 goto done;
4727 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4728 if (error != NULL)
4729 goto done;
4731 error = apply_unveil(got_repo_get_path(repo), 1,
4732 worktree ? got_worktree_get_root_path(worktree) : NULL);
4733 if (error)
4734 goto done;
4736 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4737 if (error)
4738 goto done;
4740 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4741 if (error)
4742 goto done;
4744 if (start_commit == NULL) {
4745 struct got_reference *head_ref;
4746 struct got_commit_object *commit = NULL;
4747 error = got_ref_open(&head_ref, repo,
4748 worktree ? got_worktree_get_head_ref_name(worktree)
4749 : GOT_REF_HEAD, 0);
4750 if (error != NULL)
4751 goto done;
4752 error = got_ref_resolve(&start_id, repo, head_ref);
4753 got_ref_close(head_ref);
4754 if (error != NULL)
4755 goto done;
4756 error = got_object_open_as_commit(&commit, repo,
4757 start_id);
4758 if (error != NULL)
4759 goto done;
4760 got_object_commit_close(commit);
4761 } else {
4762 char *keyword_idstr = NULL;
4764 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4765 repo, worktree);
4766 if (error != NULL)
4767 goto done;
4768 if (keyword_idstr != NULL)
4769 start_commit = keyword_idstr;
4771 error = got_repo_match_object_id(&start_id, NULL,
4772 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4773 free(keyword_idstr);
4774 if (error != NULL)
4775 goto done;
4777 if (end_commit != NULL) {
4778 error = got_repo_match_object_id(&end_id, NULL,
4779 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4780 if (error != NULL)
4781 goto done;
4784 if (worktree) {
4786 * If a path was specified on the command line it was resolved
4787 * to a path in the work tree above. Prepend the work tree's
4788 * path prefix to obtain the corresponding in-repository path.
4790 if (path) {
4791 const char *prefix;
4792 prefix = got_worktree_get_path_prefix(worktree);
4793 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4794 (path[0] != '\0') ? "/" : "", path) == -1) {
4795 error = got_error_from_errno("asprintf");
4796 goto done;
4799 } else
4800 error = got_repo_map_path(&in_repo_path, repo,
4801 path ? path : "");
4802 if (error != NULL)
4803 goto done;
4804 if (in_repo_path) {
4805 free(path);
4806 path = in_repo_path;
4809 if (worktree) {
4810 /* Release work tree lock. */
4811 got_worktree_close(worktree);
4812 worktree = NULL;
4815 if (search_pattern && show_patch) {
4816 tmpfile = got_opentemp();
4817 if (tmpfile == NULL) {
4818 error = got_error_from_errno("got_opentemp");
4819 goto done;
4823 error = print_commits(start_id, end_id, repo, path ? path : "",
4824 show_changed_paths, show_diffstat, show_patch, search_pattern,
4825 diff_context, limit, log_branches, reverse_display_order,
4826 refs_idmap, one_line, tmpfile);
4827 done:
4828 free(path);
4829 free(repo_path);
4830 free(cwd);
4831 free(start_id);
4832 free(end_id);
4833 if (worktree)
4834 got_worktree_close(worktree);
4835 if (repo) {
4836 const struct got_error *close_err = got_repo_close(repo);
4837 if (error == NULL)
4838 error = close_err;
4840 if (pack_fds) {
4841 const struct got_error *pack_err =
4842 got_repo_pack_fds_close(pack_fds);
4843 if (error == NULL)
4844 error = pack_err;
4846 if (refs_idmap)
4847 got_reflist_object_id_map_free(refs_idmap);
4848 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4849 error = got_error_from_errno("fclose");
4850 got_ref_list_free(&refs);
4851 return error;
4854 __dead static void
4855 usage_diff(void)
4857 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4858 "[-r repository-path] [object1 object2 | path ...]\n",
4859 getprogname());
4860 exit(1);
4863 struct print_diff_arg {
4864 struct got_repository *repo;
4865 struct got_worktree *worktree;
4866 struct got_diffstat_cb_arg *diffstat;
4867 int diff_context;
4868 const char *id_str;
4869 int header_shown;
4870 int diff_staged;
4871 enum got_diff_algorithm diff_algo;
4872 int ignore_whitespace;
4873 int force_text_diff;
4874 FILE *f1;
4875 FILE *f2;
4876 FILE *outfile;
4880 * Create a file which contains the target path of a symlink so we can feed
4881 * it as content to the diff engine.
4883 static const struct got_error *
4884 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4885 const char *abspath)
4887 const struct got_error *err = NULL;
4888 char target_path[PATH_MAX];
4889 ssize_t target_len, outlen;
4891 *fd = -1;
4893 if (dirfd != -1) {
4894 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4895 if (target_len == -1)
4896 return got_error_from_errno2("readlinkat", abspath);
4897 } else {
4898 target_len = readlink(abspath, target_path, PATH_MAX);
4899 if (target_len == -1)
4900 return got_error_from_errno2("readlink", abspath);
4903 *fd = got_opentempfd();
4904 if (*fd == -1)
4905 return got_error_from_errno("got_opentempfd");
4907 outlen = write(*fd, target_path, target_len);
4908 if (outlen == -1) {
4909 err = got_error_from_errno("got_opentempfd");
4910 goto done;
4913 if (lseek(*fd, 0, SEEK_SET) == -1) {
4914 err = got_error_from_errno2("lseek", abspath);
4915 goto done;
4917 done:
4918 if (err) {
4919 close(*fd);
4920 *fd = -1;
4922 return err;
4925 static const struct got_error *
4926 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4927 const char *path, struct got_object_id *blob_id,
4928 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4929 int dirfd, const char *de_name)
4931 struct print_diff_arg *a = arg;
4932 const struct got_error *err = NULL;
4933 struct got_blob_object *blob1 = NULL;
4934 int fd = -1, fd1 = -1, fd2 = -1;
4935 FILE *f2 = NULL;
4936 char *abspath = NULL, *label1 = NULL;
4937 struct stat sb;
4938 off_t size1 = 0;
4939 int f2_exists = 0;
4941 memset(&sb, 0, sizeof(sb));
4943 if (a->diff_staged) {
4944 if (staged_status != GOT_STATUS_MODIFY &&
4945 staged_status != GOT_STATUS_ADD &&
4946 staged_status != GOT_STATUS_DELETE)
4947 return NULL;
4948 } else {
4949 if (staged_status == GOT_STATUS_DELETE)
4950 return NULL;
4951 if (status == GOT_STATUS_NONEXISTENT)
4952 return got_error_set_errno(ENOENT, path);
4953 if (status != GOT_STATUS_MODIFY &&
4954 status != GOT_STATUS_ADD &&
4955 status != GOT_STATUS_DELETE &&
4956 status != GOT_STATUS_CONFLICT)
4957 return NULL;
4960 err = got_opentemp_truncate(a->f1);
4961 if (err)
4962 return got_error_from_errno("got_opentemp_truncate");
4963 err = got_opentemp_truncate(a->f2);
4964 if (err)
4965 return got_error_from_errno("got_opentemp_truncate");
4967 if (!a->header_shown) {
4968 if (fprintf(a->outfile, "diff %s%s\n",
4969 a->diff_staged ? "-s " : "",
4970 got_worktree_get_root_path(a->worktree)) < 0) {
4971 err = got_error_from_errno("fprintf");
4972 goto done;
4974 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4975 err = got_error_from_errno("fprintf");
4976 goto done;
4978 if (fprintf(a->outfile, "path + %s%s\n",
4979 got_worktree_get_root_path(a->worktree),
4980 a->diff_staged ? " (staged changes)" : "") < 0) {
4981 err = got_error_from_errno("fprintf");
4982 goto done;
4984 a->header_shown = 1;
4987 if (a->diff_staged) {
4988 const char *label1 = NULL, *label2 = NULL;
4989 switch (staged_status) {
4990 case GOT_STATUS_MODIFY:
4991 label1 = path;
4992 label2 = path;
4993 break;
4994 case GOT_STATUS_ADD:
4995 label2 = path;
4996 break;
4997 case GOT_STATUS_DELETE:
4998 label1 = path;
4999 break;
5000 default:
5001 return got_error(GOT_ERR_FILE_STATUS);
5003 fd1 = got_opentempfd();
5004 if (fd1 == -1) {
5005 err = got_error_from_errno("got_opentempfd");
5006 goto done;
5008 fd2 = got_opentempfd();
5009 if (fd2 == -1) {
5010 err = got_error_from_errno("got_opentempfd");
5011 goto done;
5013 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5014 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5015 a->diff_algo, a->diff_context, a->ignore_whitespace,
5016 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5017 goto done;
5020 fd1 = got_opentempfd();
5021 if (fd1 == -1) {
5022 err = got_error_from_errno("got_opentempfd");
5023 goto done;
5026 if (staged_status == GOT_STATUS_ADD ||
5027 staged_status == GOT_STATUS_MODIFY) {
5028 char *id_str;
5029 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5030 8192, fd1);
5031 if (err)
5032 goto done;
5033 err = got_object_id_str(&id_str, staged_blob_id);
5034 if (err)
5035 goto done;
5036 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5037 err = got_error_from_errno("asprintf");
5038 free(id_str);
5039 goto done;
5041 free(id_str);
5042 } else if (status != GOT_STATUS_ADD) {
5043 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5044 fd1);
5045 if (err)
5046 goto done;
5049 if (status != GOT_STATUS_DELETE) {
5050 if (asprintf(&abspath, "%s/%s",
5051 got_worktree_get_root_path(a->worktree), path) == -1) {
5052 err = got_error_from_errno("asprintf");
5053 goto done;
5056 if (dirfd != -1) {
5057 fd = openat(dirfd, de_name,
5058 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5059 if (fd == -1) {
5060 if (!got_err_open_nofollow_on_symlink()) {
5061 err = got_error_from_errno2("openat",
5062 abspath);
5063 goto done;
5065 err = get_symlink_target_file(&fd, dirfd,
5066 de_name, abspath);
5067 if (err)
5068 goto done;
5070 } else {
5071 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5072 if (fd == -1) {
5073 if (!got_err_open_nofollow_on_symlink()) {
5074 err = got_error_from_errno2("open",
5075 abspath);
5076 goto done;
5078 err = get_symlink_target_file(&fd, dirfd,
5079 de_name, abspath);
5080 if (err)
5081 goto done;
5084 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5085 err = got_error_from_errno2("fstatat", abspath);
5086 goto done;
5088 f2 = fdopen(fd, "r");
5089 if (f2 == NULL) {
5090 err = got_error_from_errno2("fdopen", abspath);
5091 goto done;
5093 fd = -1;
5094 f2_exists = 1;
5097 if (blob1) {
5098 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5099 a->f1, blob1);
5100 if (err)
5101 goto done;
5104 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5105 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5106 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5107 done:
5108 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5109 err = got_error_from_errno("close");
5110 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5111 err = got_error_from_errno("close");
5112 if (blob1)
5113 got_object_blob_close(blob1);
5114 if (fd != -1 && close(fd) == -1 && err == NULL)
5115 err = got_error_from_errno("close");
5116 if (f2 && fclose(f2) == EOF && err == NULL)
5117 err = got_error_from_errno("fclose");
5118 free(abspath);
5119 return err;
5122 static const struct got_error *
5123 cmd_diff(int argc, char *argv[])
5125 const struct got_error *error;
5126 struct got_repository *repo = NULL;
5127 struct got_worktree *worktree = NULL;
5128 char *cwd = NULL, *repo_path = NULL;
5129 const char *commit_args[2] = { NULL, NULL };
5130 int ncommit_args = 0;
5131 struct got_object_id *ids[2] = { NULL, NULL };
5132 char *labels[2] = { NULL, NULL };
5133 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5134 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5135 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5136 const char *errstr;
5137 struct got_reflist_head refs;
5138 struct got_pathlist_head diffstat_paths, paths;
5139 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5140 int fd1 = -1, fd2 = -1;
5141 int *pack_fds = NULL;
5142 struct got_diffstat_cb_arg dsa;
5144 memset(&dsa, 0, sizeof(dsa));
5146 TAILQ_INIT(&refs);
5147 TAILQ_INIT(&paths);
5148 TAILQ_INIT(&diffstat_paths);
5150 #ifndef PROFILE
5151 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5152 NULL) == -1)
5153 err(1, "pledge");
5154 #endif
5156 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5157 switch (ch) {
5158 case 'a':
5159 force_text_diff = 1;
5160 break;
5161 case 'C':
5162 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5163 &errstr);
5164 if (errstr != NULL)
5165 errx(1, "number of context lines is %s: %s",
5166 errstr, optarg);
5167 break;
5168 case 'c':
5169 if (ncommit_args >= 2)
5170 errx(1, "too many -c options used");
5171 commit_args[ncommit_args++] = optarg;
5172 break;
5173 case 'd':
5174 show_diffstat = 1;
5175 break;
5176 case 'P':
5177 force_path = 1;
5178 break;
5179 case 'r':
5180 repo_path = realpath(optarg, NULL);
5181 if (repo_path == NULL)
5182 return got_error_from_errno2("realpath",
5183 optarg);
5184 got_path_strip_trailing_slashes(repo_path);
5185 rflag = 1;
5186 break;
5187 case 's':
5188 diff_staged = 1;
5189 break;
5190 case 'w':
5191 ignore_whitespace = 1;
5192 break;
5193 default:
5194 usage_diff();
5195 /* NOTREACHED */
5199 argc -= optind;
5200 argv += optind;
5202 cwd = getcwd(NULL, 0);
5203 if (cwd == NULL) {
5204 error = got_error_from_errno("getcwd");
5205 goto done;
5208 error = got_repo_pack_fds_open(&pack_fds);
5209 if (error != NULL)
5210 goto done;
5212 if (repo_path == NULL) {
5213 error = got_worktree_open(&worktree, cwd,
5214 GOT_WORKTREE_GOT_DIR);
5215 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5216 goto done;
5217 else
5218 error = NULL;
5219 if (worktree) {
5220 repo_path =
5221 strdup(got_worktree_get_repo_path(worktree));
5222 if (repo_path == NULL) {
5223 error = got_error_from_errno("strdup");
5224 goto done;
5226 } else {
5227 repo_path = strdup(cwd);
5228 if (repo_path == NULL) {
5229 error = got_error_from_errno("strdup");
5230 goto done;
5235 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5236 free(repo_path);
5237 if (error != NULL)
5238 goto done;
5240 if (show_diffstat) {
5241 dsa.paths = &diffstat_paths;
5242 dsa.force_text = force_text_diff;
5243 dsa.ignore_ws = ignore_whitespace;
5244 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5247 if (rflag || worktree == NULL || ncommit_args > 0) {
5248 if (force_path) {
5249 error = got_error_msg(GOT_ERR_NOT_IMPL,
5250 "-P option can only be used when diffing "
5251 "a work tree");
5252 goto done;
5254 if (diff_staged) {
5255 error = got_error_msg(GOT_ERR_NOT_IMPL,
5256 "-s option can only be used when diffing "
5257 "a work tree");
5258 goto done;
5262 error = apply_unveil(got_repo_get_path(repo), 1,
5263 worktree ? got_worktree_get_root_path(worktree) : NULL);
5264 if (error)
5265 goto done;
5267 if ((!force_path && argc == 2) || ncommit_args > 0) {
5268 int obj_type = (ncommit_args > 0 ?
5269 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5270 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5271 NULL);
5272 if (error)
5273 goto done;
5274 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5275 const char *arg;
5276 char *keyword_idstr = NULL;
5278 if (ncommit_args > 0)
5279 arg = commit_args[i];
5280 else
5281 arg = argv[i];
5283 error = got_keyword_to_idstr(&keyword_idstr, arg,
5284 repo, worktree);
5285 if (error != NULL)
5286 goto done;
5287 if (keyword_idstr != NULL)
5288 arg = keyword_idstr;
5290 error = got_repo_match_object_id(&ids[i], &labels[i],
5291 arg, obj_type, &refs, repo);
5292 free(keyword_idstr);
5293 if (error) {
5294 if (error->code != GOT_ERR_NOT_REF &&
5295 error->code != GOT_ERR_NO_OBJ)
5296 goto done;
5297 if (ncommit_args > 0)
5298 goto done;
5299 error = NULL;
5300 break;
5305 f1 = got_opentemp();
5306 if (f1 == NULL) {
5307 error = got_error_from_errno("got_opentemp");
5308 goto done;
5311 f2 = got_opentemp();
5312 if (f2 == NULL) {
5313 error = got_error_from_errno("got_opentemp");
5314 goto done;
5317 outfile = got_opentemp();
5318 if (outfile == NULL) {
5319 error = got_error_from_errno("got_opentemp");
5320 goto done;
5323 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5324 struct print_diff_arg arg;
5325 char *id_str;
5327 if (worktree == NULL) {
5328 if (argc == 2 && ids[0] == NULL) {
5329 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5330 goto done;
5331 } else if (argc == 2 && ids[1] == NULL) {
5332 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5333 goto done;
5334 } else if (argc > 0) {
5335 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5336 "%s", "specified paths cannot be resolved");
5337 goto done;
5338 } else {
5339 error = got_error(GOT_ERR_NOT_WORKTREE);
5340 goto done;
5344 error = get_worktree_paths_from_argv(&paths, argc, argv,
5345 worktree);
5346 if (error)
5347 goto done;
5349 error = got_object_id_str(&id_str,
5350 got_worktree_get_base_commit_id(worktree));
5351 if (error)
5352 goto done;
5353 arg.repo = repo;
5354 arg.worktree = worktree;
5355 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5356 arg.diff_context = diff_context;
5357 arg.id_str = id_str;
5358 arg.header_shown = 0;
5359 arg.diff_staged = diff_staged;
5360 arg.ignore_whitespace = ignore_whitespace;
5361 arg.force_text_diff = force_text_diff;
5362 arg.diffstat = show_diffstat ? &dsa : NULL;
5363 arg.f1 = f1;
5364 arg.f2 = f2;
5365 arg.outfile = outfile;
5367 error = got_worktree_status(worktree, &paths, repo, 0,
5368 print_diff, &arg, check_cancelled, NULL);
5369 free(id_str);
5370 if (error)
5371 goto done;
5373 if (show_diffstat && dsa.nfiles > 0) {
5374 char *header;
5376 if (asprintf(&header, "diffstat %s%s",
5377 diff_staged ? "-s " : "",
5378 got_worktree_get_root_path(worktree)) == -1) {
5379 error = got_error_from_errno("asprintf");
5380 goto done;
5383 error = print_diffstat(&dsa, header);
5384 free(header);
5385 if (error)
5386 goto done;
5389 error = printfile(outfile);
5390 goto done;
5393 if (ncommit_args == 1) {
5394 struct got_commit_object *commit;
5395 error = got_object_open_as_commit(&commit, repo, ids[0]);
5396 if (error)
5397 goto done;
5399 labels[1] = labels[0];
5400 ids[1] = ids[0];
5401 if (got_object_commit_get_nparents(commit) > 0) {
5402 const struct got_object_id_queue *pids;
5403 struct got_object_qid *pid;
5404 pids = got_object_commit_get_parent_ids(commit);
5405 pid = STAILQ_FIRST(pids);
5406 ids[0] = got_object_id_dup(&pid->id);
5407 if (ids[0] == NULL) {
5408 error = got_error_from_errno(
5409 "got_object_id_dup");
5410 got_object_commit_close(commit);
5411 goto done;
5413 error = got_object_id_str(&labels[0], ids[0]);
5414 if (error) {
5415 got_object_commit_close(commit);
5416 goto done;
5418 } else {
5419 ids[0] = NULL;
5420 labels[0] = strdup("/dev/null");
5421 if (labels[0] == NULL) {
5422 error = got_error_from_errno("strdup");
5423 got_object_commit_close(commit);
5424 goto done;
5428 got_object_commit_close(commit);
5431 if (ncommit_args == 0 && argc > 2) {
5432 error = got_error_msg(GOT_ERR_BAD_PATH,
5433 "path arguments cannot be used when diffing two objects");
5434 goto done;
5437 if (ids[0]) {
5438 error = got_object_get_type(&type1, repo, ids[0]);
5439 if (error)
5440 goto done;
5443 error = got_object_get_type(&type2, repo, ids[1]);
5444 if (error)
5445 goto done;
5446 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5447 error = got_error(GOT_ERR_OBJ_TYPE);
5448 goto done;
5450 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5451 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5452 "path arguments cannot be used when diffing blobs");
5453 goto done;
5456 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5457 char *in_repo_path;
5458 struct got_pathlist_entry *new;
5459 if (worktree) {
5460 const char *prefix;
5461 char *p;
5462 error = got_worktree_resolve_path(&p, worktree,
5463 argv[i]);
5464 if (error)
5465 goto done;
5466 prefix = got_worktree_get_path_prefix(worktree);
5467 while (prefix[0] == '/')
5468 prefix++;
5469 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5470 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5471 p) == -1) {
5472 error = got_error_from_errno("asprintf");
5473 free(p);
5474 goto done;
5476 free(p);
5477 } else {
5478 char *mapped_path, *s;
5479 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5480 if (error)
5481 goto done;
5482 s = mapped_path;
5483 while (s[0] == '/')
5484 s++;
5485 in_repo_path = strdup(s);
5486 if (in_repo_path == NULL) {
5487 error = got_error_from_errno("asprintf");
5488 free(mapped_path);
5489 goto done;
5491 free(mapped_path);
5494 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5495 if (error || new == NULL /* duplicate */)
5496 free(in_repo_path);
5497 if (error)
5498 goto done;
5501 if (worktree) {
5502 /* Release work tree lock. */
5503 got_worktree_close(worktree);
5504 worktree = NULL;
5507 fd1 = got_opentempfd();
5508 if (fd1 == -1) {
5509 error = got_error_from_errno("got_opentempfd");
5510 goto done;
5513 fd2 = got_opentempfd();
5514 if (fd2 == -1) {
5515 error = got_error_from_errno("got_opentempfd");
5516 goto done;
5519 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5520 case GOT_OBJ_TYPE_BLOB:
5521 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5522 fd1, fd2, ids[0], ids[1], NULL, NULL,
5523 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5524 ignore_whitespace, force_text_diff,
5525 show_diffstat ? &dsa : NULL, repo, outfile);
5526 break;
5527 case GOT_OBJ_TYPE_TREE:
5528 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5529 ids[0], ids[1], &paths, "", "",
5530 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5531 ignore_whitespace, force_text_diff,
5532 show_diffstat ? &dsa : NULL, repo, outfile);
5533 break;
5534 case GOT_OBJ_TYPE_COMMIT:
5535 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5536 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5537 fd1, fd2, ids[0], ids[1], &paths,
5538 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5539 ignore_whitespace, force_text_diff,
5540 show_diffstat ? &dsa : NULL, repo, outfile);
5541 break;
5542 default:
5543 error = got_error(GOT_ERR_OBJ_TYPE);
5545 if (error)
5546 goto done;
5548 if (show_diffstat && dsa.nfiles > 0) {
5549 char *header = NULL;
5551 if (asprintf(&header, "diffstat %s %s",
5552 labels[0], labels[1]) == -1) {
5553 error = got_error_from_errno("asprintf");
5554 goto done;
5557 error = print_diffstat(&dsa, header);
5558 free(header);
5559 if (error)
5560 goto done;
5563 error = printfile(outfile);
5565 done:
5566 free(labels[0]);
5567 free(labels[1]);
5568 free(ids[0]);
5569 free(ids[1]);
5570 if (worktree)
5571 got_worktree_close(worktree);
5572 if (repo) {
5573 const struct got_error *close_err = got_repo_close(repo);
5574 if (error == NULL)
5575 error = close_err;
5577 if (pack_fds) {
5578 const struct got_error *pack_err =
5579 got_repo_pack_fds_close(pack_fds);
5580 if (error == NULL)
5581 error = pack_err;
5583 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5584 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5585 got_ref_list_free(&refs);
5586 if (outfile && fclose(outfile) == EOF && error == NULL)
5587 error = got_error_from_errno("fclose");
5588 if (f1 && fclose(f1) == EOF && error == NULL)
5589 error = got_error_from_errno("fclose");
5590 if (f2 && fclose(f2) == EOF && error == NULL)
5591 error = got_error_from_errno("fclose");
5592 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5593 error = got_error_from_errno("close");
5594 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5595 error = got_error_from_errno("close");
5596 return error;
5599 __dead static void
5600 usage_blame(void)
5602 fprintf(stderr,
5603 "usage: %s blame [-c commit] [-r repository-path] path\n",
5604 getprogname());
5605 exit(1);
5608 struct blame_line {
5609 int annotated;
5610 char *id_str;
5611 char *committer;
5612 char datebuf[11]; /* YYYY-MM-DD + NUL */
5615 struct blame_cb_args {
5616 struct blame_line *lines;
5617 int nlines;
5618 int nlines_prec;
5619 int lineno_cur;
5620 off_t *line_offsets;
5621 FILE *f;
5622 struct got_repository *repo;
5625 static const struct got_error *
5626 blame_cb(void *arg, int nlines, int lineno,
5627 struct got_commit_object *commit, struct got_object_id *id)
5629 const struct got_error *err = NULL;
5630 struct blame_cb_args *a = arg;
5631 struct blame_line *bline;
5632 char *line = NULL;
5633 size_t linesize = 0;
5634 off_t offset;
5635 struct tm tm;
5636 time_t committer_time;
5638 if (nlines != a->nlines ||
5639 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5640 return got_error(GOT_ERR_RANGE);
5642 if (sigint_received)
5643 return got_error(GOT_ERR_ITER_COMPLETED);
5645 if (lineno == -1)
5646 return NULL; /* no change in this commit */
5648 /* Annotate this line. */
5649 bline = &a->lines[lineno - 1];
5650 if (bline->annotated)
5651 return NULL;
5652 err = got_object_id_str(&bline->id_str, id);
5653 if (err)
5654 return err;
5656 bline->committer = strdup(got_object_commit_get_committer(commit));
5657 if (bline->committer == NULL) {
5658 err = got_error_from_errno("strdup");
5659 goto done;
5662 committer_time = got_object_commit_get_committer_time(commit);
5663 if (gmtime_r(&committer_time, &tm) == NULL)
5664 return got_error_from_errno("gmtime_r");
5665 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5666 &tm) == 0) {
5667 err = got_error(GOT_ERR_NO_SPACE);
5668 goto done;
5670 bline->annotated = 1;
5672 /* Print lines annotated so far. */
5673 bline = &a->lines[a->lineno_cur - 1];
5674 if (!bline->annotated)
5675 goto done;
5677 offset = a->line_offsets[a->lineno_cur - 1];
5678 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5679 err = got_error_from_errno("fseeko");
5680 goto done;
5683 while (a->lineno_cur <= a->nlines && bline->annotated) {
5684 char *smallerthan, *at, *nl, *committer;
5685 size_t len;
5687 if (getline(&line, &linesize, a->f) == -1) {
5688 if (ferror(a->f))
5689 err = got_error_from_errno("getline");
5690 break;
5693 committer = bline->committer;
5694 smallerthan = strchr(committer, '<');
5695 if (smallerthan && smallerthan[1] != '\0')
5696 committer = smallerthan + 1;
5697 at = strchr(committer, '@');
5698 if (at)
5699 *at = '\0';
5700 len = strlen(committer);
5701 if (len >= 9)
5702 committer[8] = '\0';
5704 nl = strchr(line, '\n');
5705 if (nl)
5706 *nl = '\0';
5707 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5708 bline->id_str, bline->datebuf, committer, line);
5710 a->lineno_cur++;
5711 bline = &a->lines[a->lineno_cur - 1];
5713 done:
5714 free(line);
5715 return err;
5718 static const struct got_error *
5719 cmd_blame(int argc, char *argv[])
5721 const struct got_error *error;
5722 struct got_repository *repo = NULL;
5723 struct got_worktree *worktree = NULL;
5724 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5725 char *link_target = NULL;
5726 struct got_object_id *obj_id = NULL;
5727 struct got_object_id *commit_id = NULL;
5728 struct got_commit_object *commit = NULL;
5729 struct got_blob_object *blob = NULL;
5730 char *commit_id_str = NULL, *keyword_idstr = NULL;
5731 struct blame_cb_args bca;
5732 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5733 off_t filesize;
5734 int *pack_fds = NULL;
5735 FILE *f1 = NULL, *f2 = NULL;
5737 fd1 = got_opentempfd();
5738 if (fd1 == -1)
5739 return got_error_from_errno("got_opentempfd");
5741 memset(&bca, 0, sizeof(bca));
5743 #ifndef PROFILE
5744 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5745 NULL) == -1)
5746 err(1, "pledge");
5747 #endif
5749 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5750 switch (ch) {
5751 case 'c':
5752 commit_id_str = optarg;
5753 break;
5754 case 'r':
5755 repo_path = realpath(optarg, NULL);
5756 if (repo_path == NULL)
5757 return got_error_from_errno2("realpath",
5758 optarg);
5759 got_path_strip_trailing_slashes(repo_path);
5760 break;
5761 default:
5762 usage_blame();
5763 /* NOTREACHED */
5767 argc -= optind;
5768 argv += optind;
5770 if (argc == 1)
5771 path = argv[0];
5772 else
5773 usage_blame();
5775 cwd = getcwd(NULL, 0);
5776 if (cwd == NULL) {
5777 error = got_error_from_errno("getcwd");
5778 goto done;
5781 error = got_repo_pack_fds_open(&pack_fds);
5782 if (error != NULL)
5783 goto done;
5785 if (repo_path == NULL) {
5786 error = got_worktree_open(&worktree, cwd,
5787 GOT_WORKTREE_GOT_DIR);
5788 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5789 goto done;
5790 else
5791 error = NULL;
5792 if (worktree) {
5793 repo_path =
5794 strdup(got_worktree_get_repo_path(worktree));
5795 if (repo_path == NULL) {
5796 error = got_error_from_errno("strdup");
5797 if (error)
5798 goto done;
5800 } else {
5801 repo_path = strdup(cwd);
5802 if (repo_path == NULL) {
5803 error = got_error_from_errno("strdup");
5804 goto done;
5809 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5810 if (error != NULL)
5811 goto done;
5813 if (worktree) {
5814 const char *prefix = got_worktree_get_path_prefix(worktree);
5815 char *p;
5817 error = got_worktree_resolve_path(&p, worktree, path);
5818 if (error)
5819 goto done;
5820 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5821 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5822 p) == -1) {
5823 error = got_error_from_errno("asprintf");
5824 free(p);
5825 goto done;
5827 free(p);
5828 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5829 } else {
5830 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5831 if (error)
5832 goto done;
5833 error = got_repo_map_path(&in_repo_path, repo, path);
5835 if (error)
5836 goto done;
5838 if (commit_id_str == NULL) {
5839 struct got_reference *head_ref;
5840 error = got_ref_open(&head_ref, repo, worktree ?
5841 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5842 if (error != NULL)
5843 goto done;
5844 error = got_ref_resolve(&commit_id, repo, head_ref);
5845 got_ref_close(head_ref);
5846 if (error != NULL)
5847 goto done;
5848 } else {
5849 struct got_reflist_head refs;
5851 TAILQ_INIT(&refs);
5852 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5853 NULL);
5854 if (error)
5855 goto done;
5857 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5858 repo, worktree);
5859 if (error != NULL)
5860 goto done;
5861 if (keyword_idstr != NULL)
5862 commit_id_str = keyword_idstr;
5864 error = got_repo_match_object_id(&commit_id, NULL,
5865 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5866 got_ref_list_free(&refs);
5867 if (error)
5868 goto done;
5871 if (worktree) {
5872 /* Release work tree lock. */
5873 got_worktree_close(worktree);
5874 worktree = NULL;
5877 error = got_object_open_as_commit(&commit, repo, commit_id);
5878 if (error)
5879 goto done;
5881 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5882 commit, repo);
5883 if (error)
5884 goto done;
5886 error = got_object_id_by_path(&obj_id, repo, commit,
5887 link_target ? link_target : in_repo_path);
5888 if (error)
5889 goto done;
5891 error = got_object_get_type(&obj_type, repo, obj_id);
5892 if (error)
5893 goto done;
5895 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5896 error = got_error_path(link_target ? link_target : in_repo_path,
5897 GOT_ERR_OBJ_TYPE);
5898 goto done;
5901 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5902 if (error)
5903 goto done;
5904 bca.f = got_opentemp();
5905 if (bca.f == NULL) {
5906 error = got_error_from_errno("got_opentemp");
5907 goto done;
5909 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5910 &bca.line_offsets, bca.f, blob);
5911 if (error || bca.nlines == 0)
5912 goto done;
5914 /* Don't include \n at EOF in the blame line count. */
5915 if (bca.line_offsets[bca.nlines - 1] == filesize)
5916 bca.nlines--;
5918 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5919 if (bca.lines == NULL) {
5920 error = got_error_from_errno("calloc");
5921 goto done;
5923 bca.lineno_cur = 1;
5924 bca.nlines_prec = 0;
5925 i = bca.nlines;
5926 while (i > 0) {
5927 i /= 10;
5928 bca.nlines_prec++;
5930 bca.repo = repo;
5932 fd2 = got_opentempfd();
5933 if (fd2 == -1) {
5934 error = got_error_from_errno("got_opentempfd");
5935 goto done;
5937 fd3 = got_opentempfd();
5938 if (fd3 == -1) {
5939 error = got_error_from_errno("got_opentempfd");
5940 goto done;
5942 f1 = got_opentemp();
5943 if (f1 == NULL) {
5944 error = got_error_from_errno("got_opentemp");
5945 goto done;
5947 f2 = got_opentemp();
5948 if (f2 == NULL) {
5949 error = got_error_from_errno("got_opentemp");
5950 goto done;
5952 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5953 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5954 check_cancelled, NULL, fd2, fd3, f1, f2);
5955 done:
5956 free(keyword_idstr);
5957 free(in_repo_path);
5958 free(link_target);
5959 free(repo_path);
5960 free(cwd);
5961 free(commit_id);
5962 free(obj_id);
5963 if (commit)
5964 got_object_commit_close(commit);
5966 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5967 error = got_error_from_errno("close");
5968 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5969 error = got_error_from_errno("close");
5970 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5971 error = got_error_from_errno("close");
5972 if (f1 && fclose(f1) == EOF && error == NULL)
5973 error = got_error_from_errno("fclose");
5974 if (f2 && fclose(f2) == EOF && error == NULL)
5975 error = got_error_from_errno("fclose");
5977 if (blob)
5978 got_object_blob_close(blob);
5979 if (worktree)
5980 got_worktree_close(worktree);
5981 if (repo) {
5982 const struct got_error *close_err = got_repo_close(repo);
5983 if (error == NULL)
5984 error = close_err;
5986 if (pack_fds) {
5987 const struct got_error *pack_err =
5988 got_repo_pack_fds_close(pack_fds);
5989 if (error == NULL)
5990 error = pack_err;
5992 if (bca.lines) {
5993 for (i = 0; i < bca.nlines; i++) {
5994 struct blame_line *bline = &bca.lines[i];
5995 free(bline->id_str);
5996 free(bline->committer);
5998 free(bca.lines);
6000 free(bca.line_offsets);
6001 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6002 error = got_error_from_errno("fclose");
6003 return error;
6006 __dead static void
6007 usage_tree(void)
6009 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6010 "[path]\n", getprogname());
6011 exit(1);
6014 static const struct got_error *
6015 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6016 const char *root_path, struct got_repository *repo)
6018 const struct got_error *err = NULL;
6019 int is_root_path = (strcmp(path, root_path) == 0);
6020 const char *modestr = "";
6021 mode_t mode = got_tree_entry_get_mode(te);
6022 char *link_target = NULL;
6024 path += strlen(root_path);
6025 while (path[0] == '/')
6026 path++;
6028 if (got_object_tree_entry_is_submodule(te))
6029 modestr = "$";
6030 else if (S_ISLNK(mode)) {
6031 int i;
6033 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6034 if (err)
6035 return err;
6036 for (i = 0; link_target[i] != '\0'; i++) {
6037 if (!isprint((unsigned char)link_target[i]))
6038 link_target[i] = '?';
6041 modestr = "@";
6043 else if (S_ISDIR(mode))
6044 modestr = "/";
6045 else if (mode & S_IXUSR)
6046 modestr = "*";
6048 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6049 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6050 link_target ? " -> ": "", link_target ? link_target : "");
6052 free(link_target);
6053 return NULL;
6056 static const struct got_error *
6057 print_tree(const char *path, struct got_commit_object *commit,
6058 int show_ids, int recurse, const char *root_path,
6059 struct got_repository *repo)
6061 const struct got_error *err = NULL;
6062 struct got_object_id *tree_id = NULL;
6063 struct got_tree_object *tree = NULL;
6064 int nentries, i;
6066 err = got_object_id_by_path(&tree_id, repo, commit, path);
6067 if (err)
6068 goto done;
6070 err = got_object_open_as_tree(&tree, repo, tree_id);
6071 if (err)
6072 goto done;
6073 nentries = got_object_tree_get_nentries(tree);
6074 for (i = 0; i < nentries; i++) {
6075 struct got_tree_entry *te;
6076 char *id = NULL;
6078 if (sigint_received || sigpipe_received)
6079 break;
6081 te = got_object_tree_get_entry(tree, i);
6082 if (show_ids) {
6083 char *id_str;
6084 err = got_object_id_str(&id_str,
6085 got_tree_entry_get_id(te));
6086 if (err)
6087 goto done;
6088 if (asprintf(&id, "%s ", id_str) == -1) {
6089 err = got_error_from_errno("asprintf");
6090 free(id_str);
6091 goto done;
6093 free(id_str);
6095 err = print_entry(te, id, path, root_path, repo);
6096 free(id);
6097 if (err)
6098 goto done;
6100 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6101 char *child_path;
6102 if (asprintf(&child_path, "%s%s%s", path,
6103 path[0] == '/' && path[1] == '\0' ? "" : "/",
6104 got_tree_entry_get_name(te)) == -1) {
6105 err = got_error_from_errno("asprintf");
6106 goto done;
6108 err = print_tree(child_path, commit, show_ids, 1,
6109 root_path, repo);
6110 free(child_path);
6111 if (err)
6112 goto done;
6115 done:
6116 if (tree)
6117 got_object_tree_close(tree);
6118 free(tree_id);
6119 return err;
6122 static const struct got_error *
6123 cmd_tree(int argc, char *argv[])
6125 const struct got_error *error;
6126 struct got_repository *repo = NULL;
6127 struct got_worktree *worktree = NULL;
6128 const char *path, *refname = NULL;
6129 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6130 struct got_object_id *commit_id = NULL;
6131 struct got_commit_object *commit = NULL;
6132 char *commit_id_str = NULL, *keyword_idstr = NULL;
6133 int show_ids = 0, recurse = 0;
6134 int ch;
6135 int *pack_fds = NULL;
6137 #ifndef PROFILE
6138 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6139 NULL) == -1)
6140 err(1, "pledge");
6141 #endif
6143 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6144 switch (ch) {
6145 case 'c':
6146 commit_id_str = optarg;
6147 break;
6148 case 'i':
6149 show_ids = 1;
6150 break;
6151 case 'R':
6152 recurse = 1;
6153 break;
6154 case 'r':
6155 repo_path = realpath(optarg, NULL);
6156 if (repo_path == NULL)
6157 return got_error_from_errno2("realpath",
6158 optarg);
6159 got_path_strip_trailing_slashes(repo_path);
6160 break;
6161 default:
6162 usage_tree();
6163 /* NOTREACHED */
6167 argc -= optind;
6168 argv += optind;
6170 if (argc == 1)
6171 path = argv[0];
6172 else if (argc > 1)
6173 usage_tree();
6174 else
6175 path = NULL;
6177 cwd = getcwd(NULL, 0);
6178 if (cwd == NULL) {
6179 error = got_error_from_errno("getcwd");
6180 goto done;
6183 error = got_repo_pack_fds_open(&pack_fds);
6184 if (error != NULL)
6185 goto done;
6187 if (repo_path == NULL) {
6188 error = got_worktree_open(&worktree, cwd,
6189 GOT_WORKTREE_GOT_DIR);
6190 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6191 goto done;
6192 else
6193 error = NULL;
6194 if (worktree) {
6195 repo_path =
6196 strdup(got_worktree_get_repo_path(worktree));
6197 if (repo_path == NULL)
6198 error = got_error_from_errno("strdup");
6199 if (error)
6200 goto done;
6201 } else {
6202 repo_path = strdup(cwd);
6203 if (repo_path == NULL) {
6204 error = got_error_from_errno("strdup");
6205 goto done;
6210 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6211 if (error != NULL)
6212 goto done;
6214 if (worktree) {
6215 const char *prefix = got_worktree_get_path_prefix(worktree);
6216 char *p;
6218 if (path == NULL || got_path_is_root_dir(path))
6219 path = "";
6220 error = got_worktree_resolve_path(&p, worktree, path);
6221 if (error)
6222 goto done;
6223 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6224 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6225 p) == -1) {
6226 error = got_error_from_errno("asprintf");
6227 free(p);
6228 goto done;
6230 free(p);
6231 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6232 if (error)
6233 goto done;
6234 } else {
6235 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6236 if (error)
6237 goto done;
6238 if (path == NULL)
6239 path = "/";
6240 error = got_repo_map_path(&in_repo_path, repo, path);
6241 if (error != NULL)
6242 goto done;
6245 if (commit_id_str == NULL) {
6246 struct got_reference *head_ref;
6247 if (worktree)
6248 refname = got_worktree_get_head_ref_name(worktree);
6249 else
6250 refname = GOT_REF_HEAD;
6251 error = got_ref_open(&head_ref, repo, refname, 0);
6252 if (error != NULL)
6253 goto done;
6254 error = got_ref_resolve(&commit_id, repo, head_ref);
6255 got_ref_close(head_ref);
6256 if (error != NULL)
6257 goto done;
6258 } else {
6259 struct got_reflist_head refs;
6261 TAILQ_INIT(&refs);
6262 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6263 NULL);
6264 if (error)
6265 goto done;
6267 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6268 repo, worktree);
6269 if (error != NULL)
6270 goto done;
6271 if (keyword_idstr != NULL)
6272 commit_id_str = keyword_idstr;
6274 error = got_repo_match_object_id(&commit_id, NULL,
6275 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6276 got_ref_list_free(&refs);
6277 if (error)
6278 goto done;
6281 if (worktree) {
6282 /* Release work tree lock. */
6283 got_worktree_close(worktree);
6284 worktree = NULL;
6287 error = got_object_open_as_commit(&commit, repo, commit_id);
6288 if (error)
6289 goto done;
6291 error = print_tree(in_repo_path, commit, show_ids, recurse,
6292 in_repo_path, repo);
6293 done:
6294 free(keyword_idstr);
6295 free(in_repo_path);
6296 free(repo_path);
6297 free(cwd);
6298 free(commit_id);
6299 if (commit)
6300 got_object_commit_close(commit);
6301 if (worktree)
6302 got_worktree_close(worktree);
6303 if (repo) {
6304 const struct got_error *close_err = got_repo_close(repo);
6305 if (error == NULL)
6306 error = close_err;
6308 if (pack_fds) {
6309 const struct got_error *pack_err =
6310 got_repo_pack_fds_close(pack_fds);
6311 if (error == NULL)
6312 error = pack_err;
6314 return error;
6317 __dead static void
6318 usage_status(void)
6320 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6321 "[-s status-codes] [path ...]\n", getprogname());
6322 exit(1);
6325 struct got_status_arg {
6326 char *status_codes;
6327 int suppress;
6330 static const struct got_error *
6331 print_status(void *arg, unsigned char status, unsigned char staged_status,
6332 const char *path, struct got_object_id *blob_id,
6333 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6334 int dirfd, const char *de_name)
6336 struct got_status_arg *st = arg;
6338 if (status == staged_status && (status == GOT_STATUS_DELETE))
6339 status = GOT_STATUS_NO_CHANGE;
6340 if (st != NULL && st->status_codes) {
6341 size_t ncodes = strlen(st->status_codes);
6342 int i, j = 0;
6344 for (i = 0; i < ncodes ; i++) {
6345 if (st->suppress) {
6346 if (status == st->status_codes[i] ||
6347 staged_status == st->status_codes[i]) {
6348 j++;
6349 continue;
6351 } else {
6352 if (status == st->status_codes[i] ||
6353 staged_status == st->status_codes[i])
6354 break;
6358 if (st->suppress && j == 0)
6359 goto print;
6361 if (i == ncodes)
6362 return NULL;
6364 print:
6365 printf("%c%c %s\n", status, staged_status, path);
6366 return NULL;
6369 static const struct got_error *
6370 cmd_status(int argc, char *argv[])
6372 const struct got_error *error = NULL;
6373 struct got_repository *repo = NULL;
6374 struct got_worktree *worktree = NULL;
6375 struct got_status_arg st;
6376 char *cwd = NULL;
6377 struct got_pathlist_head paths;
6378 int ch, i, no_ignores = 0;
6379 int *pack_fds = NULL;
6381 TAILQ_INIT(&paths);
6383 memset(&st, 0, sizeof(st));
6384 st.status_codes = NULL;
6385 st.suppress = 0;
6387 #ifndef PROFILE
6388 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6389 NULL) == -1)
6390 err(1, "pledge");
6391 #endif
6393 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6394 switch (ch) {
6395 case 'I':
6396 no_ignores = 1;
6397 break;
6398 case 'S':
6399 if (st.status_codes != NULL && st.suppress == 0)
6400 option_conflict('S', 's');
6401 st.suppress = 1;
6402 /* fallthrough */
6403 case 's':
6404 for (i = 0; optarg[i] != '\0'; i++) {
6405 switch (optarg[i]) {
6406 case GOT_STATUS_MODIFY:
6407 case GOT_STATUS_ADD:
6408 case GOT_STATUS_DELETE:
6409 case GOT_STATUS_CONFLICT:
6410 case GOT_STATUS_MISSING:
6411 case GOT_STATUS_OBSTRUCTED:
6412 case GOT_STATUS_UNVERSIONED:
6413 case GOT_STATUS_MODE_CHANGE:
6414 case GOT_STATUS_NONEXISTENT:
6415 break;
6416 default:
6417 errx(1, "invalid status code '%c'",
6418 optarg[i]);
6421 if (ch == 's' && st.suppress)
6422 option_conflict('s', 'S');
6423 st.status_codes = optarg;
6424 break;
6425 default:
6426 usage_status();
6427 /* NOTREACHED */
6431 argc -= optind;
6432 argv += optind;
6434 cwd = getcwd(NULL, 0);
6435 if (cwd == NULL) {
6436 error = got_error_from_errno("getcwd");
6437 goto done;
6440 error = got_repo_pack_fds_open(&pack_fds);
6441 if (error != NULL)
6442 goto done;
6444 error = got_worktree_open(&worktree, cwd,
6445 GOT_WORKTREE_GOT_DIR);
6446 if (error) {
6447 if (error->code == GOT_ERR_NOT_WORKTREE)
6448 error = wrap_not_worktree_error(error, "status", cwd);
6449 goto done;
6452 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6453 NULL, pack_fds);
6454 if (error != NULL)
6455 goto done;
6457 error = apply_unveil(got_repo_get_path(repo), 1,
6458 got_worktree_get_root_path(worktree));
6459 if (error)
6460 goto done;
6462 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6463 if (error)
6464 goto done;
6466 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6467 print_status, &st, check_cancelled, NULL);
6468 done:
6469 if (pack_fds) {
6470 const struct got_error *pack_err =
6471 got_repo_pack_fds_close(pack_fds);
6472 if (error == NULL)
6473 error = pack_err;
6475 if (repo) {
6476 const struct got_error *close_err = got_repo_close(repo);
6477 if (error == NULL)
6478 error = close_err;
6481 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6482 free(cwd);
6483 return error;
6486 __dead static void
6487 usage_ref(void)
6489 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6490 "[-s reference] [name]\n", getprogname());
6491 exit(1);
6494 static const struct got_error *
6495 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6497 static const struct got_error *err = NULL;
6498 struct got_reflist_head refs;
6499 struct got_reflist_entry *re;
6501 TAILQ_INIT(&refs);
6502 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6503 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6504 repo);
6505 if (err)
6506 return err;
6508 TAILQ_FOREACH(re, &refs, entry) {
6509 char *refstr;
6510 refstr = got_ref_to_str(re->ref);
6511 if (refstr == NULL) {
6512 err = got_error_from_errno("got_ref_to_str");
6513 break;
6515 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6516 free(refstr);
6519 got_ref_list_free(&refs);
6520 return err;
6523 static const struct got_error *
6524 delete_ref_by_name(struct got_repository *repo, const char *refname)
6526 const struct got_error *err;
6527 struct got_reference *ref;
6529 err = got_ref_open(&ref, repo, refname, 0);
6530 if (err)
6531 return err;
6533 err = delete_ref(repo, ref);
6534 got_ref_close(ref);
6535 return err;
6538 static const struct got_error *
6539 add_ref(struct got_repository *repo, const char *refname, const char *target)
6541 const struct got_error *err = NULL;
6542 struct got_object_id *id = NULL;
6543 struct got_reference *ref = NULL;
6544 struct got_reflist_head refs;
6547 * Don't let the user create a reference name with a leading '-'.
6548 * While technically a valid reference name, this case is usually
6549 * an unintended typo.
6551 if (refname[0] == '-')
6552 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6554 TAILQ_INIT(&refs);
6555 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6556 if (err)
6557 goto done;
6558 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6559 &refs, repo);
6560 got_ref_list_free(&refs);
6561 if (err)
6562 goto done;
6564 err = got_ref_alloc(&ref, refname, id);
6565 if (err)
6566 goto done;
6568 err = got_ref_write(ref, repo);
6569 done:
6570 if (ref)
6571 got_ref_close(ref);
6572 free(id);
6573 return err;
6576 static const struct got_error *
6577 add_symref(struct got_repository *repo, const char *refname, const char *target)
6579 const struct got_error *err = NULL;
6580 struct got_reference *ref = NULL;
6581 struct got_reference *target_ref = NULL;
6584 * Don't let the user create a reference name with a leading '-'.
6585 * While technically a valid reference name, this case is usually
6586 * an unintended typo.
6588 if (refname[0] == '-')
6589 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6591 err = got_ref_open(&target_ref, repo, target, 0);
6592 if (err)
6593 return err;
6595 err = got_ref_alloc_symref(&ref, refname, target_ref);
6596 if (err)
6597 goto done;
6599 err = got_ref_write(ref, repo);
6600 done:
6601 if (target_ref)
6602 got_ref_close(target_ref);
6603 if (ref)
6604 got_ref_close(ref);
6605 return err;
6608 static const struct got_error *
6609 cmd_ref(int argc, char *argv[])
6611 const struct got_error *error = NULL;
6612 struct got_repository *repo = NULL;
6613 struct got_worktree *worktree = NULL;
6614 char *cwd = NULL, *repo_path = NULL;
6615 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6616 const char *obj_arg = NULL, *symref_target= NULL;
6617 char *refname = NULL, *keyword_idstr = NULL;
6618 int *pack_fds = NULL;
6620 #ifndef PROFILE
6621 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6622 "sendfd unveil", NULL) == -1)
6623 err(1, "pledge");
6624 #endif
6626 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6627 switch (ch) {
6628 case 'c':
6629 obj_arg = optarg;
6630 break;
6631 case 'd':
6632 do_delete = 1;
6633 break;
6634 case 'l':
6635 do_list = 1;
6636 break;
6637 case 'r':
6638 repo_path = realpath(optarg, NULL);
6639 if (repo_path == NULL)
6640 return got_error_from_errno2("realpath",
6641 optarg);
6642 got_path_strip_trailing_slashes(repo_path);
6643 break;
6644 case 's':
6645 symref_target = optarg;
6646 break;
6647 case 't':
6648 sort_by_time = 1;
6649 break;
6650 default:
6651 usage_ref();
6652 /* NOTREACHED */
6656 if (obj_arg && do_list)
6657 option_conflict('c', 'l');
6658 if (obj_arg && do_delete)
6659 option_conflict('c', 'd');
6660 if (obj_arg && symref_target)
6661 option_conflict('c', 's');
6662 if (symref_target && do_delete)
6663 option_conflict('s', 'd');
6664 if (symref_target && do_list)
6665 option_conflict('s', 'l');
6666 if (do_delete && do_list)
6667 option_conflict('d', 'l');
6668 if (sort_by_time && !do_list)
6669 errx(1, "-t option requires -l option");
6671 argc -= optind;
6672 argv += optind;
6674 if (do_list) {
6675 if (argc != 0 && argc != 1)
6676 usage_ref();
6677 if (argc == 1) {
6678 refname = strdup(argv[0]);
6679 if (refname == NULL) {
6680 error = got_error_from_errno("strdup");
6681 goto done;
6684 } else {
6685 if (argc != 1)
6686 usage_ref();
6687 refname = strdup(argv[0]);
6688 if (refname == NULL) {
6689 error = got_error_from_errno("strdup");
6690 goto done;
6694 if (refname)
6695 got_path_strip_trailing_slashes(refname);
6697 cwd = getcwd(NULL, 0);
6698 if (cwd == NULL) {
6699 error = got_error_from_errno("getcwd");
6700 goto done;
6703 error = got_repo_pack_fds_open(&pack_fds);
6704 if (error != NULL)
6705 goto done;
6707 if (repo_path == NULL) {
6708 error = got_worktree_open(&worktree, cwd,
6709 GOT_WORKTREE_GOT_DIR);
6710 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6711 goto done;
6712 else
6713 error = NULL;
6714 if (worktree) {
6715 repo_path =
6716 strdup(got_worktree_get_repo_path(worktree));
6717 if (repo_path == NULL)
6718 error = got_error_from_errno("strdup");
6719 if (error)
6720 goto done;
6721 } else {
6722 repo_path = strdup(cwd);
6723 if (repo_path == NULL) {
6724 error = got_error_from_errno("strdup");
6725 goto done;
6730 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6731 if (error != NULL)
6732 goto done;
6734 #ifndef PROFILE
6735 if (do_list) {
6736 /* Remove "cpath" promise. */
6737 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6738 NULL) == -1)
6739 err(1, "pledge");
6741 #endif
6743 error = apply_unveil(got_repo_get_path(repo), do_list,
6744 worktree ? got_worktree_get_root_path(worktree) : NULL);
6745 if (error)
6746 goto done;
6748 if (do_list)
6749 error = list_refs(repo, refname, sort_by_time);
6750 else if (do_delete)
6751 error = delete_ref_by_name(repo, refname);
6752 else if (symref_target)
6753 error = add_symref(repo, refname, symref_target);
6754 else {
6755 if (obj_arg == NULL)
6756 usage_ref();
6758 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6759 repo, worktree);
6760 if (error != NULL)
6761 goto done;
6762 if (keyword_idstr != NULL)
6763 obj_arg = keyword_idstr;
6765 error = add_ref(repo, refname, obj_arg);
6767 done:
6768 free(refname);
6769 if (repo) {
6770 const struct got_error *close_err = got_repo_close(repo);
6771 if (error == NULL)
6772 error = close_err;
6774 if (worktree)
6775 got_worktree_close(worktree);
6776 if (pack_fds) {
6777 const struct got_error *pack_err =
6778 got_repo_pack_fds_close(pack_fds);
6779 if (error == NULL)
6780 error = pack_err;
6782 free(cwd);
6783 free(repo_path);
6784 free(keyword_idstr);
6785 return error;
6788 __dead static void
6789 usage_branch(void)
6791 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6792 "[-r repository-path] [name]\n", getprogname());
6793 exit(1);
6796 static const struct got_error *
6797 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6798 struct got_reference *ref)
6800 const struct got_error *err = NULL;
6801 const char *refname;
6802 char *refstr;
6803 char marker = ' ';
6805 refname = got_ref_get_name(ref);
6806 if (worktree && strcmp(refname,
6807 got_worktree_get_head_ref_name(worktree)) == 0) {
6808 err = got_worktree_get_state(&marker, repo, worktree);
6809 if (err != NULL)
6810 return err;
6813 if (strncmp(refname, "refs/heads/", 11) == 0)
6814 refname += 11;
6815 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6816 refname += 18;
6817 if (strncmp(refname, "refs/remotes/", 13) == 0)
6818 refname += 13;
6820 refstr = got_ref_to_str(ref);
6821 if (refstr == NULL)
6822 return got_error_from_errno("got_ref_to_str");
6824 printf("%c %s: %s\n", marker, refname, refstr);
6825 free(refstr);
6826 return NULL;
6829 static const struct got_error *
6830 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6832 const char *refname;
6834 if (worktree == NULL)
6835 return got_error(GOT_ERR_NOT_WORKTREE);
6837 refname = got_worktree_get_head_ref_name(worktree);
6839 if (strncmp(refname, "refs/heads/", 11) == 0)
6840 refname += 11;
6841 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6842 refname += 18;
6844 printf("%s\n", refname);
6846 return NULL;
6849 static const struct got_error *
6850 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6851 int sort_by_time)
6853 static const struct got_error *err = NULL;
6854 struct got_reflist_head refs;
6855 struct got_reflist_entry *re;
6856 struct got_reference *temp_ref = NULL;
6857 int rebase_in_progress, histedit_in_progress;
6859 TAILQ_INIT(&refs);
6861 if (worktree) {
6862 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6863 worktree);
6864 if (err)
6865 return err;
6867 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6868 worktree);
6869 if (err)
6870 return err;
6872 if (rebase_in_progress || histedit_in_progress) {
6873 err = got_ref_open(&temp_ref, repo,
6874 got_worktree_get_head_ref_name(worktree), 0);
6875 if (err)
6876 return err;
6877 list_branch(repo, worktree, temp_ref);
6878 got_ref_close(temp_ref);
6882 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6883 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6884 repo);
6885 if (err)
6886 return err;
6888 TAILQ_FOREACH(re, &refs, entry)
6889 list_branch(repo, worktree, re->ref);
6891 got_ref_list_free(&refs);
6893 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6894 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6895 repo);
6896 if (err)
6897 return err;
6899 TAILQ_FOREACH(re, &refs, entry)
6900 list_branch(repo, worktree, re->ref);
6902 got_ref_list_free(&refs);
6904 return NULL;
6907 static const struct got_error *
6908 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6909 const char *branch_name)
6911 const struct got_error *err = NULL;
6912 struct got_reference *ref = NULL;
6913 char *refname, *remote_refname = NULL;
6915 if (strncmp(branch_name, "refs/", 5) == 0)
6916 branch_name += 5;
6917 if (strncmp(branch_name, "heads/", 6) == 0)
6918 branch_name += 6;
6919 else if (strncmp(branch_name, "remotes/", 8) == 0)
6920 branch_name += 8;
6922 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6923 return got_error_from_errno("asprintf");
6925 if (asprintf(&remote_refname, "refs/remotes/%s",
6926 branch_name) == -1) {
6927 err = got_error_from_errno("asprintf");
6928 goto done;
6931 err = got_ref_open(&ref, repo, refname, 0);
6932 if (err) {
6933 const struct got_error *err2;
6934 if (err->code != GOT_ERR_NOT_REF)
6935 goto done;
6937 * Keep 'err' intact such that if neither branch exists
6938 * we report "refs/heads" rather than "refs/remotes" in
6939 * our error message.
6941 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6942 if (err2)
6943 goto done;
6944 err = NULL;
6947 if (worktree &&
6948 strcmp(got_worktree_get_head_ref_name(worktree),
6949 got_ref_get_name(ref)) == 0) {
6950 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6951 "will not delete this work tree's current branch");
6952 goto done;
6955 err = delete_ref(repo, ref);
6956 done:
6957 if (ref)
6958 got_ref_close(ref);
6959 free(refname);
6960 free(remote_refname);
6961 return err;
6964 static const struct got_error *
6965 add_branch(struct got_repository *repo, const char *branch_name,
6966 struct got_object_id *base_commit_id)
6968 const struct got_error *err = NULL;
6969 struct got_reference *ref = NULL;
6970 char *refname = NULL;
6973 * Don't let the user create a branch name with a leading '-'.
6974 * While technically a valid reference name, this case is usually
6975 * an unintended typo.
6977 if (branch_name[0] == '-')
6978 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6980 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6981 branch_name += 11;
6983 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6984 err = got_error_from_errno("asprintf");
6985 goto done;
6988 err = got_ref_open(&ref, repo, refname, 0);
6989 if (err == NULL) {
6990 err = got_error(GOT_ERR_BRANCH_EXISTS);
6991 goto done;
6992 } else if (err->code != GOT_ERR_NOT_REF)
6993 goto done;
6995 err = got_ref_alloc(&ref, refname, base_commit_id);
6996 if (err)
6997 goto done;
6999 err = got_ref_write(ref, repo);
7000 done:
7001 if (ref)
7002 got_ref_close(ref);
7003 free(refname);
7004 return err;
7007 static const struct got_error *
7008 cmd_branch(int argc, char *argv[])
7010 const struct got_error *error = NULL;
7011 struct got_repository *repo = NULL;
7012 struct got_worktree *worktree = NULL;
7013 char *cwd = NULL, *repo_path = NULL;
7014 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7015 const char *delref = NULL, *commit_id_arg = NULL;
7016 struct got_reference *ref = NULL;
7017 struct got_pathlist_head paths;
7018 struct got_object_id *commit_id = NULL;
7019 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7020 int *pack_fds = NULL;
7022 TAILQ_INIT(&paths);
7024 #ifndef PROFILE
7025 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7026 "sendfd unveil", NULL) == -1)
7027 err(1, "pledge");
7028 #endif
7030 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7031 switch (ch) {
7032 case 'c':
7033 commit_id_arg = optarg;
7034 break;
7035 case 'd':
7036 delref = optarg;
7037 break;
7038 case 'l':
7039 do_list = 1;
7040 break;
7041 case 'n':
7042 do_update = 0;
7043 break;
7044 case 'r':
7045 repo_path = realpath(optarg, NULL);
7046 if (repo_path == NULL)
7047 return got_error_from_errno2("realpath",
7048 optarg);
7049 got_path_strip_trailing_slashes(repo_path);
7050 break;
7051 case 't':
7052 sort_by_time = 1;
7053 break;
7054 default:
7055 usage_branch();
7056 /* NOTREACHED */
7060 if (do_list && delref)
7061 option_conflict('l', 'd');
7062 if (sort_by_time && !do_list)
7063 errx(1, "-t option requires -l option");
7065 argc -= optind;
7066 argv += optind;
7068 if (!do_list && !delref && argc == 0)
7069 do_show = 1;
7071 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7072 errx(1, "-c option can only be used when creating a branch");
7074 if (do_list || delref) {
7075 if (argc > 0)
7076 usage_branch();
7077 } else if (!do_show && argc != 1)
7078 usage_branch();
7080 cwd = getcwd(NULL, 0);
7081 if (cwd == NULL) {
7082 error = got_error_from_errno("getcwd");
7083 goto done;
7086 error = got_repo_pack_fds_open(&pack_fds);
7087 if (error != NULL)
7088 goto done;
7090 if (repo_path == NULL) {
7091 error = got_worktree_open(&worktree, cwd,
7092 GOT_WORKTREE_GOT_DIR);
7093 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7094 goto done;
7095 else
7096 error = NULL;
7097 if (worktree) {
7098 repo_path =
7099 strdup(got_worktree_get_repo_path(worktree));
7100 if (repo_path == NULL)
7101 error = got_error_from_errno("strdup");
7102 if (error)
7103 goto done;
7104 } else {
7105 repo_path = strdup(cwd);
7106 if (repo_path == NULL) {
7107 error = got_error_from_errno("strdup");
7108 goto done;
7113 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7114 if (error != NULL)
7115 goto done;
7117 #ifndef PROFILE
7118 if (do_list || do_show) {
7119 /* Remove "cpath" promise. */
7120 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7121 NULL) == -1)
7122 err(1, "pledge");
7124 #endif
7126 error = apply_unveil(got_repo_get_path(repo), do_list,
7127 worktree ? got_worktree_get_root_path(worktree) : NULL);
7128 if (error)
7129 goto done;
7131 if (do_show)
7132 error = show_current_branch(repo, worktree);
7133 else if (do_list)
7134 error = list_branches(repo, worktree, sort_by_time);
7135 else if (delref)
7136 error = delete_branch(repo, worktree, delref);
7137 else {
7138 struct got_reflist_head refs;
7139 TAILQ_INIT(&refs);
7140 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7141 NULL);
7142 if (error)
7143 goto done;
7144 if (commit_id_arg == NULL)
7145 commit_id_arg = worktree ?
7146 got_worktree_get_head_ref_name(worktree) :
7147 GOT_REF_HEAD;
7148 else {
7149 error = got_keyword_to_idstr(&keyword_idstr,
7150 commit_id_arg, repo, worktree);
7151 if (error != NULL)
7152 goto done;
7153 if (keyword_idstr != NULL)
7154 commit_id_arg = keyword_idstr;
7156 error = got_repo_match_object_id(&commit_id, NULL,
7157 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7158 got_ref_list_free(&refs);
7159 if (error)
7160 goto done;
7161 error = add_branch(repo, argv[0], commit_id);
7162 if (error)
7163 goto done;
7164 if (worktree && do_update) {
7165 struct got_update_progress_arg upa;
7166 char *branch_refname = NULL;
7168 error = got_object_id_str(&commit_id_str, commit_id);
7169 if (error)
7170 goto done;
7171 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7172 worktree);
7173 if (error)
7174 goto done;
7175 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7176 == -1) {
7177 error = got_error_from_errno("asprintf");
7178 goto done;
7180 error = got_ref_open(&ref, repo, branch_refname, 0);
7181 free(branch_refname);
7182 if (error)
7183 goto done;
7184 error = switch_head_ref(ref, commit_id, worktree,
7185 repo);
7186 if (error)
7187 goto done;
7188 error = got_worktree_set_base_commit_id(worktree, repo,
7189 commit_id);
7190 if (error)
7191 goto done;
7192 memset(&upa, 0, sizeof(upa));
7193 error = got_worktree_checkout_files(worktree, &paths,
7194 repo, update_progress, &upa, check_cancelled,
7195 NULL);
7196 if (error)
7197 goto done;
7198 if (upa.did_something) {
7199 printf("Updated to %s: %s\n",
7200 got_worktree_get_head_ref_name(worktree),
7201 commit_id_str);
7203 print_update_progress_stats(&upa);
7206 done:
7207 free(keyword_idstr);
7208 if (ref)
7209 got_ref_close(ref);
7210 if (repo) {
7211 const struct got_error *close_err = got_repo_close(repo);
7212 if (error == NULL)
7213 error = close_err;
7215 if (worktree)
7216 got_worktree_close(worktree);
7217 if (pack_fds) {
7218 const struct got_error *pack_err =
7219 got_repo_pack_fds_close(pack_fds);
7220 if (error == NULL)
7221 error = pack_err;
7223 free(cwd);
7224 free(repo_path);
7225 free(commit_id);
7226 free(commit_id_str);
7227 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7228 return error;
7232 __dead static void
7233 usage_tag(void)
7235 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7236 "[-r repository-path] [-s signer-id] name\n", getprogname());
7237 exit(1);
7240 #if 0
7241 static const struct got_error *
7242 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7244 const struct got_error *err = NULL;
7245 struct got_reflist_entry *re, *se, *new;
7246 struct got_object_id *re_id, *se_id;
7247 struct got_tag_object *re_tag, *se_tag;
7248 time_t re_time, se_time;
7250 STAILQ_FOREACH(re, tags, entry) {
7251 se = STAILQ_FIRST(sorted);
7252 if (se == NULL) {
7253 err = got_reflist_entry_dup(&new, re);
7254 if (err)
7255 return err;
7256 STAILQ_INSERT_HEAD(sorted, new, entry);
7257 continue;
7258 } else {
7259 err = got_ref_resolve(&re_id, repo, re->ref);
7260 if (err)
7261 break;
7262 err = got_object_open_as_tag(&re_tag, repo, re_id);
7263 free(re_id);
7264 if (err)
7265 break;
7266 re_time = got_object_tag_get_tagger_time(re_tag);
7267 got_object_tag_close(re_tag);
7270 while (se) {
7271 err = got_ref_resolve(&se_id, repo, re->ref);
7272 if (err)
7273 break;
7274 err = got_object_open_as_tag(&se_tag, repo, se_id);
7275 free(se_id);
7276 if (err)
7277 break;
7278 se_time = got_object_tag_get_tagger_time(se_tag);
7279 got_object_tag_close(se_tag);
7281 if (se_time > re_time) {
7282 err = got_reflist_entry_dup(&new, re);
7283 if (err)
7284 return err;
7285 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7286 break;
7288 se = STAILQ_NEXT(se, entry);
7289 continue;
7292 done:
7293 return err;
7295 #endif
7297 static const struct got_error *
7298 get_tag_refname(char **refname, const char *tag_name)
7300 const struct got_error *err;
7302 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7303 *refname = strdup(tag_name);
7304 if (*refname == NULL)
7305 return got_error_from_errno("strdup");
7306 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7307 err = got_error_from_errno("asprintf");
7308 *refname = NULL;
7309 return err;
7312 return NULL;
7315 static const struct got_error *
7316 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7317 const char *allowed_signers, const char *revoked_signers, int verbosity)
7319 static const struct got_error *err = NULL;
7320 struct got_reflist_head refs;
7321 struct got_reflist_entry *re;
7322 char *wanted_refname = NULL;
7323 int bad_sigs = 0;
7325 TAILQ_INIT(&refs);
7327 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7328 if (err)
7329 return err;
7331 if (tag_name) {
7332 struct got_reference *ref;
7333 err = get_tag_refname(&wanted_refname, tag_name);
7334 if (err)
7335 goto done;
7336 /* Wanted tag reference should exist. */
7337 err = got_ref_open(&ref, repo, wanted_refname, 0);
7338 if (err)
7339 goto done;
7340 got_ref_close(ref);
7343 TAILQ_FOREACH(re, &refs, entry) {
7344 const char *refname;
7345 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7346 char datebuf[26];
7347 const char *tagger, *ssh_sig = NULL;
7348 char *sig_msg = NULL;
7349 time_t tagger_time;
7350 struct got_object_id *id;
7351 struct got_tag_object *tag;
7352 struct got_commit_object *commit = NULL;
7354 refname = got_ref_get_name(re->ref);
7355 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7356 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7357 continue;
7358 refname += 10;
7359 refstr = got_ref_to_str(re->ref);
7360 if (refstr == NULL) {
7361 err = got_error_from_errno("got_ref_to_str");
7362 break;
7365 err = got_ref_resolve(&id, repo, re->ref);
7366 if (err)
7367 break;
7368 err = got_object_open_as_tag(&tag, repo, id);
7369 if (err) {
7370 if (err->code != GOT_ERR_OBJ_TYPE) {
7371 free(id);
7372 break;
7374 /* "lightweight" tag */
7375 err = got_object_open_as_commit(&commit, repo, id);
7376 if (err) {
7377 free(id);
7378 break;
7380 tagger = got_object_commit_get_committer(commit);
7381 tagger_time =
7382 got_object_commit_get_committer_time(commit);
7383 err = got_object_id_str(&id_str, id);
7384 free(id);
7385 if (err)
7386 break;
7387 } else {
7388 free(id);
7389 tagger = got_object_tag_get_tagger(tag);
7390 tagger_time = got_object_tag_get_tagger_time(tag);
7391 err = got_object_id_str(&id_str,
7392 got_object_tag_get_object_id(tag));
7393 if (err)
7394 break;
7397 if (tag && verify_tags) {
7398 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7399 got_object_tag_get_message(tag));
7400 if (ssh_sig && allowed_signers == NULL) {
7401 err = got_error_msg(
7402 GOT_ERR_VERIFY_TAG_SIGNATURE,
7403 "SSH signature verification requires "
7404 "setting allowed_signers in "
7405 "got.conf(5)");
7406 break;
7410 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7411 free(refstr);
7412 printf("from: %s\n", tagger);
7413 datestr = get_datestr(&tagger_time, datebuf);
7414 if (datestr)
7415 printf("date: %s UTC\n", datestr);
7416 if (commit)
7417 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7418 else {
7419 switch (got_object_tag_get_object_type(tag)) {
7420 case GOT_OBJ_TYPE_BLOB:
7421 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7422 id_str);
7423 break;
7424 case GOT_OBJ_TYPE_TREE:
7425 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7426 id_str);
7427 break;
7428 case GOT_OBJ_TYPE_COMMIT:
7429 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7430 id_str);
7431 break;
7432 case GOT_OBJ_TYPE_TAG:
7433 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7434 id_str);
7435 break;
7436 default:
7437 break;
7440 free(id_str);
7442 if (ssh_sig) {
7443 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7444 allowed_signers, revoked_signers, verbosity);
7445 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7446 bad_sigs = 1;
7447 else if (err)
7448 break;
7449 printf("signature: %s", sig_msg);
7450 free(sig_msg);
7451 sig_msg = NULL;
7454 if (commit) {
7455 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7456 if (err)
7457 break;
7458 got_object_commit_close(commit);
7459 } else {
7460 tagmsg0 = strdup(got_object_tag_get_message(tag));
7461 got_object_tag_close(tag);
7462 if (tagmsg0 == NULL) {
7463 err = got_error_from_errno("strdup");
7464 break;
7468 tagmsg = tagmsg0;
7469 do {
7470 line = strsep(&tagmsg, "\n");
7471 if (line)
7472 printf(" %s\n", line);
7473 } while (line);
7474 free(tagmsg0);
7476 done:
7477 got_ref_list_free(&refs);
7478 free(wanted_refname);
7480 if (err == NULL && bad_sigs)
7481 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7482 return err;
7485 static const struct got_error *
7486 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7487 const char *tag_name, const char *repo_path)
7489 const struct got_error *err = NULL;
7490 char *template = NULL, *initial_content = NULL;
7491 char *editor = NULL;
7492 int initial_content_len;
7493 int fd = -1;
7495 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7496 err = got_error_from_errno("asprintf");
7497 goto done;
7500 initial_content_len = asprintf(&initial_content,
7501 "\n# tagging commit %s as %s\n",
7502 commit_id_str, tag_name);
7503 if (initial_content_len == -1) {
7504 err = got_error_from_errno("asprintf");
7505 goto done;
7508 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7509 if (err)
7510 goto done;
7512 if (write(fd, initial_content, initial_content_len) == -1) {
7513 err = got_error_from_errno2("write", *tagmsg_path);
7514 goto done;
7516 if (close(fd) == -1) {
7517 err = got_error_from_errno2("close", *tagmsg_path);
7518 goto done;
7520 fd = -1;
7522 err = get_editor(&editor);
7523 if (err)
7524 goto done;
7525 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7526 initial_content_len, 1);
7527 done:
7528 free(initial_content);
7529 free(template);
7530 free(editor);
7532 if (fd != -1 && close(fd) == -1 && err == NULL)
7533 err = got_error_from_errno2("close", *tagmsg_path);
7535 if (err) {
7536 free(*tagmsg);
7537 *tagmsg = NULL;
7539 return err;
7542 static const struct got_error *
7543 add_tag(struct got_repository *repo, const char *tagger,
7544 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7545 const char *signer_id, int verbosity)
7547 const struct got_error *err = NULL;
7548 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7549 char *label = NULL, *commit_id_str = NULL;
7550 struct got_reference *ref = NULL;
7551 char *refname = NULL, *tagmsg = NULL;
7552 char *tagmsg_path = NULL, *tag_id_str = NULL;
7553 int preserve_tagmsg = 0;
7554 struct got_reflist_head refs;
7556 TAILQ_INIT(&refs);
7559 * Don't let the user create a tag name with a leading '-'.
7560 * While technically a valid reference name, this case is usually
7561 * an unintended typo.
7563 if (tag_name[0] == '-')
7564 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7566 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7567 if (err)
7568 goto done;
7570 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7571 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7572 if (err)
7573 goto done;
7575 err = got_object_id_str(&commit_id_str, commit_id);
7576 if (err)
7577 goto done;
7579 err = get_tag_refname(&refname, tag_name);
7580 if (err)
7581 goto done;
7582 if (strncmp("refs/tags/", tag_name, 10) == 0)
7583 tag_name += 10;
7585 err = got_ref_open(&ref, repo, refname, 0);
7586 if (err == NULL) {
7587 err = got_error(GOT_ERR_TAG_EXISTS);
7588 goto done;
7589 } else if (err->code != GOT_ERR_NOT_REF)
7590 goto done;
7592 if (tagmsg_arg == NULL) {
7593 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7594 tag_name, got_repo_get_path(repo));
7595 if (err) {
7596 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7597 tagmsg_path != NULL)
7598 preserve_tagmsg = 1;
7599 goto done;
7601 /* Editor is done; we can now apply unveil(2) */
7602 err = got_sigs_apply_unveil();
7603 if (err)
7604 goto done;
7605 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7606 if (err)
7607 goto done;
7610 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7611 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7612 verbosity);
7613 if (err) {
7614 if (tagmsg_path)
7615 preserve_tagmsg = 1;
7616 goto done;
7619 err = got_ref_alloc(&ref, refname, tag_id);
7620 if (err) {
7621 if (tagmsg_path)
7622 preserve_tagmsg = 1;
7623 goto done;
7626 err = got_ref_write(ref, repo);
7627 if (err) {
7628 if (tagmsg_path)
7629 preserve_tagmsg = 1;
7630 goto done;
7633 err = got_object_id_str(&tag_id_str, tag_id);
7634 if (err) {
7635 if (tagmsg_path)
7636 preserve_tagmsg = 1;
7637 goto done;
7639 printf("Created tag %s\n", tag_id_str);
7640 done:
7641 if (preserve_tagmsg) {
7642 fprintf(stderr, "%s: tag message preserved in %s\n",
7643 getprogname(), tagmsg_path);
7644 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7645 err = got_error_from_errno2("unlink", tagmsg_path);
7646 free(tag_id_str);
7647 if (ref)
7648 got_ref_close(ref);
7649 free(commit_id);
7650 free(commit_id_str);
7651 free(refname);
7652 free(tagmsg);
7653 free(tagmsg_path);
7654 got_ref_list_free(&refs);
7655 return err;
7658 static const struct got_error *
7659 cmd_tag(int argc, char *argv[])
7661 const struct got_error *error = NULL;
7662 struct got_repository *repo = NULL;
7663 struct got_worktree *worktree = NULL;
7664 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7665 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7666 char *allowed_signers = NULL, *revoked_signers = NULL;
7667 const char *signer_id = NULL;
7668 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7669 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7670 int *pack_fds = NULL;
7672 #ifndef PROFILE
7673 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7674 "sendfd unveil", NULL) == -1)
7675 err(1, "pledge");
7676 #endif
7678 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7679 switch (ch) {
7680 case 'c':
7681 commit_id_arg = optarg;
7682 break;
7683 case 'l':
7684 do_list = 1;
7685 break;
7686 case 'm':
7687 tagmsg = optarg;
7688 break;
7689 case 'r':
7690 repo_path = realpath(optarg, NULL);
7691 if (repo_path == NULL) {
7692 error = got_error_from_errno2("realpath",
7693 optarg);
7694 goto done;
7696 got_path_strip_trailing_slashes(repo_path);
7697 break;
7698 case 's':
7699 signer_id = optarg;
7700 break;
7701 case 'V':
7702 verify_tags = 1;
7703 break;
7704 case 'v':
7705 if (verbosity < 0)
7706 verbosity = 0;
7707 else if (verbosity < 3)
7708 verbosity++;
7709 break;
7710 default:
7711 usage_tag();
7712 /* NOTREACHED */
7716 argc -= optind;
7717 argv += optind;
7719 if (do_list || verify_tags) {
7720 if (commit_id_arg != NULL)
7721 errx(1,
7722 "-c option can only be used when creating a tag");
7723 if (tagmsg) {
7724 if (do_list)
7725 option_conflict('l', 'm');
7726 else
7727 option_conflict('V', 'm');
7729 if (signer_id) {
7730 if (do_list)
7731 option_conflict('l', 's');
7732 else
7733 option_conflict('V', 's');
7735 if (argc > 1)
7736 usage_tag();
7737 } else if (argc != 1)
7738 usage_tag();
7740 if (argc == 1)
7741 tag_name = argv[0];
7743 cwd = getcwd(NULL, 0);
7744 if (cwd == NULL) {
7745 error = got_error_from_errno("getcwd");
7746 goto done;
7749 error = got_repo_pack_fds_open(&pack_fds);
7750 if (error != NULL)
7751 goto done;
7753 if (repo_path == NULL) {
7754 error = got_worktree_open(&worktree, cwd,
7755 GOT_WORKTREE_GOT_DIR);
7756 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7757 goto done;
7758 else
7759 error = NULL;
7760 if (worktree) {
7761 repo_path =
7762 strdup(got_worktree_get_repo_path(worktree));
7763 if (repo_path == NULL)
7764 error = got_error_from_errno("strdup");
7765 if (error)
7766 goto done;
7767 } else {
7768 repo_path = strdup(cwd);
7769 if (repo_path == NULL) {
7770 error = got_error_from_errno("strdup");
7771 goto done;
7776 if (do_list || verify_tags) {
7777 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7778 if (error != NULL)
7779 goto done;
7780 error = get_allowed_signers(&allowed_signers, repo, worktree);
7781 if (error)
7782 goto done;
7783 error = get_revoked_signers(&revoked_signers, repo, worktree);
7784 if (error)
7785 goto done;
7786 if (worktree) {
7787 /* Release work tree lock. */
7788 got_worktree_close(worktree);
7789 worktree = NULL;
7793 * Remove "cpath" promise unless needed for signature tmpfile
7794 * creation.
7796 if (verify_tags)
7797 got_sigs_apply_unveil();
7798 else {
7799 #ifndef PROFILE
7800 if (pledge("stdio rpath wpath flock proc exec sendfd "
7801 "unveil", NULL) == -1)
7802 err(1, "pledge");
7803 #endif
7805 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7806 if (error)
7807 goto done;
7808 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7809 revoked_signers, verbosity);
7810 } else {
7811 error = get_gitconfig_path(&gitconfig_path);
7812 if (error)
7813 goto done;
7814 error = got_repo_open(&repo, repo_path, gitconfig_path,
7815 pack_fds);
7816 if (error != NULL)
7817 goto done;
7819 error = get_author(&tagger, repo, worktree);
7820 if (error)
7821 goto done;
7822 if (signer_id == NULL)
7823 signer_id = get_signer_id(repo, worktree);
7825 if (tagmsg) {
7826 if (signer_id) {
7827 error = got_sigs_apply_unveil();
7828 if (error)
7829 goto done;
7831 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7832 if (error)
7833 goto done;
7836 if (commit_id_arg == NULL) {
7837 struct got_reference *head_ref;
7838 struct got_object_id *commit_id;
7839 error = got_ref_open(&head_ref, repo,
7840 worktree ? got_worktree_get_head_ref_name(worktree)
7841 : GOT_REF_HEAD, 0);
7842 if (error)
7843 goto done;
7844 error = got_ref_resolve(&commit_id, repo, head_ref);
7845 got_ref_close(head_ref);
7846 if (error)
7847 goto done;
7848 error = got_object_id_str(&commit_id_str, commit_id);
7849 free(commit_id);
7850 if (error)
7851 goto done;
7852 } else {
7853 error = got_keyword_to_idstr(&keyword_idstr,
7854 commit_id_arg, repo, worktree);
7855 if (error != NULL)
7856 goto done;
7857 commit_id_str = keyword_idstr;
7860 if (worktree) {
7861 /* Release work tree lock. */
7862 got_worktree_close(worktree);
7863 worktree = NULL;
7866 error = add_tag(repo, tagger, tag_name,
7867 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7868 signer_id, verbosity);
7870 done:
7871 if (repo) {
7872 const struct got_error *close_err = got_repo_close(repo);
7873 if (error == NULL)
7874 error = close_err;
7876 if (worktree)
7877 got_worktree_close(worktree);
7878 if (pack_fds) {
7879 const struct got_error *pack_err =
7880 got_repo_pack_fds_close(pack_fds);
7881 if (error == NULL)
7882 error = pack_err;
7884 free(cwd);
7885 free(repo_path);
7886 free(gitconfig_path);
7887 free(commit_id_str);
7888 free(tagger);
7889 free(allowed_signers);
7890 free(revoked_signers);
7891 return error;
7894 __dead static void
7895 usage_add(void)
7897 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7898 exit(1);
7901 static const struct got_error *
7902 add_progress(void *arg, unsigned char status, const char *path)
7904 while (path[0] == '/')
7905 path++;
7906 printf("%c %s\n", status, path);
7907 return NULL;
7910 static const struct got_error *
7911 cmd_add(int argc, char *argv[])
7913 const struct got_error *error = NULL;
7914 struct got_repository *repo = NULL;
7915 struct got_worktree *worktree = NULL;
7916 char *cwd = NULL;
7917 struct got_pathlist_head paths;
7918 struct got_pathlist_entry *pe;
7919 int ch, can_recurse = 0, no_ignores = 0;
7920 int *pack_fds = NULL;
7922 TAILQ_INIT(&paths);
7924 #ifndef PROFILE
7925 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7926 NULL) == -1)
7927 err(1, "pledge");
7928 #endif
7930 while ((ch = getopt(argc, argv, "IR")) != -1) {
7931 switch (ch) {
7932 case 'I':
7933 no_ignores = 1;
7934 break;
7935 case 'R':
7936 can_recurse = 1;
7937 break;
7938 default:
7939 usage_add();
7940 /* NOTREACHED */
7944 argc -= optind;
7945 argv += optind;
7947 if (argc < 1)
7948 usage_add();
7950 cwd = getcwd(NULL, 0);
7951 if (cwd == NULL) {
7952 error = got_error_from_errno("getcwd");
7953 goto done;
7956 error = got_repo_pack_fds_open(&pack_fds);
7957 if (error != NULL)
7958 goto done;
7960 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7961 if (error) {
7962 if (error->code == GOT_ERR_NOT_WORKTREE)
7963 error = wrap_not_worktree_error(error, "add", cwd);
7964 goto done;
7967 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7968 NULL, pack_fds);
7969 if (error != NULL)
7970 goto done;
7972 error = apply_unveil(got_repo_get_path(repo), 1,
7973 got_worktree_get_root_path(worktree));
7974 if (error)
7975 goto done;
7977 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7978 if (error)
7979 goto done;
7981 if (!can_recurse) {
7982 char *ondisk_path;
7983 struct stat sb;
7984 TAILQ_FOREACH(pe, &paths, entry) {
7985 if (asprintf(&ondisk_path, "%s/%s",
7986 got_worktree_get_root_path(worktree),
7987 pe->path) == -1) {
7988 error = got_error_from_errno("asprintf");
7989 goto done;
7991 if (lstat(ondisk_path, &sb) == -1) {
7992 if (errno == ENOENT) {
7993 free(ondisk_path);
7994 continue;
7996 error = got_error_from_errno2("lstat",
7997 ondisk_path);
7998 free(ondisk_path);
7999 goto done;
8001 free(ondisk_path);
8002 if (S_ISDIR(sb.st_mode)) {
8003 error = got_error_msg(GOT_ERR_BAD_PATH,
8004 "adding directories requires -R option");
8005 goto done;
8010 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8011 NULL, repo, no_ignores);
8012 done:
8013 if (repo) {
8014 const struct got_error *close_err = got_repo_close(repo);
8015 if (error == NULL)
8016 error = close_err;
8018 if (worktree)
8019 got_worktree_close(worktree);
8020 if (pack_fds) {
8021 const struct got_error *pack_err =
8022 got_repo_pack_fds_close(pack_fds);
8023 if (error == NULL)
8024 error = pack_err;
8026 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8027 free(cwd);
8028 return error;
8031 __dead static void
8032 usage_remove(void)
8034 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8035 getprogname());
8036 exit(1);
8039 static const struct got_error *
8040 print_remove_status(void *arg, unsigned char status,
8041 unsigned char staged_status, const char *path)
8043 while (path[0] == '/')
8044 path++;
8045 if (status == GOT_STATUS_NONEXISTENT)
8046 return NULL;
8047 if (status == staged_status && (status == GOT_STATUS_DELETE))
8048 status = GOT_STATUS_NO_CHANGE;
8049 printf("%c%c %s\n", status, staged_status, path);
8050 return NULL;
8053 static const struct got_error *
8054 cmd_remove(int argc, char *argv[])
8056 const struct got_error *error = NULL;
8057 struct got_worktree *worktree = NULL;
8058 struct got_repository *repo = NULL;
8059 const char *status_codes = NULL;
8060 char *cwd = NULL;
8061 struct got_pathlist_head paths;
8062 struct got_pathlist_entry *pe;
8063 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8064 int ignore_missing_paths = 0;
8065 int *pack_fds = NULL;
8067 TAILQ_INIT(&paths);
8069 #ifndef PROFILE
8070 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8071 NULL) == -1)
8072 err(1, "pledge");
8073 #endif
8075 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8076 switch (ch) {
8077 case 'f':
8078 delete_local_mods = 1;
8079 ignore_missing_paths = 1;
8080 break;
8081 case 'k':
8082 keep_on_disk = 1;
8083 break;
8084 case 'R':
8085 can_recurse = 1;
8086 break;
8087 case 's':
8088 for (i = 0; optarg[i] != '\0'; i++) {
8089 switch (optarg[i]) {
8090 case GOT_STATUS_MODIFY:
8091 delete_local_mods = 1;
8092 break;
8093 case GOT_STATUS_MISSING:
8094 ignore_missing_paths = 1;
8095 break;
8096 default:
8097 errx(1, "invalid status code '%c'",
8098 optarg[i]);
8101 status_codes = optarg;
8102 break;
8103 default:
8104 usage_remove();
8105 /* NOTREACHED */
8109 argc -= optind;
8110 argv += optind;
8112 if (argc < 1)
8113 usage_remove();
8115 cwd = getcwd(NULL, 0);
8116 if (cwd == NULL) {
8117 error = got_error_from_errno("getcwd");
8118 goto done;
8121 error = got_repo_pack_fds_open(&pack_fds);
8122 if (error != NULL)
8123 goto done;
8125 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8126 if (error) {
8127 if (error->code == GOT_ERR_NOT_WORKTREE)
8128 error = wrap_not_worktree_error(error, "remove", cwd);
8129 goto done;
8132 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8133 NULL, pack_fds);
8134 if (error)
8135 goto done;
8137 error = apply_unveil(got_repo_get_path(repo), 1,
8138 got_worktree_get_root_path(worktree));
8139 if (error)
8140 goto done;
8142 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8143 if (error)
8144 goto done;
8146 if (!can_recurse) {
8147 char *ondisk_path;
8148 struct stat sb;
8149 TAILQ_FOREACH(pe, &paths, entry) {
8150 if (asprintf(&ondisk_path, "%s/%s",
8151 got_worktree_get_root_path(worktree),
8152 pe->path) == -1) {
8153 error = got_error_from_errno("asprintf");
8154 goto done;
8156 if (lstat(ondisk_path, &sb) == -1) {
8157 if (errno == ENOENT) {
8158 free(ondisk_path);
8159 continue;
8161 error = got_error_from_errno2("lstat",
8162 ondisk_path);
8163 free(ondisk_path);
8164 goto done;
8166 free(ondisk_path);
8167 if (S_ISDIR(sb.st_mode)) {
8168 error = got_error_msg(GOT_ERR_BAD_PATH,
8169 "removing directories requires -R option");
8170 goto done;
8175 error = got_worktree_schedule_delete(worktree, &paths,
8176 delete_local_mods, status_codes, print_remove_status, NULL,
8177 repo, keep_on_disk, ignore_missing_paths);
8178 done:
8179 if (repo) {
8180 const struct got_error *close_err = got_repo_close(repo);
8181 if (error == NULL)
8182 error = close_err;
8184 if (worktree)
8185 got_worktree_close(worktree);
8186 if (pack_fds) {
8187 const struct got_error *pack_err =
8188 got_repo_pack_fds_close(pack_fds);
8189 if (error == NULL)
8190 error = pack_err;
8192 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8193 free(cwd);
8194 return error;
8197 __dead static void
8198 usage_patch(void)
8200 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8201 "[patchfile]\n", getprogname());
8202 exit(1);
8205 static const struct got_error *
8206 patch_from_stdin(int *patchfd)
8208 const struct got_error *err = NULL;
8209 ssize_t r;
8210 char buf[BUFSIZ];
8211 sig_t sighup, sigint, sigquit;
8213 *patchfd = got_opentempfd();
8214 if (*patchfd == -1)
8215 return got_error_from_errno("got_opentempfd");
8217 sighup = signal(SIGHUP, SIG_DFL);
8218 sigint = signal(SIGINT, SIG_DFL);
8219 sigquit = signal(SIGQUIT, SIG_DFL);
8221 for (;;) {
8222 r = read(0, buf, sizeof(buf));
8223 if (r == -1) {
8224 err = got_error_from_errno("read");
8225 break;
8227 if (r == 0)
8228 break;
8229 if (write(*patchfd, buf, r) == -1) {
8230 err = got_error_from_errno("write");
8231 break;
8235 signal(SIGHUP, sighup);
8236 signal(SIGINT, sigint);
8237 signal(SIGQUIT, sigquit);
8239 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8240 err = got_error_from_errno("lseek");
8242 if (err != NULL) {
8243 close(*patchfd);
8244 *patchfd = -1;
8247 return err;
8250 struct got_patch_progress_arg {
8251 int did_something;
8252 int conflicts;
8253 int rejects;
8256 static const struct got_error *
8257 patch_progress(void *arg, const char *old, const char *new,
8258 unsigned char status, const struct got_error *error, int old_from,
8259 int old_lines, int new_from, int new_lines, int offset,
8260 int ws_mangled, const struct got_error *hunk_err)
8262 const char *path = new == NULL ? old : new;
8263 struct got_patch_progress_arg *a = arg;
8265 while (*path == '/')
8266 path++;
8268 if (status != GOT_STATUS_NO_CHANGE &&
8269 status != 0 /* per-hunk progress */) {
8270 printf("%c %s\n", status, path);
8271 a->did_something = 1;
8274 if (hunk_err == NULL) {
8275 if (status == GOT_STATUS_CANNOT_UPDATE)
8276 a->rejects++;
8277 else if (status == GOT_STATUS_CONFLICT)
8278 a->conflicts++;
8281 if (error != NULL)
8282 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8284 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8285 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8286 old_lines, new_from, new_lines);
8287 if (hunk_err != NULL)
8288 printf("%s\n", hunk_err->msg);
8289 else if (offset != 0)
8290 printf("applied with offset %d\n", offset);
8291 else
8292 printf("hunk contains mangled whitespace\n");
8295 return NULL;
8298 static void
8299 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8301 if (!ppa->did_something)
8302 return;
8304 if (ppa->conflicts > 0)
8305 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8307 if (ppa->rejects > 0) {
8308 printf("Files where patch failed to apply: %d\n",
8309 ppa->rejects);
8313 static const struct got_error *
8314 cmd_patch(int argc, char *argv[])
8316 const struct got_error *error = NULL, *close_error = NULL;
8317 struct got_worktree *worktree = NULL;
8318 struct got_repository *repo = NULL;
8319 struct got_reflist_head refs;
8320 struct got_object_id *commit_id = NULL;
8321 const char *commit_id_str = NULL;
8322 struct stat sb;
8323 const char *errstr;
8324 char *cwd = NULL, *keyword_idstr = NULL;
8325 int ch, nop = 0, strip = -1, reverse = 0;
8326 int patchfd;
8327 int *pack_fds = NULL;
8328 struct got_patch_progress_arg ppa;
8330 TAILQ_INIT(&refs);
8332 #ifndef PROFILE
8333 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8334 "unveil", NULL) == -1)
8335 err(1, "pledge");
8336 #endif
8338 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8339 switch (ch) {
8340 case 'c':
8341 commit_id_str = optarg;
8342 break;
8343 case 'n':
8344 nop = 1;
8345 break;
8346 case 'p':
8347 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8348 if (errstr != NULL)
8349 errx(1, "pathname strip count is %s: %s",
8350 errstr, optarg);
8351 break;
8352 case 'R':
8353 reverse = 1;
8354 break;
8355 default:
8356 usage_patch();
8357 /* NOTREACHED */
8361 argc -= optind;
8362 argv += optind;
8364 if (argc == 0) {
8365 error = patch_from_stdin(&patchfd);
8366 if (error)
8367 return error;
8368 } else if (argc == 1) {
8369 patchfd = open(argv[0], O_RDONLY);
8370 if (patchfd == -1) {
8371 error = got_error_from_errno2("open", argv[0]);
8372 return error;
8374 if (fstat(patchfd, &sb) == -1) {
8375 error = got_error_from_errno2("fstat", argv[0]);
8376 goto done;
8378 if (!S_ISREG(sb.st_mode)) {
8379 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8380 goto done;
8382 } else
8383 usage_patch();
8385 if ((cwd = getcwd(NULL, 0)) == NULL) {
8386 error = got_error_from_errno("getcwd");
8387 goto done;
8390 error = got_repo_pack_fds_open(&pack_fds);
8391 if (error != NULL)
8392 goto done;
8394 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8395 if (error != NULL)
8396 goto done;
8398 const char *repo_path = got_worktree_get_repo_path(worktree);
8399 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8400 if (error != NULL)
8401 goto done;
8403 error = apply_unveil(got_repo_get_path(repo), 0,
8404 got_worktree_get_root_path(worktree));
8405 if (error != NULL)
8406 goto done;
8408 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8409 if (error)
8410 goto done;
8412 if (commit_id_str != NULL) {
8413 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8414 repo, worktree);
8415 if (error != NULL)
8416 goto done;
8418 error = got_repo_match_object_id(&commit_id, NULL,
8419 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8420 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8421 if (error)
8422 goto done;
8425 memset(&ppa, 0, sizeof(ppa));
8426 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8427 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8428 print_patch_progress_stats(&ppa);
8429 done:
8430 got_ref_list_free(&refs);
8431 free(keyword_idstr);
8432 free(commit_id);
8433 if (repo) {
8434 close_error = got_repo_close(repo);
8435 if (error == NULL)
8436 error = close_error;
8438 if (worktree != NULL) {
8439 close_error = got_worktree_close(worktree);
8440 if (error == NULL)
8441 error = close_error;
8443 if (pack_fds) {
8444 const struct got_error *pack_err =
8445 got_repo_pack_fds_close(pack_fds);
8446 if (error == NULL)
8447 error = pack_err;
8449 free(cwd);
8450 return error;
8453 __dead static void
8454 usage_revert(void)
8456 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8457 getprogname());
8458 exit(1);
8461 static const struct got_error *
8462 revert_progress(void *arg, unsigned char status, const char *path)
8464 if (status == GOT_STATUS_UNVERSIONED)
8465 return NULL;
8467 while (path[0] == '/')
8468 path++;
8469 printf("%c %s\n", status, path);
8470 return NULL;
8473 struct choose_patch_arg {
8474 FILE *patch_script_file;
8475 const char *action;
8478 static const struct got_error *
8479 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8480 int nchanges, const char *action)
8482 const struct got_error *err;
8483 char *line = NULL;
8484 size_t linesize = 0;
8485 ssize_t linelen;
8487 switch (status) {
8488 case GOT_STATUS_ADD:
8489 printf("A %s\n%s this addition? [y/n] ", path, action);
8490 break;
8491 case GOT_STATUS_DELETE:
8492 printf("D %s\n%s this deletion? [y/n] ", path, action);
8493 break;
8494 case GOT_STATUS_MODIFY:
8495 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8496 return got_error_from_errno("fseek");
8497 printf(GOT_COMMIT_SEP_STR);
8498 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8499 printf("%s", line);
8500 if (linelen == -1 && ferror(patch_file)) {
8501 err = got_error_from_errno("getline");
8502 free(line);
8503 return err;
8505 free(line);
8506 printf(GOT_COMMIT_SEP_STR);
8507 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8508 path, n, nchanges, action);
8509 break;
8510 default:
8511 return got_error_path(path, GOT_ERR_FILE_STATUS);
8514 fflush(stdout);
8515 return NULL;
8518 static const struct got_error *
8519 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8520 FILE *patch_file, int n, int nchanges)
8522 const struct got_error *err = NULL;
8523 char *line = NULL;
8524 size_t linesize = 0;
8525 ssize_t linelen;
8526 int resp = ' ';
8527 struct choose_patch_arg *a = arg;
8529 *choice = GOT_PATCH_CHOICE_NONE;
8531 if (a->patch_script_file) {
8532 char *nl;
8533 err = show_change(status, path, patch_file, n, nchanges,
8534 a->action);
8535 if (err)
8536 return err;
8537 linelen = getline(&line, &linesize, a->patch_script_file);
8538 if (linelen == -1) {
8539 if (ferror(a->patch_script_file))
8540 return got_error_from_errno("getline");
8541 return NULL;
8543 nl = strchr(line, '\n');
8544 if (nl)
8545 *nl = '\0';
8546 if (strcmp(line, "y") == 0) {
8547 *choice = GOT_PATCH_CHOICE_YES;
8548 printf("y\n");
8549 } else if (strcmp(line, "n") == 0) {
8550 *choice = GOT_PATCH_CHOICE_NO;
8551 printf("n\n");
8552 } else if (strcmp(line, "q") == 0 &&
8553 status == GOT_STATUS_MODIFY) {
8554 *choice = GOT_PATCH_CHOICE_QUIT;
8555 printf("q\n");
8556 } else
8557 printf("invalid response '%s'\n", line);
8558 free(line);
8559 return NULL;
8562 while (resp != 'y' && resp != 'n' && resp != 'q') {
8563 err = show_change(status, path, patch_file, n, nchanges,
8564 a->action);
8565 if (err)
8566 return err;
8567 resp = getchar();
8568 if (resp == '\n')
8569 resp = getchar();
8570 if (status == GOT_STATUS_MODIFY) {
8571 if (resp != 'y' && resp != 'n' && resp != 'q') {
8572 printf("invalid response '%c'\n", resp);
8573 resp = ' ';
8575 } else if (resp != 'y' && resp != 'n') {
8576 printf("invalid response '%c'\n", resp);
8577 resp = ' ';
8581 if (resp == 'y')
8582 *choice = GOT_PATCH_CHOICE_YES;
8583 else if (resp == 'n')
8584 *choice = GOT_PATCH_CHOICE_NO;
8585 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8586 *choice = GOT_PATCH_CHOICE_QUIT;
8588 return NULL;
8591 struct wt_commitable_path_arg {
8592 struct got_pathlist_head *commit_paths;
8593 int *has_changes;
8597 * Shortcut work tree status callback to determine if the set of paths scanned
8598 * has at least one versioned path that is being modified and, if not NULL, is
8599 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8600 * soon as a path is passed with a status that satisfies this criteria.
8602 static const struct got_error *
8603 worktree_has_commitable_path(void *arg, unsigned char status,
8604 unsigned char staged_status, const char *path,
8605 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8606 struct got_object_id *commit_id, int dirfd, const char *de_name)
8608 struct wt_commitable_path_arg *a = arg;
8610 if (status == staged_status && (status == GOT_STATUS_DELETE))
8611 status = GOT_STATUS_NO_CHANGE;
8613 if (!(status == GOT_STATUS_NO_CHANGE ||
8614 status == GOT_STATUS_UNVERSIONED) ||
8615 staged_status != GOT_STATUS_NO_CHANGE) {
8616 if (a->commit_paths != NULL) {
8617 struct got_pathlist_entry *pe;
8619 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8620 if (strncmp(path, pe->path,
8621 pe->path_len) == 0) {
8622 *a->has_changes = 1;
8623 break;
8626 } else
8627 *a->has_changes = 1;
8629 if (*a->has_changes)
8630 return got_error(GOT_ERR_FILE_MODIFIED);
8633 return NULL;
8637 * Check that the changeset of the commit identified by id is
8638 * comprised of at least one modified path that is being committed.
8640 static const struct got_error *
8641 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8642 struct got_object_id *id, struct got_worktree *worktree,
8643 struct got_repository *repo)
8645 const struct got_error *err;
8646 struct got_pathlist_head paths;
8647 struct got_commit_object *commit = NULL, *pcommit = NULL;
8648 struct got_tree_object *tree = NULL, *ptree = NULL;
8649 struct got_object_qid *pid;
8651 TAILQ_INIT(&paths);
8653 err = got_object_open_as_commit(&commit, repo, id);
8654 if (err)
8655 goto done;
8657 err = got_object_open_as_tree(&tree, repo,
8658 got_object_commit_get_tree_id(commit));
8659 if (err)
8660 goto done;
8662 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8663 if (pid != NULL) {
8664 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8665 if (err)
8666 goto done;
8668 err = got_object_open_as_tree(&ptree, repo,
8669 got_object_commit_get_tree_id(pcommit));
8670 if (err)
8671 goto done;
8674 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8675 got_diff_tree_collect_changed_paths, &paths, 0);
8676 if (err)
8677 goto done;
8679 err = got_worktree_status(worktree, &paths, repo, 0,
8680 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8681 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8683 * At least one changed path in the referenced commit is
8684 * modified in the work tree, that's all we need to know!
8686 err = NULL;
8689 done:
8690 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8691 if (commit)
8692 got_object_commit_close(commit);
8693 if (pcommit)
8694 got_object_commit_close(pcommit);
8695 if (tree)
8696 got_object_tree_close(tree);
8697 if (ptree)
8698 got_object_tree_close(ptree);
8699 return err;
8703 * Remove any "logmsg" reference comprised entirely of paths that have
8704 * been reverted in this work tree. If any path in the logmsg ref changeset
8705 * remains in a changed state in the worktree, do not remove the reference.
8707 static const struct got_error *
8708 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8710 const struct got_error *err;
8711 struct got_reflist_head refs;
8712 struct got_reflist_entry *re;
8713 struct got_commit_object *commit = NULL;
8714 struct got_object_id *commit_id = NULL;
8715 struct wt_commitable_path_arg wcpa;
8716 char *uuidstr = NULL;
8718 TAILQ_INIT(&refs);
8720 err = got_worktree_get_uuid(&uuidstr, worktree);
8721 if (err)
8722 goto done;
8724 err = got_ref_list(&refs, repo, "refs/got/worktree",
8725 got_ref_cmp_by_name, repo);
8726 if (err)
8727 goto done;
8729 TAILQ_FOREACH(re, &refs, entry) {
8730 const char *refname;
8731 int has_changes = 0;
8733 refname = got_ref_get_name(re->ref);
8735 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8736 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8737 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8738 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8739 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8740 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8741 else
8742 continue;
8744 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8745 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8746 else
8747 continue;
8749 err = got_repo_match_object_id(&commit_id, NULL, refname,
8750 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8751 if (err)
8752 goto done;
8754 err = got_object_open_as_commit(&commit, repo, commit_id);
8755 if (err)
8756 goto done;
8758 wcpa.commit_paths = NULL;
8759 wcpa.has_changes = &has_changes;
8761 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8762 worktree, repo);
8763 if (err)
8764 goto done;
8766 if (!has_changes) {
8767 err = got_ref_delete(re->ref, repo);
8768 if (err)
8769 goto done;
8772 got_object_commit_close(commit);
8773 commit = NULL;
8774 free(commit_id);
8775 commit_id = NULL;
8778 done:
8779 free(uuidstr);
8780 free(commit_id);
8781 got_ref_list_free(&refs);
8782 if (commit)
8783 got_object_commit_close(commit);
8784 return err;
8787 static const struct got_error *
8788 cmd_revert(int argc, char *argv[])
8790 const struct got_error *error = NULL;
8791 struct got_worktree *worktree = NULL;
8792 struct got_repository *repo = NULL;
8793 char *cwd = NULL, *path = NULL;
8794 struct got_pathlist_head paths;
8795 struct got_pathlist_entry *pe;
8796 int ch, can_recurse = 0, pflag = 0;
8797 FILE *patch_script_file = NULL;
8798 const char *patch_script_path = NULL;
8799 struct choose_patch_arg cpa;
8800 int *pack_fds = NULL;
8802 TAILQ_INIT(&paths);
8804 #ifndef PROFILE
8805 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8806 "unveil", NULL) == -1)
8807 err(1, "pledge");
8808 #endif
8810 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8811 switch (ch) {
8812 case 'F':
8813 patch_script_path = optarg;
8814 break;
8815 case 'p':
8816 pflag = 1;
8817 break;
8818 case 'R':
8819 can_recurse = 1;
8820 break;
8821 default:
8822 usage_revert();
8823 /* NOTREACHED */
8827 argc -= optind;
8828 argv += optind;
8830 if (argc < 1)
8831 usage_revert();
8832 if (patch_script_path && !pflag)
8833 errx(1, "-F option can only be used together with -p option");
8835 cwd = getcwd(NULL, 0);
8836 if (cwd == NULL) {
8837 error = got_error_from_errno("getcwd");
8838 goto done;
8841 error = got_repo_pack_fds_open(&pack_fds);
8842 if (error != NULL)
8843 goto done;
8845 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8846 if (error) {
8847 if (error->code == GOT_ERR_NOT_WORKTREE)
8848 error = wrap_not_worktree_error(error, "revert", cwd);
8849 goto done;
8852 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8853 NULL, pack_fds);
8854 if (error != NULL)
8855 goto done;
8857 if (patch_script_path) {
8858 patch_script_file = fopen(patch_script_path, "re");
8859 if (patch_script_file == NULL) {
8860 error = got_error_from_errno2("fopen",
8861 patch_script_path);
8862 goto done;
8867 * XXX "c" perm needed on repo dir to delete merge references.
8869 error = apply_unveil(got_repo_get_path(repo), 0,
8870 got_worktree_get_root_path(worktree));
8871 if (error)
8872 goto done;
8874 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8875 if (error)
8876 goto done;
8878 if (!can_recurse) {
8879 char *ondisk_path;
8880 struct stat sb;
8881 TAILQ_FOREACH(pe, &paths, entry) {
8882 if (asprintf(&ondisk_path, "%s/%s",
8883 got_worktree_get_root_path(worktree),
8884 pe->path) == -1) {
8885 error = got_error_from_errno("asprintf");
8886 goto done;
8888 if (lstat(ondisk_path, &sb) == -1) {
8889 if (errno == ENOENT) {
8890 free(ondisk_path);
8891 continue;
8893 error = got_error_from_errno2("lstat",
8894 ondisk_path);
8895 free(ondisk_path);
8896 goto done;
8898 free(ondisk_path);
8899 if (S_ISDIR(sb.st_mode)) {
8900 error = got_error_msg(GOT_ERR_BAD_PATH,
8901 "reverting directories requires -R option");
8902 goto done;
8907 cpa.patch_script_file = patch_script_file;
8908 cpa.action = "revert";
8909 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8910 pflag ? choose_patch : NULL, &cpa, repo);
8912 error = rm_logmsg_ref(worktree, repo);
8913 done:
8914 if (patch_script_file && fclose(patch_script_file) == EOF &&
8915 error == NULL)
8916 error = got_error_from_errno2("fclose", patch_script_path);
8917 if (repo) {
8918 const struct got_error *close_err = got_repo_close(repo);
8919 if (error == NULL)
8920 error = close_err;
8922 if (worktree)
8923 got_worktree_close(worktree);
8924 if (pack_fds) {
8925 const struct got_error *pack_err =
8926 got_repo_pack_fds_close(pack_fds);
8927 if (error == NULL)
8928 error = pack_err;
8930 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8931 free(path);
8932 free(cwd);
8933 return error;
8936 __dead static void
8937 usage_commit(void)
8939 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8940 "[-m message] [path ...]\n", getprogname());
8941 exit(1);
8944 struct collect_commit_logmsg_arg {
8945 const char *cmdline_log;
8946 const char *prepared_log;
8947 const char *merged_log;
8948 int non_interactive;
8949 const char *editor;
8950 const char *worktree_path;
8951 const char *branch_name;
8952 const char *repo_path;
8953 char *logmsg_path;
8957 static const struct got_error *
8958 read_prepared_logmsg(char **logmsg, const char *path)
8960 const struct got_error *err = NULL;
8961 FILE *f = NULL;
8962 struct stat sb;
8963 size_t r;
8965 *logmsg = NULL;
8966 memset(&sb, 0, sizeof(sb));
8968 f = fopen(path, "re");
8969 if (f == NULL)
8970 return got_error_from_errno2("fopen", path);
8972 if (fstat(fileno(f), &sb) == -1) {
8973 err = got_error_from_errno2("fstat", path);
8974 goto done;
8976 if (sb.st_size == 0) {
8977 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8978 goto done;
8981 *logmsg = malloc(sb.st_size + 1);
8982 if (*logmsg == NULL) {
8983 err = got_error_from_errno("malloc");
8984 goto done;
8987 r = fread(*logmsg, 1, sb.st_size, f);
8988 if (r != sb.st_size) {
8989 if (ferror(f))
8990 err = got_error_from_errno2("fread", path);
8991 else
8992 err = got_error(GOT_ERR_IO);
8993 goto done;
8995 (*logmsg)[sb.st_size] = '\0';
8996 done:
8997 if (fclose(f) == EOF && err == NULL)
8998 err = got_error_from_errno2("fclose", path);
8999 if (err) {
9000 free(*logmsg);
9001 *logmsg = NULL;
9003 return err;
9006 static const struct got_error *
9007 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9008 const char *diff_path, char **logmsg, void *arg)
9010 char *initial_content = NULL;
9011 struct got_pathlist_entry *pe;
9012 const struct got_error *err = NULL;
9013 char *template = NULL;
9014 char *prepared_msg = NULL, *merged_msg = NULL;
9015 struct collect_commit_logmsg_arg *a = arg;
9016 int initial_content_len;
9017 int fd = -1;
9018 size_t len;
9020 /* if a message was specified on the command line, just use it */
9021 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9022 len = strlen(a->cmdline_log) + 1;
9023 *logmsg = malloc(len + 1);
9024 if (*logmsg == NULL)
9025 return got_error_from_errno("malloc");
9026 strlcpy(*logmsg, a->cmdline_log, len);
9027 return NULL;
9028 } else if (a->prepared_log != NULL && a->non_interactive)
9029 return read_prepared_logmsg(logmsg, a->prepared_log);
9031 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9032 return got_error_from_errno("asprintf");
9034 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9035 if (err)
9036 goto done;
9038 if (a->prepared_log) {
9039 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9040 if (err)
9041 goto done;
9042 } else if (a->merged_log) {
9043 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9044 if (err)
9045 goto done;
9048 initial_content_len = asprintf(&initial_content,
9049 "%s%s\n# changes to be committed on branch %s:\n",
9050 prepared_msg ? prepared_msg : "",
9051 merged_msg ? merged_msg : "", a->branch_name);
9052 if (initial_content_len == -1) {
9053 err = got_error_from_errno("asprintf");
9054 goto done;
9057 if (write(fd, initial_content, initial_content_len) == -1) {
9058 err = got_error_from_errno2("write", a->logmsg_path);
9059 goto done;
9062 TAILQ_FOREACH(pe, commitable_paths, entry) {
9063 struct got_commitable *ct = pe->data;
9064 dprintf(fd, "# %c %s\n",
9065 got_commitable_get_status(ct),
9066 got_commitable_get_path(ct));
9069 if (diff_path) {
9070 dprintf(fd, "# detailed changes can be viewed in %s\n",
9071 diff_path);
9074 if (close(fd) == -1) {
9075 err = got_error_from_errno2("close", a->logmsg_path);
9076 goto done;
9078 fd = -1;
9080 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9081 initial_content_len, a->prepared_log ? 0 : 1);
9082 done:
9083 free(initial_content);
9084 free(template);
9085 free(prepared_msg);
9086 free(merged_msg);
9088 if (fd != -1 && close(fd) == -1 && err == NULL)
9089 err = got_error_from_errno2("close", a->logmsg_path);
9091 /* Editor is done; we can now apply unveil(2) */
9092 if (err == NULL)
9093 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9094 if (err) {
9095 free(*logmsg);
9096 *logmsg = NULL;
9098 return err;
9101 static const struct got_error *
9102 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9103 const char *type, int has_content)
9105 const struct got_error *err = NULL;
9106 char *logmsg = NULL;
9108 err = got_object_commit_get_logmsg(&logmsg, commit);
9109 if (err)
9110 return err;
9112 if (fprintf(f, "%s# log message of %s commit %s:%s",
9113 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9114 err = got_ferror(f, GOT_ERR_IO);
9116 free(logmsg);
9117 return err;
9121 * Lookup "logmsg" references of backed-out and cherrypicked commits
9122 * belonging to the current work tree. If found, and the worktree has
9123 * at least one modified file that was changed in the referenced commit,
9124 * add its log message to a new temporary file at *logmsg_path.
9125 * Add all refs found to matched_refs to be scheduled for removal on
9126 * successful commit.
9128 static const struct got_error *
9129 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9130 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9131 struct got_repository *repo)
9133 const struct got_error *err;
9134 struct got_commit_object *commit = NULL;
9135 struct got_object_id *id = NULL;
9136 struct got_reflist_head refs;
9137 struct got_reflist_entry *re, *re_match;
9138 FILE *f = NULL;
9139 char *uuidstr = NULL;
9140 int added_logmsg = 0;
9142 TAILQ_INIT(&refs);
9144 *logmsg_path = NULL;
9146 err = got_worktree_get_uuid(&uuidstr, worktree);
9147 if (err)
9148 goto done;
9150 err = got_ref_list(&refs, repo, "refs/got/worktree",
9151 got_ref_cmp_by_name, repo);
9152 if (err)
9153 goto done;
9155 TAILQ_FOREACH(re, &refs, entry) {
9156 const char *refname, *type;
9157 struct wt_commitable_path_arg wcpa;
9158 int add_logmsg = 0;
9160 refname = got_ref_get_name(re->ref);
9162 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9163 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9164 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9165 type = "cherrypicked";
9166 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9167 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9168 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9169 type = "backed-out";
9170 } else
9171 continue;
9173 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9174 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9175 else
9176 continue;
9178 err = got_repo_match_object_id(&id, NULL, refname,
9179 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9180 if (err)
9181 goto done;
9183 err = got_object_open_as_commit(&commit, repo, id);
9184 if (err)
9185 goto done;
9187 wcpa.commit_paths = paths;
9188 wcpa.has_changes = &add_logmsg;
9190 err = commit_path_changed_in_worktree(&wcpa, id,
9191 worktree, repo);
9192 if (err)
9193 goto done;
9195 if (add_logmsg) {
9196 if (f == NULL) {
9197 err = got_opentemp_named(logmsg_path, &f,
9198 "got-commit-logmsg", "");
9199 if (err)
9200 goto done;
9202 err = cat_logmsg(f, commit, refname, type,
9203 added_logmsg);
9204 if (err)
9205 goto done;
9206 if (!added_logmsg)
9207 ++added_logmsg;
9209 err = got_reflist_entry_dup(&re_match, re);
9210 if (err)
9211 goto done;
9212 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9215 got_object_commit_close(commit);
9216 commit = NULL;
9217 free(id);
9218 id = NULL;
9221 done:
9222 free(id);
9223 free(uuidstr);
9224 got_ref_list_free(&refs);
9225 if (commit)
9226 got_object_commit_close(commit);
9227 if (f && fclose(f) == EOF && err == NULL)
9228 err = got_error_from_errno("fclose");
9229 if (!added_logmsg) {
9230 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9231 err = got_error_from_errno2("unlink", *logmsg_path);
9232 *logmsg_path = NULL;
9234 return err;
9237 static const struct got_error *
9238 cmd_commit(int argc, char *argv[])
9240 const struct got_error *error = NULL;
9241 struct got_worktree *worktree = NULL;
9242 struct got_repository *repo = NULL;
9243 char *cwd = NULL, *id_str = NULL;
9244 struct got_object_id *id = NULL;
9245 const char *logmsg = NULL;
9246 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9247 struct collect_commit_logmsg_arg cl_arg;
9248 const char *author = NULL;
9249 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9250 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9251 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9252 int show_diff = 1, commit_conflicts = 0;
9253 struct got_pathlist_head paths;
9254 struct got_reflist_head refs;
9255 struct got_reflist_entry *re;
9256 int *pack_fds = NULL;
9258 TAILQ_INIT(&refs);
9259 TAILQ_INIT(&paths);
9260 cl_arg.logmsg_path = NULL;
9262 #ifndef PROFILE
9263 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9264 "unveil", NULL) == -1)
9265 err(1, "pledge");
9266 #endif
9268 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9269 switch (ch) {
9270 case 'A':
9271 author = optarg;
9272 error = valid_author(author);
9273 if (error)
9274 return error;
9275 break;
9276 case 'C':
9277 commit_conflicts = 1;
9278 break;
9279 case 'F':
9280 if (logmsg != NULL)
9281 option_conflict('F', 'm');
9282 prepared_logmsg = realpath(optarg, NULL);
9283 if (prepared_logmsg == NULL)
9284 return got_error_from_errno2("realpath",
9285 optarg);
9286 break;
9287 case 'm':
9288 if (prepared_logmsg)
9289 option_conflict('m', 'F');
9290 logmsg = optarg;
9291 break;
9292 case 'N':
9293 non_interactive = 1;
9294 break;
9295 case 'n':
9296 show_diff = 0;
9297 break;
9298 case 'S':
9299 allow_bad_symlinks = 1;
9300 break;
9301 default:
9302 usage_commit();
9303 /* NOTREACHED */
9307 argc -= optind;
9308 argv += optind;
9310 cwd = getcwd(NULL, 0);
9311 if (cwd == NULL) {
9312 error = got_error_from_errno("getcwd");
9313 goto done;
9316 error = got_repo_pack_fds_open(&pack_fds);
9317 if (error != NULL)
9318 goto done;
9320 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9321 if (error) {
9322 if (error->code == GOT_ERR_NOT_WORKTREE)
9323 error = wrap_not_worktree_error(error, "commit", cwd);
9324 goto done;
9327 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9328 if (error)
9329 goto done;
9330 if (rebase_in_progress) {
9331 error = got_error(GOT_ERR_REBASING);
9332 goto done;
9335 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9336 worktree);
9337 if (error)
9338 goto done;
9340 error = get_gitconfig_path(&gitconfig_path);
9341 if (error)
9342 goto done;
9343 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9344 gitconfig_path, pack_fds);
9345 if (error != NULL)
9346 goto done;
9348 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9349 if (error)
9350 goto done;
9351 if (merge_in_progress) {
9352 error = got_error(GOT_ERR_MERGE_BUSY);
9353 goto done;
9356 error = get_author(&committer, repo, worktree);
9357 if (error)
9358 goto done;
9360 if (author == NULL)
9361 author = committer;
9364 * unveil(2) traverses exec(2); if an editor is used we have
9365 * to apply unveil after the log message has been written.
9367 if (logmsg == NULL || strlen(logmsg) == 0)
9368 error = get_editor(&editor);
9369 else
9370 error = apply_unveil(got_repo_get_path(repo), 0,
9371 got_worktree_get_root_path(worktree));
9372 if (error)
9373 goto done;
9375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9376 if (error)
9377 goto done;
9379 if (prepared_logmsg == NULL) {
9380 error = lookup_logmsg_ref(&merged_logmsg,
9381 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9382 if (error)
9383 goto done;
9386 cl_arg.editor = editor;
9387 cl_arg.cmdline_log = logmsg;
9388 cl_arg.prepared_log = prepared_logmsg;
9389 cl_arg.merged_log = merged_logmsg;
9390 cl_arg.non_interactive = non_interactive;
9391 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9392 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9393 if (!histedit_in_progress) {
9394 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9395 error = got_error(GOT_ERR_COMMIT_BRANCH);
9396 goto done;
9398 cl_arg.branch_name += 11;
9400 cl_arg.repo_path = got_repo_get_path(repo);
9401 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9402 allow_bad_symlinks, show_diff, commit_conflicts,
9403 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9404 if (error) {
9405 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9406 cl_arg.logmsg_path != NULL)
9407 preserve_logmsg = 1;
9408 goto done;
9411 error = got_object_id_str(&id_str, id);
9412 if (error)
9413 goto done;
9414 printf("Created commit %s\n", id_str);
9416 TAILQ_FOREACH(re, &refs, entry) {
9417 error = got_ref_delete(re->ref, repo);
9418 if (error)
9419 goto done;
9422 done:
9423 if (preserve_logmsg) {
9424 fprintf(stderr, "%s: log message preserved in %s\n",
9425 getprogname(), cl_arg.logmsg_path);
9426 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9427 error == NULL)
9428 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9429 free(cl_arg.logmsg_path);
9430 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9431 error = got_error_from_errno2("unlink", merged_logmsg);
9432 free(merged_logmsg);
9433 if (repo) {
9434 const struct got_error *close_err = got_repo_close(repo);
9435 if (error == NULL)
9436 error = close_err;
9438 if (worktree)
9439 got_worktree_close(worktree);
9440 if (pack_fds) {
9441 const struct got_error *pack_err =
9442 got_repo_pack_fds_close(pack_fds);
9443 if (error == NULL)
9444 error = pack_err;
9446 got_ref_list_free(&refs);
9447 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9448 free(cwd);
9449 free(id_str);
9450 free(gitconfig_path);
9451 free(editor);
9452 free(committer);
9453 free(prepared_logmsg);
9454 return error;
9457 __dead static void
9458 usage_send(void)
9460 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9461 "[-r repository-path] [-t tag] [remote-repository]\n",
9462 getprogname());
9463 exit(1);
9466 static void
9467 print_load_info(int print_colored, int print_found, int print_trees,
9468 int ncolored, int nfound, int ntrees)
9470 if (print_colored) {
9471 printf("%d commit%s colored", ncolored,
9472 ncolored == 1 ? "" : "s");
9474 if (print_found) {
9475 printf("%s%d object%s found",
9476 ncolored > 0 ? "; " : "",
9477 nfound, nfound == 1 ? "" : "s");
9479 if (print_trees) {
9480 printf("; %d tree%s scanned", ntrees,
9481 ntrees == 1 ? "" : "s");
9485 struct got_send_progress_arg {
9486 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9487 int verbosity;
9488 int last_ncolored;
9489 int last_nfound;
9490 int last_ntrees;
9491 int loading_done;
9492 int last_ncommits;
9493 int last_nobj_total;
9494 int last_p_deltify;
9495 int last_p_written;
9496 int last_p_sent;
9497 int printed_something;
9498 int sent_something;
9499 struct got_pathlist_head *delete_branches;
9502 static const struct got_error *
9503 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9504 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9505 int nobj_written, off_t bytes_sent, const char *refname,
9506 const char *errmsg, int success)
9508 struct got_send_progress_arg *a = arg;
9509 char scaled_packsize[FMT_SCALED_STRSIZE];
9510 char scaled_sent[FMT_SCALED_STRSIZE];
9511 int p_deltify = 0, p_written = 0, p_sent = 0;
9512 int print_colored = 0, print_found = 0, print_trees = 0;
9513 int print_searching = 0, print_total = 0;
9514 int print_deltify = 0, print_written = 0, print_sent = 0;
9516 if (a->verbosity < 0)
9517 return NULL;
9519 if (refname) {
9520 const char *status = success ? "accepted" : "rejected";
9522 if (success) {
9523 struct got_pathlist_entry *pe;
9524 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9525 const char *branchname = pe->path;
9526 if (got_path_cmp(branchname, refname,
9527 strlen(branchname), strlen(refname)) == 0) {
9528 status = "deleted";
9529 a->sent_something = 1;
9530 break;
9535 if (a->printed_something)
9536 putchar('\n');
9537 printf("Server has %s %s", status, refname);
9538 if (errmsg)
9539 printf(": %s", errmsg);
9540 a->printed_something = 1;
9541 return NULL;
9544 if (a->last_ncolored != ncolored) {
9545 print_colored = 1;
9546 a->last_ncolored = ncolored;
9549 if (a->last_nfound != nfound) {
9550 print_colored = 1;
9551 print_found = 1;
9552 a->last_nfound = nfound;
9555 if (a->last_ntrees != ntrees) {
9556 print_colored = 1;
9557 print_found = 1;
9558 print_trees = 1;
9559 a->last_ntrees = ntrees;
9562 if ((print_colored || print_found || print_trees) &&
9563 !a->loading_done) {
9564 printf("\r");
9565 print_load_info(print_colored, print_found, print_trees,
9566 ncolored, nfound, ntrees);
9567 a->printed_something = 1;
9568 fflush(stdout);
9569 return NULL;
9570 } else if (!a->loading_done) {
9571 printf("\r");
9572 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9573 printf("\n");
9574 a->loading_done = 1;
9577 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9578 return got_error_from_errno("fmt_scaled");
9579 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9580 return got_error_from_errno("fmt_scaled");
9582 if (a->last_ncommits != ncommits) {
9583 print_searching = 1;
9584 a->last_ncommits = ncommits;
9587 if (a->last_nobj_total != nobj_total) {
9588 print_searching = 1;
9589 print_total = 1;
9590 a->last_nobj_total = nobj_total;
9593 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9594 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9595 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9596 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9597 return got_error(GOT_ERR_NO_SPACE);
9600 if (nobj_deltify > 0 || nobj_written > 0) {
9601 if (nobj_deltify > 0) {
9602 p_deltify = (nobj_deltify * 100) / nobj_total;
9603 if (p_deltify != a->last_p_deltify) {
9604 a->last_p_deltify = p_deltify;
9605 print_searching = 1;
9606 print_total = 1;
9607 print_deltify = 1;
9610 if (nobj_written > 0) {
9611 p_written = (nobj_written * 100) / nobj_total;
9612 if (p_written != a->last_p_written) {
9613 a->last_p_written = p_written;
9614 print_searching = 1;
9615 print_total = 1;
9616 print_deltify = 1;
9617 print_written = 1;
9622 if (bytes_sent > 0) {
9623 p_sent = (bytes_sent * 100) / packfile_size;
9624 if (p_sent != a->last_p_sent) {
9625 a->last_p_sent = p_sent;
9626 print_searching = 1;
9627 print_total = 1;
9628 print_deltify = 1;
9629 print_written = 1;
9630 print_sent = 1;
9632 a->sent_something = 1;
9635 if (print_searching || print_total || print_deltify || print_written ||
9636 print_sent)
9637 printf("\r");
9638 if (print_searching)
9639 printf("packing %d reference%s", ncommits,
9640 ncommits == 1 ? "" : "s");
9641 if (print_total)
9642 printf("; %d object%s", nobj_total,
9643 nobj_total == 1 ? "" : "s");
9644 if (print_deltify)
9645 printf("; deltify: %d%%", p_deltify);
9646 if (print_sent)
9647 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9648 scaled_packsize, p_sent);
9649 else if (print_written)
9650 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9651 scaled_packsize, p_written);
9652 if (print_searching || print_total || print_deltify ||
9653 print_written || print_sent) {
9654 a->printed_something = 1;
9655 fflush(stdout);
9657 return NULL;
9660 static const struct got_error *
9661 cmd_send(int argc, char *argv[])
9663 const struct got_error *error = NULL;
9664 char *cwd = NULL, *repo_path = NULL;
9665 const char *remote_name;
9666 char *proto = NULL, *host = NULL, *port = NULL;
9667 char *repo_name = NULL, *server_path = NULL;
9668 const struct got_remote_repo *remotes, *remote = NULL;
9669 int nremotes, nbranches = 0, ndelete_branches = 0;
9670 struct got_repository *repo = NULL;
9671 struct got_worktree *worktree = NULL;
9672 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9673 struct got_pathlist_head branches;
9674 struct got_pathlist_head tags;
9675 struct got_reflist_head all_branches;
9676 struct got_reflist_head all_tags;
9677 struct got_pathlist_head delete_args;
9678 struct got_pathlist_head delete_branches;
9679 struct got_reflist_entry *re;
9680 struct got_pathlist_entry *pe;
9681 int i, ch, sendfd = -1, sendstatus;
9682 pid_t sendpid = -1;
9683 struct got_send_progress_arg spa;
9684 int verbosity = 0, overwrite_refs = 0;
9685 int send_all_branches = 0, send_all_tags = 0;
9686 struct got_reference *ref = NULL;
9687 int *pack_fds = NULL;
9689 TAILQ_INIT(&branches);
9690 TAILQ_INIT(&tags);
9691 TAILQ_INIT(&all_branches);
9692 TAILQ_INIT(&all_tags);
9693 TAILQ_INIT(&delete_args);
9694 TAILQ_INIT(&delete_branches);
9696 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9697 switch (ch) {
9698 case 'a':
9699 send_all_branches = 1;
9700 break;
9701 case 'b':
9702 error = got_pathlist_append(&branches, optarg, NULL);
9703 if (error)
9704 return error;
9705 nbranches++;
9706 break;
9707 case 'd':
9708 error = got_pathlist_append(&delete_args, optarg, NULL);
9709 if (error)
9710 return error;
9711 break;
9712 case 'f':
9713 overwrite_refs = 1;
9714 break;
9715 case 'q':
9716 verbosity = -1;
9717 break;
9718 case 'r':
9719 repo_path = realpath(optarg, NULL);
9720 if (repo_path == NULL)
9721 return got_error_from_errno2("realpath",
9722 optarg);
9723 got_path_strip_trailing_slashes(repo_path);
9724 break;
9725 case 'T':
9726 send_all_tags = 1;
9727 break;
9728 case 't':
9729 error = got_pathlist_append(&tags, optarg, NULL);
9730 if (error)
9731 return error;
9732 break;
9733 case 'v':
9734 if (verbosity < 0)
9735 verbosity = 0;
9736 else if (verbosity < 3)
9737 verbosity++;
9738 break;
9739 default:
9740 usage_send();
9741 /* NOTREACHED */
9744 argc -= optind;
9745 argv += optind;
9747 if (send_all_branches && !TAILQ_EMPTY(&branches))
9748 option_conflict('a', 'b');
9749 if (send_all_tags && !TAILQ_EMPTY(&tags))
9750 option_conflict('T', 't');
9753 if (argc == 0)
9754 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9755 else if (argc == 1)
9756 remote_name = argv[0];
9757 else
9758 usage_send();
9760 cwd = getcwd(NULL, 0);
9761 if (cwd == NULL) {
9762 error = got_error_from_errno("getcwd");
9763 goto done;
9766 error = got_repo_pack_fds_open(&pack_fds);
9767 if (error != NULL)
9768 goto done;
9770 if (repo_path == NULL) {
9771 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9772 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9773 goto done;
9774 else
9775 error = NULL;
9776 if (worktree) {
9777 repo_path =
9778 strdup(got_worktree_get_repo_path(worktree));
9779 if (repo_path == NULL)
9780 error = got_error_from_errno("strdup");
9781 if (error)
9782 goto done;
9783 } else {
9784 repo_path = strdup(cwd);
9785 if (repo_path == NULL) {
9786 error = got_error_from_errno("strdup");
9787 goto done;
9792 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9793 if (error)
9794 goto done;
9796 if (worktree) {
9797 worktree_conf = got_worktree_get_gotconfig(worktree);
9798 if (worktree_conf) {
9799 got_gotconfig_get_remotes(&nremotes, &remotes,
9800 worktree_conf);
9801 for (i = 0; i < nremotes; i++) {
9802 if (strcmp(remotes[i].name, remote_name) == 0) {
9803 remote = &remotes[i];
9804 break;
9809 if (remote == NULL) {
9810 repo_conf = got_repo_get_gotconfig(repo);
9811 if (repo_conf) {
9812 got_gotconfig_get_remotes(&nremotes, &remotes,
9813 repo_conf);
9814 for (i = 0; i < nremotes; i++) {
9815 if (strcmp(remotes[i].name, remote_name) == 0) {
9816 remote = &remotes[i];
9817 break;
9822 if (remote == NULL) {
9823 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9824 for (i = 0; i < nremotes; i++) {
9825 if (strcmp(remotes[i].name, remote_name) == 0) {
9826 remote = &remotes[i];
9827 break;
9831 if (remote == NULL) {
9832 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9833 goto done;
9836 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9837 &repo_name, remote->send_url);
9838 if (error)
9839 goto done;
9841 if (strcmp(proto, "git") == 0) {
9842 #ifndef PROFILE
9843 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9844 "sendfd dns inet unveil", NULL) == -1)
9845 err(1, "pledge");
9846 #endif
9847 } else if (strcmp(proto, "git+ssh") == 0 ||
9848 strcmp(proto, "ssh") == 0) {
9849 #ifndef PROFILE
9850 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9851 "sendfd unveil", NULL) == -1)
9852 err(1, "pledge");
9853 #endif
9854 } else if (strcmp(proto, "http") == 0 ||
9855 strcmp(proto, "git+http") == 0) {
9856 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9857 goto done;
9858 } else {
9859 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9860 goto done;
9863 error = got_dial_apply_unveil(proto);
9864 if (error)
9865 goto done;
9867 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9868 if (error)
9869 goto done;
9871 if (send_all_branches) {
9872 error = got_ref_list(&all_branches, repo, "refs/heads",
9873 got_ref_cmp_by_name, NULL);
9874 if (error)
9875 goto done;
9876 TAILQ_FOREACH(re, &all_branches, entry) {
9877 const char *branchname = got_ref_get_name(re->ref);
9878 error = got_pathlist_append(&branches,
9879 branchname, NULL);
9880 if (error)
9881 goto done;
9882 nbranches++;
9884 } else if (nbranches == 0) {
9885 for (i = 0; i < remote->nsend_branches; i++) {
9886 error = got_pathlist_append(&branches,
9887 remote->send_branches[i], NULL);
9888 if (error)
9889 goto done;
9893 if (send_all_tags) {
9894 error = got_ref_list(&all_tags, repo, "refs/tags",
9895 got_ref_cmp_by_name, NULL);
9896 if (error)
9897 goto done;
9898 TAILQ_FOREACH(re, &all_tags, entry) {
9899 const char *tagname = got_ref_get_name(re->ref);
9900 error = got_pathlist_append(&tags,
9901 tagname, NULL);
9902 if (error)
9903 goto done;
9908 * To prevent accidents only branches in refs/heads/ can be deleted
9909 * with 'got send -d'.
9910 * Deleting anything else requires local repository access or Git.
9912 TAILQ_FOREACH(pe, &delete_args, entry) {
9913 const char *branchname = pe->path;
9914 char *s;
9915 struct got_pathlist_entry *new;
9916 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9917 s = strdup(branchname);
9918 if (s == NULL) {
9919 error = got_error_from_errno("strdup");
9920 goto done;
9922 } else {
9923 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9924 error = got_error_from_errno("asprintf");
9925 goto done;
9928 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9929 if (error || new == NULL /* duplicate */)
9930 free(s);
9931 if (error)
9932 goto done;
9933 ndelete_branches++;
9936 if (nbranches == 0 && ndelete_branches == 0) {
9937 struct got_reference *head_ref;
9938 if (worktree)
9939 error = got_ref_open(&head_ref, repo,
9940 got_worktree_get_head_ref_name(worktree), 0);
9941 else
9942 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9943 if (error)
9944 goto done;
9945 if (got_ref_is_symbolic(head_ref)) {
9946 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9947 got_ref_close(head_ref);
9948 if (error)
9949 goto done;
9950 } else
9951 ref = head_ref;
9952 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9953 NULL);
9954 if (error)
9955 goto done;
9956 nbranches++;
9959 if (verbosity >= 0) {
9960 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9961 remote->name, proto, host,
9962 port ? ":" : "", port ? port : "",
9963 *server_path == '/' ? "" : "/", server_path);
9966 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9967 server_path, verbosity);
9968 if (error)
9969 goto done;
9971 memset(&spa, 0, sizeof(spa));
9972 spa.last_scaled_packsize[0] = '\0';
9973 spa.last_p_deltify = -1;
9974 spa.last_p_written = -1;
9975 spa.verbosity = verbosity;
9976 spa.delete_branches = &delete_branches;
9977 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9978 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9979 check_cancelled, NULL);
9980 if (spa.printed_something)
9981 putchar('\n');
9982 if (error)
9983 goto done;
9984 if (!spa.sent_something && verbosity >= 0)
9985 printf("Already up-to-date\n");
9986 done:
9987 if (sendpid > 0) {
9988 if (kill(sendpid, SIGTERM) == -1)
9989 error = got_error_from_errno("kill");
9990 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9991 error = got_error_from_errno("waitpid");
9993 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9994 error = got_error_from_errno("close");
9995 if (repo) {
9996 const struct got_error *close_err = got_repo_close(repo);
9997 if (error == NULL)
9998 error = close_err;
10000 if (worktree)
10001 got_worktree_close(worktree);
10002 if (pack_fds) {
10003 const struct got_error *pack_err =
10004 got_repo_pack_fds_close(pack_fds);
10005 if (error == NULL)
10006 error = pack_err;
10008 if (ref)
10009 got_ref_close(ref);
10010 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10011 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10012 got_ref_list_free(&all_branches);
10013 got_ref_list_free(&all_tags);
10014 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10015 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10016 free(cwd);
10017 free(repo_path);
10018 free(proto);
10019 free(host);
10020 free(port);
10021 free(server_path);
10022 free(repo_name);
10023 return error;
10027 * Print and if delete is set delete all ref_prefix references.
10028 * If wanted_ref is not NULL, only print or delete this reference.
10030 static const struct got_error *
10031 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10032 const char *wanted_ref, int delete, struct got_worktree *worktree,
10033 struct got_repository *repo)
10035 const struct got_error *err;
10036 struct got_pathlist_head paths;
10037 struct got_reflist_head refs;
10038 struct got_reflist_entry *re;
10039 struct got_reflist_object_id_map *refs_idmap = NULL;
10040 struct got_commit_object *commit = NULL;
10041 struct got_object_id *id = NULL;
10042 const char *header_prefix;
10043 char *uuidstr = NULL;
10044 int found = 0;
10046 TAILQ_INIT(&refs);
10047 TAILQ_INIT(&paths);
10049 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10050 if (err)
10051 goto done;
10053 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10054 if (err)
10055 goto done;
10057 if (worktree != NULL) {
10058 err = got_worktree_get_uuid(&uuidstr, worktree);
10059 if (err)
10060 goto done;
10063 if (wanted_ref) {
10064 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10065 wanted_ref += 11;
10068 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10069 header_prefix = "backout";
10070 else
10071 header_prefix = "cherrypick";
10073 TAILQ_FOREACH(re, &refs, entry) {
10074 const char *refname, *wt;
10076 refname = got_ref_get_name(re->ref);
10078 err = check_cancelled(NULL);
10079 if (err)
10080 goto done;
10082 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10083 refname += prefix_len + 1; /* skip '-' delimiter */
10084 else
10085 continue;
10087 wt = refname;
10089 if (worktree == NULL || strncmp(refname, uuidstr,
10090 GOT_WORKTREE_UUID_STRLEN) == 0)
10091 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10092 else
10093 continue;
10095 err = got_repo_match_object_id(&id, NULL, refname,
10096 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10097 if (err)
10098 goto done;
10100 err = got_object_open_as_commit(&commit, repo, id);
10101 if (err)
10102 goto done;
10104 if (wanted_ref)
10105 found = strncmp(wanted_ref, refname,
10106 strlen(wanted_ref)) == 0;
10107 if (wanted_ref && !found) {
10108 struct got_reflist_head *ci_refs;
10110 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10111 id);
10113 if (ci_refs) {
10114 char *refs_str = NULL;
10115 char const *r = NULL;
10117 err = build_refs_str(&refs_str, ci_refs, id,
10118 repo, 1);
10119 if (err)
10120 goto done;
10122 r = refs_str;
10123 while (r) {
10124 if (strncmp(r, wanted_ref,
10125 strlen(wanted_ref)) == 0) {
10126 found = 1;
10127 break;
10129 r = strchr(r, ' ');
10130 if (r)
10131 ++r;
10133 free(refs_str);
10137 if (wanted_ref == NULL || found) {
10138 if (delete) {
10139 err = got_ref_delete(re->ref, repo);
10140 if (err)
10141 goto done;
10142 printf("Deleted: ");
10143 err = print_commit_oneline(commit, id, repo,
10144 refs_idmap);
10145 } else {
10147 * Print paths modified by commit to help
10148 * associate commits with worktree changes.
10150 err = get_changed_paths(&paths, commit,
10151 repo, NULL);
10152 if (err)
10153 goto done;
10155 err = print_commit(commit, id, repo, NULL,
10156 &paths, NULL, 0, 0, refs_idmap, NULL,
10157 header_prefix);
10158 got_pathlist_free(&paths,
10159 GOT_PATHLIST_FREE_ALL);
10161 if (worktree == NULL)
10162 printf("work tree: %.*s\n\n",
10163 GOT_WORKTREE_UUID_STRLEN, wt);
10165 if (err || found)
10166 goto done;
10169 got_object_commit_close(commit);
10170 commit = NULL;
10171 free(id);
10172 id = NULL;
10175 if (wanted_ref != NULL && !found)
10176 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10178 done:
10179 free(id);
10180 free(uuidstr);
10181 got_ref_list_free(&refs);
10182 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10183 if (refs_idmap)
10184 got_reflist_object_id_map_free(refs_idmap);
10185 if (commit)
10186 got_object_commit_close(commit);
10187 return err;
10191 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10192 * identified by id for log messages to prepopulate the editor on commit.
10194 static const struct got_error *
10195 logmsg_ref(struct got_object_id *id, const char *prefix,
10196 struct got_worktree *worktree, struct got_repository *repo)
10198 const struct got_error *err = NULL;
10199 char *idstr, *ref = NULL, *refname = NULL;
10200 int histedit_in_progress;
10201 int rebase_in_progress, merge_in_progress;
10204 * Silenty refuse to create merge reference if any histedit, merge,
10205 * or rebase operation is in progress.
10207 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10208 worktree);
10209 if (err)
10210 return err;
10211 if (histedit_in_progress)
10212 return NULL;
10214 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10215 if (err)
10216 return err;
10217 if (rebase_in_progress)
10218 return NULL;
10220 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10221 repo);
10222 if (err)
10223 return err;
10224 if (merge_in_progress)
10225 return NULL;
10227 err = got_object_id_str(&idstr, id);
10228 if (err)
10229 return err;
10231 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10232 if (err)
10233 goto done;
10235 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10236 err = got_error_from_errno("asprintf");
10237 goto done;
10240 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10241 -1, repo);
10242 done:
10243 free(ref);
10244 free(idstr);
10245 free(refname);
10246 return err;
10249 __dead static void
10250 usage_cherrypick(void)
10252 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10253 getprogname());
10254 exit(1);
10257 static const struct got_error *
10258 cmd_cherrypick(int argc, char *argv[])
10260 const struct got_error *error = NULL;
10261 struct got_worktree *worktree = NULL;
10262 struct got_repository *repo = NULL;
10263 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10264 struct got_object_id *commit_id = NULL;
10265 struct got_commit_object *commit = NULL;
10266 struct got_object_qid *pid;
10267 int ch, list_refs = 0, remove_refs = 0;
10268 struct got_update_progress_arg upa;
10269 int *pack_fds = NULL;
10271 #ifndef PROFILE
10272 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10273 "unveil", NULL) == -1)
10274 err(1, "pledge");
10275 #endif
10277 while ((ch = getopt(argc, argv, "lX")) != -1) {
10278 switch (ch) {
10279 case 'l':
10280 list_refs = 1;
10281 break;
10282 case 'X':
10283 remove_refs = 1;
10284 break;
10285 default:
10286 usage_cherrypick();
10287 /* NOTREACHED */
10291 argc -= optind;
10292 argv += optind;
10294 if (list_refs || remove_refs) {
10295 if (argc != 0 && argc != 1)
10296 usage_cherrypick();
10297 } else if (argc != 1)
10298 usage_cherrypick();
10299 if (list_refs && remove_refs)
10300 option_conflict('l', 'X');
10302 cwd = getcwd(NULL, 0);
10303 if (cwd == NULL) {
10304 error = got_error_from_errno("getcwd");
10305 goto done;
10308 error = got_repo_pack_fds_open(&pack_fds);
10309 if (error != NULL)
10310 goto done;
10312 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10313 if (error) {
10314 if (list_refs || remove_refs) {
10315 if (error->code != GOT_ERR_NOT_WORKTREE)
10316 goto done;
10317 } else {
10318 if (error->code == GOT_ERR_NOT_WORKTREE)
10319 error = wrap_not_worktree_error(error,
10320 "cherrypick", cwd);
10321 goto done;
10325 error = got_repo_open(&repo,
10326 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10327 NULL, pack_fds);
10328 if (error != NULL)
10329 goto done;
10331 error = apply_unveil(got_repo_get_path(repo), 0,
10332 worktree ? got_worktree_get_root_path(worktree) : NULL);
10333 if (error)
10334 goto done;
10336 if (list_refs || remove_refs) {
10337 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10338 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10339 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10340 goto done;
10343 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10344 if (error != NULL)
10345 goto done;
10347 error = got_repo_match_object_id(&commit_id, NULL,
10348 keyword_idstr != NULL ? keyword_idstr : argv[0],
10349 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10350 if (error)
10351 goto done;
10352 error = got_object_id_str(&commit_id_str, commit_id);
10353 if (error)
10354 goto done;
10356 error = got_object_open_as_commit(&commit, repo, commit_id);
10357 if (error)
10358 goto done;
10359 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10360 memset(&upa, 0, sizeof(upa));
10361 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10362 commit_id, repo, update_progress, &upa, check_cancelled,
10363 NULL);
10364 if (error != NULL)
10365 goto done;
10367 if (upa.did_something) {
10368 error = logmsg_ref(commit_id,
10369 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10370 if (error)
10371 goto done;
10372 printf("Merged commit %s\n", commit_id_str);
10374 print_merge_progress_stats(&upa);
10375 done:
10376 free(cwd);
10377 free(keyword_idstr);
10378 if (commit)
10379 got_object_commit_close(commit);
10380 free(commit_id_str);
10381 if (worktree)
10382 got_worktree_close(worktree);
10383 if (repo) {
10384 const struct got_error *close_err = got_repo_close(repo);
10385 if (error == NULL)
10386 error = close_err;
10388 if (pack_fds) {
10389 const struct got_error *pack_err =
10390 got_repo_pack_fds_close(pack_fds);
10391 if (error == NULL)
10392 error = pack_err;
10395 return error;
10398 __dead static void
10399 usage_backout(void)
10401 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10402 exit(1);
10405 static const struct got_error *
10406 cmd_backout(int argc, char *argv[])
10408 const struct got_error *error = NULL;
10409 struct got_worktree *worktree = NULL;
10410 struct got_repository *repo = NULL;
10411 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10412 struct got_object_id *commit_id = NULL;
10413 struct got_commit_object *commit = NULL;
10414 struct got_object_qid *pid;
10415 int ch, list_refs = 0, remove_refs = 0;
10416 struct got_update_progress_arg upa;
10417 int *pack_fds = NULL;
10419 #ifndef PROFILE
10420 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10421 "unveil", NULL) == -1)
10422 err(1, "pledge");
10423 #endif
10425 while ((ch = getopt(argc, argv, "lX")) != -1) {
10426 switch (ch) {
10427 case 'l':
10428 list_refs = 1;
10429 break;
10430 case 'X':
10431 remove_refs = 1;
10432 break;
10433 default:
10434 usage_backout();
10435 /* NOTREACHED */
10439 argc -= optind;
10440 argv += optind;
10442 if (list_refs || remove_refs) {
10443 if (argc != 0 && argc != 1)
10444 usage_backout();
10445 } else if (argc != 1)
10446 usage_backout();
10447 if (list_refs && remove_refs)
10448 option_conflict('l', 'X');
10450 cwd = getcwd(NULL, 0);
10451 if (cwd == NULL) {
10452 error = got_error_from_errno("getcwd");
10453 goto done;
10456 error = got_repo_pack_fds_open(&pack_fds);
10457 if (error != NULL)
10458 goto done;
10460 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10461 if (error) {
10462 if (list_refs || remove_refs) {
10463 if (error->code != GOT_ERR_NOT_WORKTREE)
10464 goto done;
10465 } else {
10466 if (error->code == GOT_ERR_NOT_WORKTREE)
10467 error = wrap_not_worktree_error(error,
10468 "backout", cwd);
10469 goto done;
10473 error = got_repo_open(&repo,
10474 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10475 NULL, pack_fds);
10476 if (error != NULL)
10477 goto done;
10479 error = apply_unveil(got_repo_get_path(repo), 0,
10480 worktree ? got_worktree_get_root_path(worktree) : NULL);
10481 if (error)
10482 goto done;
10484 if (list_refs || remove_refs) {
10485 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10486 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10487 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10488 goto done;
10491 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10492 if (error != NULL)
10493 goto done;
10495 error = got_repo_match_object_id(&commit_id, NULL,
10496 keyword_idstr != NULL ? keyword_idstr : argv[0],
10497 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10498 if (error)
10499 goto done;
10500 error = got_object_id_str(&commit_id_str, commit_id);
10501 if (error)
10502 goto done;
10504 error = got_object_open_as_commit(&commit, repo, commit_id);
10505 if (error)
10506 goto done;
10507 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10508 if (pid == NULL) {
10509 error = got_error(GOT_ERR_ROOT_COMMIT);
10510 goto done;
10513 memset(&upa, 0, sizeof(upa));
10514 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10515 repo, update_progress, &upa, check_cancelled, NULL);
10516 if (error != NULL)
10517 goto done;
10519 if (upa.did_something) {
10520 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10521 worktree, repo);
10522 if (error)
10523 goto done;
10524 printf("Backed out commit %s\n", commit_id_str);
10526 print_merge_progress_stats(&upa);
10527 done:
10528 free(cwd);
10529 free(keyword_idstr);
10530 if (commit)
10531 got_object_commit_close(commit);
10532 free(commit_id_str);
10533 if (worktree)
10534 got_worktree_close(worktree);
10535 if (repo) {
10536 const struct got_error *close_err = got_repo_close(repo);
10537 if (error == NULL)
10538 error = close_err;
10540 if (pack_fds) {
10541 const struct got_error *pack_err =
10542 got_repo_pack_fds_close(pack_fds);
10543 if (error == NULL)
10544 error = pack_err;
10546 return error;
10549 __dead static void
10550 usage_rebase(void)
10552 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10553 exit(1);
10556 static void
10557 trim_logmsg(char *logmsg, int limit)
10559 char *nl;
10560 size_t len;
10562 len = strlen(logmsg);
10563 if (len > limit)
10564 len = limit;
10565 logmsg[len] = '\0';
10566 nl = strchr(logmsg, '\n');
10567 if (nl)
10568 *nl = '\0';
10571 static const struct got_error *
10572 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10574 const struct got_error *err;
10575 char *logmsg0 = NULL;
10576 const char *s;
10578 err = got_object_commit_get_logmsg(&logmsg0, commit);
10579 if (err)
10580 return err;
10582 s = logmsg0;
10583 while (isspace((unsigned char)s[0]))
10584 s++;
10586 *logmsg = strdup(s);
10587 if (*logmsg == NULL) {
10588 err = got_error_from_errno("strdup");
10589 goto done;
10592 trim_logmsg(*logmsg, limit);
10593 done:
10594 free(logmsg0);
10595 return err;
10598 static const struct got_error *
10599 show_rebase_merge_conflict(struct got_object_id *id,
10600 struct got_repository *repo)
10602 const struct got_error *err;
10603 struct got_commit_object *commit = NULL;
10604 char *id_str = NULL, *logmsg = NULL;
10606 err = got_object_open_as_commit(&commit, repo, id);
10607 if (err)
10608 return err;
10610 err = got_object_id_str(&id_str, id);
10611 if (err)
10612 goto done;
10614 id_str[12] = '\0';
10616 err = get_short_logmsg(&logmsg, 42, commit);
10617 if (err)
10618 goto done;
10620 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10621 done:
10622 free(id_str);
10623 got_object_commit_close(commit);
10624 free(logmsg);
10625 return err;
10628 static const struct got_error *
10629 show_rebase_progress(struct got_commit_object *commit,
10630 struct got_object_id *old_id, struct got_object_id *new_id)
10632 const struct got_error *err;
10633 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10635 err = got_object_id_str(&old_id_str, old_id);
10636 if (err)
10637 goto done;
10639 if (new_id) {
10640 err = got_object_id_str(&new_id_str, new_id);
10641 if (err)
10642 goto done;
10645 old_id_str[12] = '\0';
10646 if (new_id_str)
10647 new_id_str[12] = '\0';
10649 err = get_short_logmsg(&logmsg, 42, commit);
10650 if (err)
10651 goto done;
10653 printf("%s -> %s: %s\n", old_id_str,
10654 new_id_str ? new_id_str : "no-op change", logmsg);
10655 done:
10656 free(old_id_str);
10657 free(new_id_str);
10658 free(logmsg);
10659 return err;
10662 static const struct got_error *
10663 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10664 struct got_reference *branch, struct got_reference *tmp_branch,
10665 struct got_repository *repo, int create_backup)
10667 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10668 return got_worktree_rebase_complete(worktree, fileindex,
10669 tmp_branch, branch, repo, create_backup);
10672 static const struct got_error *
10673 rebase_commit(struct got_pathlist_head *merged_paths,
10674 struct got_worktree *worktree, struct got_fileindex *fileindex,
10675 struct got_reference *tmp_branch, const char *committer,
10676 struct got_object_id *commit_id, int allow_conflict,
10677 struct got_repository *repo)
10679 const struct got_error *error;
10680 struct got_commit_object *commit;
10681 struct got_object_id *new_commit_id;
10683 error = got_object_open_as_commit(&commit, repo, commit_id);
10684 if (error)
10685 return error;
10687 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10688 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10689 allow_conflict, repo);
10690 if (error) {
10691 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10692 goto done;
10693 error = show_rebase_progress(commit, commit_id, NULL);
10694 } else {
10695 error = show_rebase_progress(commit, commit_id, new_commit_id);
10696 free(new_commit_id);
10698 done:
10699 got_object_commit_close(commit);
10700 return error;
10703 struct check_path_prefix_arg {
10704 const char *path_prefix;
10705 size_t len;
10706 int errcode;
10709 static const struct got_error *
10710 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10711 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10712 struct got_object_id *id1, struct got_object_id *id2,
10713 const char *path1, const char *path2,
10714 mode_t mode1, mode_t mode2, struct got_repository *repo)
10716 struct check_path_prefix_arg *a = arg;
10718 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10719 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10720 return got_error(a->errcode);
10722 return NULL;
10725 static const struct got_error *
10726 check_path_prefix(struct got_object_id *parent_id,
10727 struct got_object_id *commit_id, const char *path_prefix,
10728 int errcode, struct got_repository *repo)
10730 const struct got_error *err;
10731 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10732 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10733 struct check_path_prefix_arg cpp_arg;
10735 if (got_path_is_root_dir(path_prefix))
10736 return NULL;
10738 err = got_object_open_as_commit(&commit, repo, commit_id);
10739 if (err)
10740 goto done;
10742 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10743 if (err)
10744 goto done;
10746 err = got_object_open_as_tree(&tree1, repo,
10747 got_object_commit_get_tree_id(parent_commit));
10748 if (err)
10749 goto done;
10751 err = got_object_open_as_tree(&tree2, repo,
10752 got_object_commit_get_tree_id(commit));
10753 if (err)
10754 goto done;
10756 cpp_arg.path_prefix = path_prefix;
10757 while (cpp_arg.path_prefix[0] == '/')
10758 cpp_arg.path_prefix++;
10759 cpp_arg.len = strlen(cpp_arg.path_prefix);
10760 cpp_arg.errcode = errcode;
10761 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10762 check_path_prefix_in_diff, &cpp_arg, 0);
10763 done:
10764 if (tree1)
10765 got_object_tree_close(tree1);
10766 if (tree2)
10767 got_object_tree_close(tree2);
10768 if (commit)
10769 got_object_commit_close(commit);
10770 if (parent_commit)
10771 got_object_commit_close(parent_commit);
10772 return err;
10775 static const struct got_error *
10776 collect_commits(struct got_object_id_queue *commits,
10777 struct got_object_id *initial_commit_id,
10778 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10779 const char *path_prefix, int path_prefix_errcode,
10780 struct got_repository *repo)
10782 const struct got_error *err = NULL;
10783 struct got_commit_graph *graph = NULL;
10784 struct got_object_id parent_id, commit_id;
10785 struct got_object_qid *qid;
10787 err = got_commit_graph_open(&graph, "/", 1);
10788 if (err)
10789 return err;
10791 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10792 check_cancelled, NULL);
10793 if (err)
10794 goto done;
10796 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10797 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10798 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10799 check_cancelled, NULL);
10800 if (err) {
10801 if (err->code == GOT_ERR_ITER_COMPLETED) {
10802 err = got_error_msg(GOT_ERR_ANCESTRY,
10803 "ran out of commits to rebase before "
10804 "youngest common ancestor commit has "
10805 "been reached?!?");
10807 goto done;
10808 } else {
10809 err = check_path_prefix(&parent_id, &commit_id,
10810 path_prefix, path_prefix_errcode, repo);
10811 if (err)
10812 goto done;
10814 err = got_object_qid_alloc(&qid, &commit_id);
10815 if (err)
10816 goto done;
10817 STAILQ_INSERT_HEAD(commits, qid, entry);
10819 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10822 done:
10823 got_commit_graph_close(graph);
10824 return err;
10827 static const struct got_error *
10828 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10830 const struct got_error *err = NULL;
10831 time_t committer_time;
10832 struct tm tm;
10833 char datebuf[11]; /* YYYY-MM-DD + NUL */
10834 char *author0 = NULL, *author, *smallerthan;
10835 char *logmsg0 = NULL, *logmsg, *newline;
10837 committer_time = got_object_commit_get_committer_time(commit);
10838 if (gmtime_r(&committer_time, &tm) == NULL)
10839 return got_error_from_errno("gmtime_r");
10840 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10841 return got_error(GOT_ERR_NO_SPACE);
10843 author0 = strdup(got_object_commit_get_author(commit));
10844 if (author0 == NULL)
10845 return got_error_from_errno("strdup");
10846 author = author0;
10847 smallerthan = strchr(author, '<');
10848 if (smallerthan && smallerthan[1] != '\0')
10849 author = smallerthan + 1;
10850 author[strcspn(author, "@>")] = '\0';
10852 err = got_object_commit_get_logmsg(&logmsg0, commit);
10853 if (err)
10854 goto done;
10855 logmsg = logmsg0;
10856 while (*logmsg == '\n')
10857 logmsg++;
10858 newline = strchr(logmsg, '\n');
10859 if (newline)
10860 *newline = '\0';
10862 if (asprintf(brief_str, "%s %s %s",
10863 datebuf, author, logmsg) == -1)
10864 err = got_error_from_errno("asprintf");
10865 done:
10866 free(author0);
10867 free(logmsg0);
10868 return err;
10871 static const struct got_error *
10872 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10873 struct got_repository *repo)
10875 const struct got_error *err;
10876 char *id_str;
10878 err = got_object_id_str(&id_str, id);
10879 if (err)
10880 return err;
10882 err = got_ref_delete(ref, repo);
10883 if (err)
10884 goto done;
10886 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10887 done:
10888 free(id_str);
10889 return err;
10892 static const struct got_error *
10893 print_backup_ref(const char *branch_name, const char *new_id_str,
10894 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10895 struct got_reflist_object_id_map *refs_idmap,
10896 struct got_repository *repo)
10898 const struct got_error *err = NULL;
10899 struct got_reflist_head *refs;
10900 char *refs_str = NULL;
10901 struct got_object_id *new_commit_id = NULL;
10902 struct got_commit_object *new_commit = NULL;
10903 char *new_commit_brief_str = NULL;
10904 struct got_object_id *yca_id = NULL;
10905 struct got_commit_object *yca_commit = NULL;
10906 char *yca_id_str = NULL, *yca_brief_str = NULL;
10907 char *custom_refs_str;
10909 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10910 return got_error_from_errno("asprintf");
10912 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10913 0, 0, refs_idmap, custom_refs_str, NULL);
10914 if (err)
10915 goto done;
10917 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10918 if (err)
10919 goto done;
10921 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10922 if (refs) {
10923 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10924 if (err)
10925 goto done;
10928 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10929 if (err)
10930 goto done;
10932 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10933 if (err)
10934 goto done;
10936 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10937 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10938 if (err)
10939 goto done;
10941 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10942 refs_str ? " (" : "", refs_str ? refs_str : "",
10943 refs_str ? ")" : "", new_commit_brief_str);
10944 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10945 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10946 free(refs_str);
10947 refs_str = NULL;
10949 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10950 if (err)
10951 goto done;
10953 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10954 if (err)
10955 goto done;
10957 err = got_object_id_str(&yca_id_str, yca_id);
10958 if (err)
10959 goto done;
10961 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10962 if (refs) {
10963 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10964 if (err)
10965 goto done;
10967 printf("history forked at %s%s%s%s\n %s\n",
10968 yca_id_str,
10969 refs_str ? " (" : "", refs_str ? refs_str : "",
10970 refs_str ? ")" : "", yca_brief_str);
10972 done:
10973 free(custom_refs_str);
10974 free(new_commit_id);
10975 free(refs_str);
10976 free(yca_id);
10977 free(yca_id_str);
10978 free(yca_brief_str);
10979 if (new_commit)
10980 got_object_commit_close(new_commit);
10981 if (yca_commit)
10982 got_object_commit_close(yca_commit);
10984 return err;
10987 static const struct got_error *
10988 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10989 struct got_repository *repo)
10991 const struct got_error *err;
10992 struct got_reflist_head refs;
10993 struct got_reflist_entry *re;
10994 char *uuidstr = NULL;
10995 static char msg[160];
10997 TAILQ_INIT(&refs);
10999 err = got_worktree_get_uuid(&uuidstr, worktree);
11000 if (err)
11001 goto done;
11003 err = got_ref_list(&refs, repo, "refs/got/worktree",
11004 got_ref_cmp_by_name, repo);
11005 if (err)
11006 goto done;
11008 TAILQ_FOREACH(re, &refs, entry) {
11009 const char *cmd, *refname, *type;
11011 refname = got_ref_get_name(re->ref);
11013 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11014 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11015 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11016 cmd = "cherrypick";
11017 type = "cherrypicked";
11018 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11019 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11020 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11021 cmd = "backout";
11022 type = "backed-out";
11023 } else
11024 continue;
11026 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11027 continue;
11029 snprintf(msg, sizeof(msg),
11030 "work tree has references created by %s commits which "
11031 "must be removed with 'got %s -X' before running the %s "
11032 "command", type, cmd, caller);
11033 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11034 goto done;
11037 done:
11038 free(uuidstr);
11039 got_ref_list_free(&refs);
11040 return err;
11043 static const struct got_error *
11044 process_backup_refs(const char *backup_ref_prefix,
11045 const char *wanted_branch_name,
11046 int delete, struct got_repository *repo)
11048 const struct got_error *err;
11049 struct got_reflist_head refs, backup_refs;
11050 struct got_reflist_entry *re;
11051 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11052 struct got_object_id *old_commit_id = NULL;
11053 char *branch_name = NULL;
11054 struct got_commit_object *old_commit = NULL;
11055 struct got_reflist_object_id_map *refs_idmap = NULL;
11056 int wanted_branch_found = 0;
11058 TAILQ_INIT(&refs);
11059 TAILQ_INIT(&backup_refs);
11061 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11062 if (err)
11063 return err;
11065 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11066 if (err)
11067 goto done;
11069 if (wanted_branch_name) {
11070 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11071 wanted_branch_name += 11;
11074 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11075 got_ref_cmp_by_commit_timestamp_descending, repo);
11076 if (err)
11077 goto done;
11079 TAILQ_FOREACH(re, &backup_refs, entry) {
11080 const char *refname = got_ref_get_name(re->ref);
11081 char *slash;
11083 err = check_cancelled(NULL);
11084 if (err)
11085 break;
11087 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11088 if (err)
11089 break;
11091 err = got_object_open_as_commit(&old_commit, repo,
11092 old_commit_id);
11093 if (err)
11094 break;
11096 if (strncmp(backup_ref_prefix, refname,
11097 backup_ref_prefix_len) == 0)
11098 refname += backup_ref_prefix_len;
11100 while (refname[0] == '/')
11101 refname++;
11103 branch_name = strdup(refname);
11104 if (branch_name == NULL) {
11105 err = got_error_from_errno("strdup");
11106 break;
11108 slash = strrchr(branch_name, '/');
11109 if (slash) {
11110 *slash = '\0';
11111 refname += strlen(branch_name) + 1;
11114 if (wanted_branch_name == NULL ||
11115 strcmp(wanted_branch_name, branch_name) == 0) {
11116 wanted_branch_found = 1;
11117 if (delete) {
11118 err = delete_backup_ref(re->ref,
11119 old_commit_id, repo);
11120 } else {
11121 err = print_backup_ref(branch_name, refname,
11122 old_commit_id, old_commit, refs_idmap,
11123 repo);
11125 if (err)
11126 break;
11129 free(old_commit_id);
11130 old_commit_id = NULL;
11131 free(branch_name);
11132 branch_name = NULL;
11133 got_object_commit_close(old_commit);
11134 old_commit = NULL;
11137 if (wanted_branch_name && !wanted_branch_found) {
11138 err = got_error_fmt(GOT_ERR_NOT_REF,
11139 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11141 done:
11142 if (refs_idmap)
11143 got_reflist_object_id_map_free(refs_idmap);
11144 got_ref_list_free(&refs);
11145 got_ref_list_free(&backup_refs);
11146 free(old_commit_id);
11147 free(branch_name);
11148 if (old_commit)
11149 got_object_commit_close(old_commit);
11150 return err;
11153 static const struct got_error *
11154 abort_progress(void *arg, unsigned char status, const char *path)
11157 * Unversioned files should not clutter progress output when
11158 * an operation is aborted.
11160 if (status == GOT_STATUS_UNVERSIONED)
11161 return NULL;
11163 return update_progress(arg, status, path);
11166 static const struct got_error *
11167 cmd_rebase(int argc, char *argv[])
11169 const struct got_error *error = NULL;
11170 struct got_worktree *worktree = NULL;
11171 struct got_repository *repo = NULL;
11172 struct got_fileindex *fileindex = NULL;
11173 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11174 struct got_reference *branch = NULL;
11175 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11176 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11177 struct got_object_id *resume_commit_id = NULL;
11178 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11179 struct got_object_id *head_commit_id = NULL;
11180 struct got_reference *head_ref = NULL;
11181 struct got_commit_object *commit = NULL;
11182 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11183 int histedit_in_progress = 0, merge_in_progress = 0;
11184 int create_backup = 1, list_backups = 0, delete_backups = 0;
11185 int allow_conflict = 0;
11186 struct got_object_id_queue commits;
11187 struct got_pathlist_head merged_paths;
11188 const struct got_object_id_queue *parent_ids;
11189 struct got_object_qid *qid, *pid;
11190 struct got_update_progress_arg upa;
11191 int *pack_fds = NULL;
11193 STAILQ_INIT(&commits);
11194 TAILQ_INIT(&merged_paths);
11195 memset(&upa, 0, sizeof(upa));
11197 #ifndef PROFILE
11198 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11199 "unveil", NULL) == -1)
11200 err(1, "pledge");
11201 #endif
11203 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11204 switch (ch) {
11205 case 'a':
11206 abort_rebase = 1;
11207 break;
11208 case 'C':
11209 allow_conflict = 1;
11210 break;
11211 case 'c':
11212 continue_rebase = 1;
11213 break;
11214 case 'l':
11215 list_backups = 1;
11216 break;
11217 case 'X':
11218 delete_backups = 1;
11219 break;
11220 default:
11221 usage_rebase();
11222 /* NOTREACHED */
11226 argc -= optind;
11227 argv += optind;
11229 if (list_backups) {
11230 if (abort_rebase)
11231 option_conflict('l', 'a');
11232 if (allow_conflict)
11233 option_conflict('l', 'C');
11234 if (continue_rebase)
11235 option_conflict('l', 'c');
11236 if (delete_backups)
11237 option_conflict('l', 'X');
11238 if (argc != 0 && argc != 1)
11239 usage_rebase();
11240 } else if (delete_backups) {
11241 if (abort_rebase)
11242 option_conflict('X', 'a');
11243 if (allow_conflict)
11244 option_conflict('X', 'C');
11245 if (continue_rebase)
11246 option_conflict('X', 'c');
11247 if (list_backups)
11248 option_conflict('l', 'X');
11249 if (argc != 0 && argc != 1)
11250 usage_rebase();
11251 } else if (allow_conflict) {
11252 if (abort_rebase)
11253 option_conflict('C', 'a');
11254 if (!continue_rebase)
11255 errx(1, "-C option requires -c");
11256 } else {
11257 if (abort_rebase && continue_rebase)
11258 usage_rebase();
11259 else if (abort_rebase || continue_rebase) {
11260 if (argc != 0)
11261 usage_rebase();
11262 } else if (argc != 1)
11263 usage_rebase();
11266 cwd = getcwd(NULL, 0);
11267 if (cwd == NULL) {
11268 error = got_error_from_errno("getcwd");
11269 goto done;
11272 error = got_repo_pack_fds_open(&pack_fds);
11273 if (error != NULL)
11274 goto done;
11276 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11277 if (error) {
11278 if (list_backups || delete_backups) {
11279 if (error->code != GOT_ERR_NOT_WORKTREE)
11280 goto done;
11281 } else {
11282 if (error->code == GOT_ERR_NOT_WORKTREE)
11283 error = wrap_not_worktree_error(error,
11284 "rebase", cwd);
11285 goto done;
11289 error = get_gitconfig_path(&gitconfig_path);
11290 if (error)
11291 goto done;
11292 error = got_repo_open(&repo,
11293 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11294 gitconfig_path, pack_fds);
11295 if (error != NULL)
11296 goto done;
11298 if (worktree != NULL && !list_backups && !delete_backups) {
11299 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11300 if (error)
11301 goto done;
11304 error = get_author(&committer, repo, worktree);
11305 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11306 goto done;
11308 error = apply_unveil(got_repo_get_path(repo), 0,
11309 worktree ? got_worktree_get_root_path(worktree) : NULL);
11310 if (error)
11311 goto done;
11313 if (list_backups || delete_backups) {
11314 error = process_backup_refs(
11315 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11316 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11317 goto done; /* nothing else to do */
11320 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11321 worktree);
11322 if (error)
11323 goto done;
11324 if (histedit_in_progress) {
11325 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11326 goto done;
11329 error = got_worktree_merge_in_progress(&merge_in_progress,
11330 worktree, repo);
11331 if (error)
11332 goto done;
11333 if (merge_in_progress) {
11334 error = got_error(GOT_ERR_MERGE_BUSY);
11335 goto done;
11338 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11339 if (error)
11340 goto done;
11342 if (abort_rebase) {
11343 if (!rebase_in_progress) {
11344 error = got_error(GOT_ERR_NOT_REBASING);
11345 goto done;
11347 error = got_worktree_rebase_continue(&resume_commit_id,
11348 &new_base_branch, &tmp_branch, &branch, &fileindex,
11349 worktree, repo);
11350 if (error)
11351 goto done;
11352 printf("Switching work tree to %s\n",
11353 got_ref_get_symref_target(new_base_branch));
11354 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11355 new_base_branch, abort_progress, &upa);
11356 if (error)
11357 goto done;
11358 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11359 print_merge_progress_stats(&upa);
11360 goto done; /* nothing else to do */
11363 if (continue_rebase) {
11364 if (!rebase_in_progress) {
11365 error = got_error(GOT_ERR_NOT_REBASING);
11366 goto done;
11368 error = got_worktree_rebase_continue(&resume_commit_id,
11369 &new_base_branch, &tmp_branch, &branch, &fileindex,
11370 worktree, repo);
11371 if (error)
11372 goto done;
11374 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11375 committer, resume_commit_id, allow_conflict, repo);
11376 if (error)
11377 goto done;
11379 yca_id = got_object_id_dup(resume_commit_id);
11380 if (yca_id == NULL) {
11381 error = got_error_from_errno("got_object_id_dup");
11382 goto done;
11384 } else {
11385 error = got_ref_open(&branch, repo, argv[0], 0);
11386 if (error != NULL)
11387 goto done;
11388 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11389 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11390 "will not rebase a branch which lives outside "
11391 "the \"refs/heads/\" reference namespace");
11392 goto done;
11396 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11397 if (error)
11398 goto done;
11400 if (!continue_rebase) {
11401 struct got_object_id *base_commit_id;
11403 error = got_ref_open(&head_ref, repo,
11404 got_worktree_get_head_ref_name(worktree), 0);
11405 if (error)
11406 goto done;
11407 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11408 if (error)
11409 goto done;
11410 base_commit_id = got_worktree_get_base_commit_id(worktree);
11411 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11412 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11413 goto done;
11416 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11417 base_commit_id, branch_head_commit_id, 1, repo,
11418 check_cancelled, NULL);
11419 if (error) {
11420 if (error->code == GOT_ERR_ANCESTRY) {
11421 error = got_error_msg(GOT_ERR_ANCESTRY,
11422 "specified branch shares no common "
11423 "ancestry with work tree's branch");
11425 goto done;
11428 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11429 struct got_pathlist_head paths;
11430 printf("%s is already based on %s\n",
11431 got_ref_get_name(branch),
11432 got_worktree_get_head_ref_name(worktree));
11433 error = switch_head_ref(branch, branch_head_commit_id,
11434 worktree, repo);
11435 if (error)
11436 goto done;
11437 error = got_worktree_set_base_commit_id(worktree, repo,
11438 branch_head_commit_id);
11439 if (error)
11440 goto done;
11441 TAILQ_INIT(&paths);
11442 error = got_pathlist_append(&paths, "", NULL);
11443 if (error)
11444 goto done;
11445 error = got_worktree_checkout_files(worktree,
11446 &paths, repo, update_progress, &upa,
11447 check_cancelled, NULL);
11448 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11449 if (error)
11450 goto done;
11451 if (upa.did_something) {
11452 char *id_str;
11453 error = got_object_id_str(&id_str,
11454 branch_head_commit_id);
11455 if (error)
11456 goto done;
11457 printf("Updated to %s: %s\n",
11458 got_worktree_get_head_ref_name(worktree),
11459 id_str);
11460 free(id_str);
11461 } else
11462 printf("Already up-to-date\n");
11463 print_update_progress_stats(&upa);
11464 goto done;
11468 commit_id = branch_head_commit_id;
11469 error = got_object_open_as_commit(&commit, repo, commit_id);
11470 if (error)
11471 goto done;
11473 parent_ids = got_object_commit_get_parent_ids(commit);
11474 pid = STAILQ_FIRST(parent_ids);
11475 if (pid) {
11476 error = collect_commits(&commits, commit_id, &pid->id,
11477 yca_id, got_worktree_get_path_prefix(worktree),
11478 GOT_ERR_REBASE_PATH, repo);
11479 if (error)
11480 goto done;
11483 got_object_commit_close(commit);
11484 commit = NULL;
11486 if (!continue_rebase) {
11487 error = got_worktree_rebase_prepare(&new_base_branch,
11488 &tmp_branch, &fileindex, worktree, branch, repo);
11489 if (error)
11490 goto done;
11493 if (STAILQ_EMPTY(&commits)) {
11494 if (continue_rebase) {
11495 error = rebase_complete(worktree, fileindex,
11496 branch, tmp_branch, repo, create_backup);
11497 goto done;
11498 } else {
11499 /* Fast-forward the reference of the branch. */
11500 struct got_object_id *new_head_commit_id;
11501 char *id_str;
11502 error = got_ref_resolve(&new_head_commit_id, repo,
11503 new_base_branch);
11504 if (error)
11505 goto done;
11506 error = got_object_id_str(&id_str, new_head_commit_id);
11507 if (error)
11508 goto done;
11509 printf("Forwarding %s to commit %s\n",
11510 got_ref_get_name(branch), id_str);
11511 free(id_str);
11512 error = got_ref_change_ref(branch,
11513 new_head_commit_id);
11514 if (error)
11515 goto done;
11516 /* No backup needed since objects did not change. */
11517 create_backup = 0;
11521 pid = NULL;
11522 STAILQ_FOREACH(qid, &commits, entry) {
11524 commit_id = &qid->id;
11525 parent_id = pid ? &pid->id : yca_id;
11526 pid = qid;
11528 memset(&upa, 0, sizeof(upa));
11529 error = got_worktree_rebase_merge_files(&merged_paths,
11530 worktree, fileindex, parent_id, commit_id, repo,
11531 update_progress, &upa, check_cancelled, NULL);
11532 if (error)
11533 goto done;
11535 print_merge_progress_stats(&upa);
11536 if (upa.conflicts > 0 || upa.missing > 0 ||
11537 upa.not_deleted > 0 || upa.unversioned > 0) {
11538 if (upa.conflicts > 0) {
11539 error = show_rebase_merge_conflict(&qid->id,
11540 repo);
11541 if (error)
11542 goto done;
11544 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11545 break;
11548 error = rebase_commit(&merged_paths, worktree, fileindex,
11549 tmp_branch, committer, commit_id, 0, repo);
11550 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11551 if (error)
11552 goto done;
11555 if (upa.conflicts > 0 || upa.missing > 0 ||
11556 upa.not_deleted > 0 || upa.unversioned > 0) {
11557 error = got_worktree_rebase_postpone(worktree, fileindex);
11558 if (error)
11559 goto done;
11560 if (upa.conflicts > 0 && upa.missing == 0 &&
11561 upa.not_deleted == 0 && upa.unversioned == 0) {
11562 error = got_error_msg(GOT_ERR_CONFLICTS,
11563 "conflicts must be resolved before rebasing "
11564 "can continue");
11565 } else if (upa.conflicts > 0) {
11566 error = got_error_msg(GOT_ERR_CONFLICTS,
11567 "conflicts must be resolved before rebasing "
11568 "can continue; changes destined for some "
11569 "files were not yet merged and should be "
11570 "merged manually if required before the "
11571 "rebase operation is continued");
11572 } else {
11573 error = got_error_msg(GOT_ERR_CONFLICTS,
11574 "changes destined for some files were not "
11575 "yet merged and should be merged manually "
11576 "if required before the rebase operation "
11577 "is continued");
11579 } else
11580 error = rebase_complete(worktree, fileindex, branch,
11581 tmp_branch, repo, create_backup);
11582 done:
11583 free(cwd);
11584 free(committer);
11585 free(gitconfig_path);
11586 got_object_id_queue_free(&commits);
11587 free(branch_head_commit_id);
11588 free(resume_commit_id);
11589 free(head_commit_id);
11590 free(yca_id);
11591 if (commit)
11592 got_object_commit_close(commit);
11593 if (branch)
11594 got_ref_close(branch);
11595 if (new_base_branch)
11596 got_ref_close(new_base_branch);
11597 if (tmp_branch)
11598 got_ref_close(tmp_branch);
11599 if (head_ref)
11600 got_ref_close(head_ref);
11601 if (worktree)
11602 got_worktree_close(worktree);
11603 if (repo) {
11604 const struct got_error *close_err = got_repo_close(repo);
11605 if (error == NULL)
11606 error = close_err;
11608 if (pack_fds) {
11609 const struct got_error *pack_err =
11610 got_repo_pack_fds_close(pack_fds);
11611 if (error == NULL)
11612 error = pack_err;
11614 return error;
11617 __dead static void
11618 usage_histedit(void)
11620 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11621 "[branch]\n", getprogname());
11622 exit(1);
11625 #define GOT_HISTEDIT_PICK 'p'
11626 #define GOT_HISTEDIT_EDIT 'e'
11627 #define GOT_HISTEDIT_FOLD 'f'
11628 #define GOT_HISTEDIT_DROP 'd'
11629 #define GOT_HISTEDIT_MESG 'm'
11631 static const struct got_histedit_cmd {
11632 unsigned char code;
11633 const char *name;
11634 const char *desc;
11635 } got_histedit_cmds[] = {
11636 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11637 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11638 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11639 "be used" },
11640 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11641 { GOT_HISTEDIT_MESG, "mesg",
11642 "single-line log message for commit above (open editor if empty)" },
11645 struct got_histedit_list_entry {
11646 TAILQ_ENTRY(got_histedit_list_entry) entry;
11647 struct got_object_id *commit_id;
11648 const struct got_histedit_cmd *cmd;
11649 char *logmsg;
11651 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11653 static const struct got_error *
11654 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11655 FILE *f, struct got_repository *repo)
11657 const struct got_error *err = NULL;
11658 char *logmsg = NULL, *id_str = NULL;
11659 struct got_commit_object *commit = NULL;
11660 int n;
11662 err = got_object_open_as_commit(&commit, repo, commit_id);
11663 if (err)
11664 goto done;
11666 err = get_short_logmsg(&logmsg, 34, commit);
11667 if (err)
11668 goto done;
11670 err = got_object_id_str(&id_str, commit_id);
11671 if (err)
11672 goto done;
11674 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11675 if (n < 0)
11676 err = got_ferror(f, GOT_ERR_IO);
11677 done:
11678 if (commit)
11679 got_object_commit_close(commit);
11680 free(id_str);
11681 free(logmsg);
11682 return err;
11685 static const struct got_error *
11686 histedit_write_commit_list(struct got_object_id_queue *commits,
11687 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11688 int edit_only, struct got_repository *repo)
11690 const struct got_error *err = NULL;
11691 struct got_object_qid *qid;
11692 const char *histedit_cmd = NULL;
11694 if (STAILQ_EMPTY(commits))
11695 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11697 STAILQ_FOREACH(qid, commits, entry) {
11698 histedit_cmd = got_histedit_cmds[0].name;
11699 if (drop_only)
11700 histedit_cmd = "drop";
11701 else if (edit_only)
11702 histedit_cmd = "edit";
11703 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11704 histedit_cmd = "fold";
11705 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11706 if (err)
11707 break;
11708 if (edit_logmsg_only) {
11709 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11710 if (n < 0) {
11711 err = got_ferror(f, GOT_ERR_IO);
11712 break;
11717 return err;
11720 static const struct got_error *
11721 write_cmd_list(FILE *f, const char *branch_name,
11722 struct got_object_id_queue *commits)
11724 const struct got_error *err = NULL;
11725 size_t i;
11726 int n;
11727 char *id_str;
11728 struct got_object_qid *qid;
11730 qid = STAILQ_FIRST(commits);
11731 err = got_object_id_str(&id_str, &qid->id);
11732 if (err)
11733 return err;
11735 n = fprintf(f,
11736 "# Editing the history of branch '%s' starting at\n"
11737 "# commit %s\n"
11738 "# Commits will be processed in order from top to "
11739 "bottom of this file.\n", branch_name, id_str);
11740 if (n < 0) {
11741 err = got_ferror(f, GOT_ERR_IO);
11742 goto done;
11745 n = fprintf(f, "# Available histedit commands:\n");
11746 if (n < 0) {
11747 err = got_ferror(f, GOT_ERR_IO);
11748 goto done;
11751 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11752 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11753 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11754 cmd->desc);
11755 if (n < 0) {
11756 err = got_ferror(f, GOT_ERR_IO);
11757 break;
11760 done:
11761 free(id_str);
11762 return err;
11765 static const struct got_error *
11766 histedit_syntax_error(int lineno)
11768 static char msg[42];
11769 int ret;
11771 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11772 lineno);
11773 if (ret < 0 || (size_t)ret >= sizeof(msg))
11774 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11776 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11779 static const struct got_error *
11780 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11781 char *logmsg, struct got_repository *repo)
11783 const struct got_error *err;
11784 struct got_commit_object *folded_commit = NULL;
11785 char *id_str, *folded_logmsg = NULL;
11787 err = got_object_id_str(&id_str, hle->commit_id);
11788 if (err)
11789 return err;
11791 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11792 if (err)
11793 goto done;
11795 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11796 if (err)
11797 goto done;
11798 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11799 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11800 folded_logmsg) == -1) {
11801 err = got_error_from_errno("asprintf");
11803 done:
11804 if (folded_commit)
11805 got_object_commit_close(folded_commit);
11806 free(id_str);
11807 free(folded_logmsg);
11808 return err;
11811 static struct got_histedit_list_entry *
11812 get_folded_commits(struct got_histedit_list_entry *hle)
11814 struct got_histedit_list_entry *prev, *folded = NULL;
11816 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11817 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11818 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11819 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11820 folded = prev;
11821 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11824 return folded;
11827 static const struct got_error *
11828 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11829 struct got_repository *repo)
11831 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11832 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11833 const struct got_error *err = NULL;
11834 struct got_commit_object *commit = NULL;
11835 int logmsg_len;
11836 int fd = -1;
11837 struct got_histedit_list_entry *folded = NULL;
11839 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11840 if (err)
11841 return err;
11843 folded = get_folded_commits(hle);
11844 if (folded) {
11845 while (folded != hle) {
11846 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11847 folded = TAILQ_NEXT(folded, entry);
11848 continue;
11850 err = append_folded_commit_msg(&new_msg, folded,
11851 logmsg, repo);
11852 if (err)
11853 goto done;
11854 free(logmsg);
11855 logmsg = new_msg;
11856 folded = TAILQ_NEXT(folded, entry);
11860 err = got_object_id_str(&id_str, hle->commit_id);
11861 if (err)
11862 goto done;
11863 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11864 if (err)
11865 goto done;
11866 logmsg_len = asprintf(&new_msg,
11867 "%s\n# original log message of commit %s: %s",
11868 logmsg ? logmsg : "", id_str, orig_logmsg);
11869 if (logmsg_len == -1) {
11870 err = got_error_from_errno("asprintf");
11871 goto done;
11873 free(logmsg);
11874 logmsg = new_msg;
11876 err = got_object_id_str(&id_str, hle->commit_id);
11877 if (err)
11878 goto done;
11880 err = got_opentemp_named_fd(&logmsg_path, &fd,
11881 GOT_TMPDIR_STR "/got-logmsg", "");
11882 if (err)
11883 goto done;
11885 if (write(fd, logmsg, logmsg_len) == -1) {
11886 err = got_error_from_errno2("write", logmsg_path);
11887 goto done;
11889 if (close(fd) == -1) {
11890 err = got_error_from_errno2("close", logmsg_path);
11891 goto done;
11893 fd = -1;
11895 err = get_editor(&editor);
11896 if (err)
11897 goto done;
11899 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11900 logmsg_len, 0);
11901 if (err) {
11902 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11903 goto done;
11904 err = NULL;
11905 hle->logmsg = strdup(new_msg);
11906 if (hle->logmsg == NULL)
11907 err = got_error_from_errno("strdup");
11909 done:
11910 if (fd != -1 && close(fd) == -1 && err == NULL)
11911 err = got_error_from_errno2("close", logmsg_path);
11912 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11913 err = got_error_from_errno2("unlink", logmsg_path);
11914 free(logmsg_path);
11915 free(logmsg);
11916 free(orig_logmsg);
11917 free(editor);
11918 if (commit)
11919 got_object_commit_close(commit);
11920 return err;
11923 static const struct got_error *
11924 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11925 FILE *f, struct got_repository *repo)
11927 const struct got_error *err = NULL;
11928 char *line = NULL, *p, *end;
11929 size_t i, linesize = 0;
11930 ssize_t linelen;
11931 int lineno = 0, lastcmd = -1;
11932 const struct got_histedit_cmd *cmd;
11933 struct got_object_id *commit_id = NULL;
11934 struct got_histedit_list_entry *hle = NULL;
11936 for (;;) {
11937 linelen = getline(&line, &linesize, f);
11938 if (linelen == -1) {
11939 const struct got_error *getline_err;
11940 if (feof(f))
11941 break;
11942 getline_err = got_error_from_errno("getline");
11943 err = got_ferror(f, getline_err->code);
11944 break;
11946 lineno++;
11947 p = line;
11948 while (isspace((unsigned char)p[0]))
11949 p++;
11950 if (p[0] == '#' || p[0] == '\0')
11951 continue;
11952 cmd = NULL;
11953 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11954 cmd = &got_histedit_cmds[i];
11955 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11956 isspace((unsigned char)p[strlen(cmd->name)])) {
11957 p += strlen(cmd->name);
11958 break;
11960 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11961 p++;
11962 break;
11965 if (i == nitems(got_histedit_cmds)) {
11966 err = histedit_syntax_error(lineno);
11967 break;
11969 while (isspace((unsigned char)p[0]))
11970 p++;
11971 if (cmd->code == GOT_HISTEDIT_MESG) {
11972 if (lastcmd != GOT_HISTEDIT_PICK &&
11973 lastcmd != GOT_HISTEDIT_EDIT) {
11974 err = got_error(GOT_ERR_HISTEDIT_CMD);
11975 break;
11977 if (p[0] == '\0') {
11978 err = histedit_edit_logmsg(hle, repo);
11979 if (err)
11980 break;
11981 } else {
11982 hle->logmsg = strdup(p);
11983 if (hle->logmsg == NULL) {
11984 err = got_error_from_errno("strdup");
11985 break;
11988 lastcmd = cmd->code;
11989 continue;
11990 } else {
11991 end = p;
11992 while (end[0] && !isspace((unsigned char)end[0]))
11993 end++;
11994 *end = '\0';
11996 err = got_object_resolve_id_str(&commit_id, repo, p);
11997 if (err) {
11998 /* override error code */
11999 err = histedit_syntax_error(lineno);
12000 break;
12003 hle = malloc(sizeof(*hle));
12004 if (hle == NULL) {
12005 err = got_error_from_errno("malloc");
12006 break;
12008 hle->cmd = cmd;
12009 hle->commit_id = commit_id;
12010 hle->logmsg = NULL;
12011 commit_id = NULL;
12012 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12013 lastcmd = cmd->code;
12016 free(line);
12017 free(commit_id);
12018 return err;
12021 static const struct got_error *
12022 histedit_check_script(struct got_histedit_list *histedit_cmds,
12023 struct got_object_id_queue *commits, struct got_repository *repo)
12025 const struct got_error *err = NULL;
12026 struct got_object_qid *qid;
12027 struct got_histedit_list_entry *hle;
12028 static char msg[92];
12029 char *id_str;
12031 if (TAILQ_EMPTY(histedit_cmds))
12032 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12033 "histedit script contains no commands");
12034 if (STAILQ_EMPTY(commits))
12035 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12037 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12038 struct got_histedit_list_entry *hle2;
12039 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12040 if (hle == hle2)
12041 continue;
12042 if (got_object_id_cmp(hle->commit_id,
12043 hle2->commit_id) != 0)
12044 continue;
12045 err = got_object_id_str(&id_str, hle->commit_id);
12046 if (err)
12047 return err;
12048 snprintf(msg, sizeof(msg), "commit %s is listed "
12049 "more than once in histedit script", id_str);
12050 free(id_str);
12051 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12055 STAILQ_FOREACH(qid, commits, entry) {
12056 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12057 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12058 break;
12060 if (hle == NULL) {
12061 err = got_object_id_str(&id_str, &qid->id);
12062 if (err)
12063 return err;
12064 snprintf(msg, sizeof(msg),
12065 "commit %s missing from histedit script", id_str);
12066 free(id_str);
12067 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12071 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12072 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12073 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12074 "last commit in histedit script cannot be folded");
12076 return NULL;
12079 static const struct got_error *
12080 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12081 const char *path, struct got_object_id_queue *commits,
12082 struct got_repository *repo)
12084 const struct got_error *err = NULL;
12085 struct stat st, st2;
12086 struct timespec timeout;
12087 char *editor;
12088 FILE *f = NULL;
12090 err = get_editor(&editor);
12091 if (err)
12092 return err;
12094 if (stat(path, &st) == -1) {
12095 err = got_error_from_errno2("stat", path);
12096 goto done;
12099 if (spawn_editor(editor, path) == -1) {
12100 err = got_error_from_errno("failed spawning editor");
12101 goto done;
12104 timeout.tv_sec = 0;
12105 timeout.tv_nsec = 1;
12106 nanosleep(&timeout, NULL);
12108 if (stat(path, &st2) == -1) {
12109 err = got_error_from_errno2("stat", path);
12110 goto done;
12113 if (st.st_size == st2.st_size &&
12114 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12115 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12116 "no changes made to histedit script, aborting");
12117 goto done;
12120 f = fopen(path, "re");
12121 if (f == NULL) {
12122 err = got_error_from_errno("fopen");
12123 goto done;
12125 err = histedit_parse_list(histedit_cmds, f, repo);
12126 if (err)
12127 goto done;
12129 err = histedit_check_script(histedit_cmds, commits, repo);
12130 done:
12131 if (f && fclose(f) == EOF && err == NULL)
12132 err = got_error_from_errno("fclose");
12133 free(editor);
12134 return err;
12137 static const struct got_error *
12138 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12139 struct got_object_id_queue *, const char *, const char *,
12140 struct got_repository *);
12142 static const struct got_error *
12143 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12144 struct got_object_id_queue *commits, const char *branch_name,
12145 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12146 struct got_repository *repo)
12148 const struct got_error *err;
12149 FILE *f = NULL;
12150 char *path = NULL;
12152 err = got_opentemp_named(&path, &f, "got-histedit", "");
12153 if (err)
12154 return err;
12156 err = write_cmd_list(f, branch_name, commits);
12157 if (err)
12158 goto done;
12160 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12161 fold_only, drop_only, edit_only, repo);
12162 if (err)
12163 goto done;
12165 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12166 rewind(f);
12167 err = histedit_parse_list(histedit_cmds, f, repo);
12168 } else {
12169 if (fclose(f) == EOF) {
12170 err = got_error_from_errno("fclose");
12171 goto done;
12173 f = NULL;
12174 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12175 if (err) {
12176 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12177 err->code != GOT_ERR_HISTEDIT_CMD)
12178 goto done;
12179 err = histedit_edit_list_retry(histedit_cmds, err,
12180 commits, path, branch_name, repo);
12183 done:
12184 if (f && fclose(f) == EOF && err == NULL)
12185 err = got_error_from_errno("fclose");
12186 if (path && unlink(path) != 0 && err == NULL)
12187 err = got_error_from_errno2("unlink", path);
12188 free(path);
12189 return err;
12192 static const struct got_error *
12193 histedit_save_list(struct got_histedit_list *histedit_cmds,
12194 struct got_worktree *worktree, struct got_repository *repo)
12196 const struct got_error *err = NULL;
12197 char *path = NULL;
12198 FILE *f = NULL;
12199 struct got_histedit_list_entry *hle;
12200 struct got_commit_object *commit = NULL;
12202 err = got_worktree_get_histedit_script_path(&path, worktree);
12203 if (err)
12204 return err;
12206 f = fopen(path, "we");
12207 if (f == NULL) {
12208 err = got_error_from_errno2("fopen", path);
12209 goto done;
12211 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12212 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12213 repo);
12214 if (err)
12215 break;
12217 if (hle->logmsg) {
12218 int n = fprintf(f, "%c %s\n",
12219 GOT_HISTEDIT_MESG, hle->logmsg);
12220 if (n < 0) {
12221 err = got_ferror(f, GOT_ERR_IO);
12222 break;
12226 done:
12227 if (f && fclose(f) == EOF && err == NULL)
12228 err = got_error_from_errno("fclose");
12229 free(path);
12230 if (commit)
12231 got_object_commit_close(commit);
12232 return err;
12235 static void
12236 histedit_free_list(struct got_histedit_list *histedit_cmds)
12238 struct got_histedit_list_entry *hle;
12240 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12241 TAILQ_REMOVE(histedit_cmds, hle, entry);
12242 free(hle);
12246 static const struct got_error *
12247 histedit_load_list(struct got_histedit_list *histedit_cmds,
12248 const char *path, struct got_repository *repo)
12250 const struct got_error *err = NULL;
12251 FILE *f = NULL;
12253 f = fopen(path, "re");
12254 if (f == NULL) {
12255 err = got_error_from_errno2("fopen", path);
12256 goto done;
12259 err = histedit_parse_list(histedit_cmds, f, repo);
12260 done:
12261 if (f && fclose(f) == EOF && err == NULL)
12262 err = got_error_from_errno("fclose");
12263 return err;
12266 static const struct got_error *
12267 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12268 const struct got_error *edit_err, struct got_object_id_queue *commits,
12269 const char *path, const char *branch_name, struct got_repository *repo)
12271 const struct got_error *err = NULL, *prev_err = edit_err;
12272 int resp = ' ';
12274 while (resp != 'c' && resp != 'r' && resp != 'a') {
12275 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12276 "or (a)bort: ", getprogname(), prev_err->msg);
12277 resp = getchar();
12278 if (resp == '\n')
12279 resp = getchar();
12280 if (resp == 'c') {
12281 histedit_free_list(histedit_cmds);
12282 err = histedit_run_editor(histedit_cmds, path, commits,
12283 repo);
12284 if (err) {
12285 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12286 err->code != GOT_ERR_HISTEDIT_CMD)
12287 break;
12288 prev_err = err;
12289 resp = ' ';
12290 continue;
12292 break;
12293 } else if (resp == 'r') {
12294 histedit_free_list(histedit_cmds);
12295 err = histedit_edit_script(histedit_cmds,
12296 commits, branch_name, 0, 0, 0, 0, repo);
12297 if (err) {
12298 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12299 err->code != GOT_ERR_HISTEDIT_CMD)
12300 break;
12301 prev_err = err;
12302 resp = ' ';
12303 continue;
12305 break;
12306 } else if (resp == 'a') {
12307 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12308 break;
12309 } else
12310 printf("invalid response '%c'\n", resp);
12313 return err;
12316 static const struct got_error *
12317 histedit_complete(struct got_worktree *worktree,
12318 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12319 struct got_reference *branch, struct got_repository *repo)
12321 printf("Switching work tree to %s\n",
12322 got_ref_get_symref_target(branch));
12323 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12324 branch, repo);
12327 static const struct got_error *
12328 show_histedit_progress(struct got_commit_object *commit,
12329 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12331 const struct got_error *err;
12332 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12334 err = got_object_id_str(&old_id_str, hle->commit_id);
12335 if (err)
12336 goto done;
12338 if (new_id) {
12339 err = got_object_id_str(&new_id_str, new_id);
12340 if (err)
12341 goto done;
12344 old_id_str[12] = '\0';
12345 if (new_id_str)
12346 new_id_str[12] = '\0';
12348 if (hle->logmsg) {
12349 logmsg = strdup(hle->logmsg);
12350 if (logmsg == NULL) {
12351 err = got_error_from_errno("strdup");
12352 goto done;
12354 trim_logmsg(logmsg, 42);
12355 } else {
12356 err = get_short_logmsg(&logmsg, 42, commit);
12357 if (err)
12358 goto done;
12361 switch (hle->cmd->code) {
12362 case GOT_HISTEDIT_PICK:
12363 case GOT_HISTEDIT_EDIT:
12364 printf("%s -> %s: %s\n", old_id_str,
12365 new_id_str ? new_id_str : "no-op change", logmsg);
12366 break;
12367 case GOT_HISTEDIT_DROP:
12368 case GOT_HISTEDIT_FOLD:
12369 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12370 logmsg);
12371 break;
12372 default:
12373 break;
12375 done:
12376 free(old_id_str);
12377 free(new_id_str);
12378 return err;
12381 static const struct got_error *
12382 histedit_commit(struct got_pathlist_head *merged_paths,
12383 struct got_worktree *worktree, struct got_fileindex *fileindex,
12384 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12385 const char *committer, int allow_conflict, struct got_repository *repo)
12387 const struct got_error *err;
12388 struct got_commit_object *commit;
12389 struct got_object_id *new_commit_id;
12391 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12392 && hle->logmsg == NULL) {
12393 err = histedit_edit_logmsg(hle, repo);
12394 if (err)
12395 return err;
12398 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12399 if (err)
12400 return err;
12402 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12403 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12404 hle->logmsg, allow_conflict, repo);
12405 if (err) {
12406 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12407 goto done;
12408 err = show_histedit_progress(commit, hle, NULL);
12409 } else {
12410 err = show_histedit_progress(commit, hle, new_commit_id);
12411 free(new_commit_id);
12413 done:
12414 got_object_commit_close(commit);
12415 return err;
12418 static const struct got_error *
12419 histedit_skip_commit(struct got_histedit_list_entry *hle,
12420 struct got_worktree *worktree, struct got_repository *repo)
12422 const struct got_error *error;
12423 struct got_commit_object *commit;
12425 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12426 repo);
12427 if (error)
12428 return error;
12430 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12431 if (error)
12432 return error;
12434 error = show_histedit_progress(commit, hle, NULL);
12435 got_object_commit_close(commit);
12436 return error;
12439 static const struct got_error *
12440 check_local_changes(void *arg, unsigned char status,
12441 unsigned char staged_status, const char *path,
12442 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12443 struct got_object_id *commit_id, int dirfd, const char *de_name)
12445 int *have_local_changes = arg;
12447 switch (status) {
12448 case GOT_STATUS_ADD:
12449 case GOT_STATUS_DELETE:
12450 case GOT_STATUS_MODIFY:
12451 case GOT_STATUS_CONFLICT:
12452 *have_local_changes = 1;
12453 return got_error(GOT_ERR_CANCELLED);
12454 default:
12455 break;
12458 switch (staged_status) {
12459 case GOT_STATUS_ADD:
12460 case GOT_STATUS_DELETE:
12461 case GOT_STATUS_MODIFY:
12462 *have_local_changes = 1;
12463 return got_error(GOT_ERR_CANCELLED);
12464 default:
12465 break;
12468 return NULL;
12471 static const struct got_error *
12472 cmd_histedit(int argc, char *argv[])
12474 const struct got_error *error = NULL;
12475 struct got_worktree *worktree = NULL;
12476 struct got_fileindex *fileindex = NULL;
12477 struct got_repository *repo = NULL;
12478 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12479 struct got_reference *branch = NULL;
12480 struct got_reference *tmp_branch = NULL;
12481 struct got_object_id *resume_commit_id = NULL;
12482 struct got_object_id *base_commit_id = NULL;
12483 struct got_object_id *head_commit_id = NULL;
12484 struct got_commit_object *commit = NULL;
12485 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12486 struct got_update_progress_arg upa;
12487 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12488 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12489 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12490 const char *edit_script_path = NULL;
12491 struct got_object_id_queue commits;
12492 struct got_pathlist_head merged_paths;
12493 const struct got_object_id_queue *parent_ids;
12494 struct got_object_qid *pid;
12495 struct got_histedit_list histedit_cmds;
12496 struct got_histedit_list_entry *hle;
12497 int *pack_fds = NULL;
12499 STAILQ_INIT(&commits);
12500 TAILQ_INIT(&histedit_cmds);
12501 TAILQ_INIT(&merged_paths);
12502 memset(&upa, 0, sizeof(upa));
12504 #ifndef PROFILE
12505 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12506 "unveil", NULL) == -1)
12507 err(1, "pledge");
12508 #endif
12510 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12511 switch (ch) {
12512 case 'a':
12513 abort_edit = 1;
12514 break;
12515 case 'C':
12516 allow_conflict = 1;
12517 break;
12518 case 'c':
12519 continue_edit = 1;
12520 break;
12521 case 'd':
12522 drop_only = 1;
12523 break;
12524 case 'e':
12525 edit_only = 1;
12526 break;
12527 case 'F':
12528 edit_script_path = optarg;
12529 break;
12530 case 'f':
12531 fold_only = 1;
12532 break;
12533 case 'l':
12534 list_backups = 1;
12535 break;
12536 case 'm':
12537 edit_logmsg_only = 1;
12538 break;
12539 case 'X':
12540 delete_backups = 1;
12541 break;
12542 default:
12543 usage_histedit();
12544 /* NOTREACHED */
12548 argc -= optind;
12549 argv += optind;
12551 if (abort_edit && allow_conflict)
12552 option_conflict('a', 'C');
12553 if (abort_edit && continue_edit)
12554 option_conflict('a', 'c');
12555 if (edit_script_path && allow_conflict)
12556 option_conflict('F', 'C');
12557 if (edit_script_path && edit_logmsg_only)
12558 option_conflict('F', 'm');
12559 if (abort_edit && edit_logmsg_only)
12560 option_conflict('a', 'm');
12561 if (edit_logmsg_only && allow_conflict)
12562 option_conflict('m', 'C');
12563 if (continue_edit && edit_logmsg_only)
12564 option_conflict('c', 'm');
12565 if (abort_edit && fold_only)
12566 option_conflict('a', 'f');
12567 if (fold_only && allow_conflict)
12568 option_conflict('f', 'C');
12569 if (continue_edit && fold_only)
12570 option_conflict('c', 'f');
12571 if (fold_only && edit_logmsg_only)
12572 option_conflict('f', 'm');
12573 if (edit_script_path && fold_only)
12574 option_conflict('F', 'f');
12575 if (abort_edit && edit_only)
12576 option_conflict('a', 'e');
12577 if (continue_edit && edit_only)
12578 option_conflict('c', 'e');
12579 if (edit_only && edit_logmsg_only)
12580 option_conflict('e', 'm');
12581 if (edit_script_path && edit_only)
12582 option_conflict('F', 'e');
12583 if (fold_only && edit_only)
12584 option_conflict('f', 'e');
12585 if (drop_only && abort_edit)
12586 option_conflict('d', 'a');
12587 if (drop_only && allow_conflict)
12588 option_conflict('d', 'C');
12589 if (drop_only && continue_edit)
12590 option_conflict('d', 'c');
12591 if (drop_only && edit_logmsg_only)
12592 option_conflict('d', 'm');
12593 if (drop_only && edit_only)
12594 option_conflict('d', 'e');
12595 if (drop_only && edit_script_path)
12596 option_conflict('d', 'F');
12597 if (drop_only && fold_only)
12598 option_conflict('d', 'f');
12599 if (list_backups) {
12600 if (abort_edit)
12601 option_conflict('l', 'a');
12602 if (allow_conflict)
12603 option_conflict('l', 'C');
12604 if (continue_edit)
12605 option_conflict('l', 'c');
12606 if (edit_script_path)
12607 option_conflict('l', 'F');
12608 if (edit_logmsg_only)
12609 option_conflict('l', 'm');
12610 if (drop_only)
12611 option_conflict('l', 'd');
12612 if (fold_only)
12613 option_conflict('l', 'f');
12614 if (edit_only)
12615 option_conflict('l', 'e');
12616 if (delete_backups)
12617 option_conflict('l', 'X');
12618 if (argc != 0 && argc != 1)
12619 usage_histedit();
12620 } else if (delete_backups) {
12621 if (abort_edit)
12622 option_conflict('X', 'a');
12623 if (allow_conflict)
12624 option_conflict('X', 'C');
12625 if (continue_edit)
12626 option_conflict('X', 'c');
12627 if (drop_only)
12628 option_conflict('X', 'd');
12629 if (edit_script_path)
12630 option_conflict('X', 'F');
12631 if (edit_logmsg_only)
12632 option_conflict('X', 'm');
12633 if (fold_only)
12634 option_conflict('X', 'f');
12635 if (edit_only)
12636 option_conflict('X', 'e');
12637 if (list_backups)
12638 option_conflict('X', 'l');
12639 if (argc != 0 && argc != 1)
12640 usage_histedit();
12641 } else if (allow_conflict && !continue_edit)
12642 errx(1, "-C option requires -c");
12643 else if (argc != 0)
12644 usage_histedit();
12647 * This command cannot apply unveil(2) in all cases because the
12648 * user may choose to run an editor to edit the histedit script
12649 * and to edit individual commit log messages.
12650 * unveil(2) traverses exec(2); if an editor is used we have to
12651 * apply unveil after edit script and log messages have been written.
12652 * XXX TODO: Make use of unveil(2) where possible.
12655 cwd = getcwd(NULL, 0);
12656 if (cwd == NULL) {
12657 error = got_error_from_errno("getcwd");
12658 goto done;
12661 error = got_repo_pack_fds_open(&pack_fds);
12662 if (error != NULL)
12663 goto done;
12665 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12666 if (error) {
12667 if (list_backups || delete_backups) {
12668 if (error->code != GOT_ERR_NOT_WORKTREE)
12669 goto done;
12670 } else {
12671 if (error->code == GOT_ERR_NOT_WORKTREE)
12672 error = wrap_not_worktree_error(error,
12673 "histedit", cwd);
12674 goto done;
12678 if (list_backups || delete_backups) {
12679 error = got_repo_open(&repo,
12680 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12681 NULL, pack_fds);
12682 if (error != NULL)
12683 goto done;
12684 error = apply_unveil(got_repo_get_path(repo), 0,
12685 worktree ? got_worktree_get_root_path(worktree) : NULL);
12686 if (error)
12687 goto done;
12688 error = process_backup_refs(
12689 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12690 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12691 goto done; /* nothing else to do */
12694 error = get_gitconfig_path(&gitconfig_path);
12695 if (error)
12696 goto done;
12697 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12698 gitconfig_path, pack_fds);
12699 if (error != NULL)
12700 goto done;
12702 if (worktree != NULL && !list_backups && !delete_backups) {
12703 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12704 if (error)
12705 goto done;
12708 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12709 if (error)
12710 goto done;
12711 if (rebase_in_progress) {
12712 error = got_error(GOT_ERR_REBASING);
12713 goto done;
12716 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12717 repo);
12718 if (error)
12719 goto done;
12720 if (merge_in_progress) {
12721 error = got_error(GOT_ERR_MERGE_BUSY);
12722 goto done;
12725 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12726 if (error)
12727 goto done;
12729 if (edit_in_progress && edit_logmsg_only) {
12730 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12731 "histedit operation is in progress in this "
12732 "work tree and must be continued or aborted "
12733 "before the -m option can be used");
12734 goto done;
12736 if (edit_in_progress && drop_only) {
12737 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12738 "histedit operation is in progress in this "
12739 "work tree and must be continued or aborted "
12740 "before the -d option can be used");
12741 goto done;
12743 if (edit_in_progress && fold_only) {
12744 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12745 "histedit operation is in progress in this "
12746 "work tree and must be continued or aborted "
12747 "before the -f option can be used");
12748 goto done;
12750 if (edit_in_progress && edit_only) {
12751 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12752 "histedit operation is in progress in this "
12753 "work tree and must be continued or aborted "
12754 "before the -e option can be used");
12755 goto done;
12758 if (edit_in_progress && abort_edit) {
12759 error = got_worktree_histedit_continue(&resume_commit_id,
12760 &tmp_branch, &branch, &base_commit_id, &fileindex,
12761 worktree, repo);
12762 if (error)
12763 goto done;
12764 printf("Switching work tree to %s\n",
12765 got_ref_get_symref_target(branch));
12766 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12767 branch, base_commit_id, abort_progress, &upa);
12768 if (error)
12769 goto done;
12770 printf("Histedit of %s aborted\n",
12771 got_ref_get_symref_target(branch));
12772 print_merge_progress_stats(&upa);
12773 goto done; /* nothing else to do */
12774 } else if (abort_edit) {
12775 error = got_error(GOT_ERR_NOT_HISTEDIT);
12776 goto done;
12779 error = get_author(&committer, repo, worktree);
12780 if (error)
12781 goto done;
12783 if (continue_edit) {
12784 char *path;
12786 if (!edit_in_progress) {
12787 error = got_error(GOT_ERR_NOT_HISTEDIT);
12788 goto done;
12791 error = got_worktree_get_histedit_script_path(&path, worktree);
12792 if (error)
12793 goto done;
12795 error = histedit_load_list(&histedit_cmds, path, repo);
12796 free(path);
12797 if (error)
12798 goto done;
12800 error = got_worktree_histedit_continue(&resume_commit_id,
12801 &tmp_branch, &branch, &base_commit_id, &fileindex,
12802 worktree, repo);
12803 if (error)
12804 goto done;
12806 error = got_ref_resolve(&head_commit_id, repo, branch);
12807 if (error)
12808 goto done;
12810 error = got_object_open_as_commit(&commit, repo,
12811 head_commit_id);
12812 if (error)
12813 goto done;
12814 parent_ids = got_object_commit_get_parent_ids(commit);
12815 pid = STAILQ_FIRST(parent_ids);
12816 if (pid == NULL) {
12817 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12818 goto done;
12820 error = collect_commits(&commits, head_commit_id, &pid->id,
12821 base_commit_id, got_worktree_get_path_prefix(worktree),
12822 GOT_ERR_HISTEDIT_PATH, repo);
12823 got_object_commit_close(commit);
12824 commit = NULL;
12825 if (error)
12826 goto done;
12827 } else {
12828 if (edit_in_progress) {
12829 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12830 goto done;
12833 error = got_ref_open(&branch, repo,
12834 got_worktree_get_head_ref_name(worktree), 0);
12835 if (error != NULL)
12836 goto done;
12838 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12839 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12840 "will not edit commit history of a branch outside "
12841 "the \"refs/heads/\" reference namespace");
12842 goto done;
12845 error = got_ref_resolve(&head_commit_id, repo, branch);
12846 got_ref_close(branch);
12847 branch = NULL;
12848 if (error)
12849 goto done;
12851 error = got_object_open_as_commit(&commit, repo,
12852 head_commit_id);
12853 if (error)
12854 goto done;
12855 parent_ids = got_object_commit_get_parent_ids(commit);
12856 pid = STAILQ_FIRST(parent_ids);
12857 if (pid == NULL) {
12858 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12859 goto done;
12861 error = collect_commits(&commits, head_commit_id, &pid->id,
12862 got_worktree_get_base_commit_id(worktree),
12863 got_worktree_get_path_prefix(worktree),
12864 GOT_ERR_HISTEDIT_PATH, repo);
12865 got_object_commit_close(commit);
12866 commit = NULL;
12867 if (error)
12868 goto done;
12870 if (STAILQ_EMPTY(&commits)) {
12871 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12872 goto done;
12875 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12876 &base_commit_id, &fileindex, worktree, repo);
12877 if (error)
12878 goto done;
12880 if (edit_script_path) {
12881 error = histedit_load_list(&histedit_cmds,
12882 edit_script_path, repo);
12883 if (error) {
12884 got_worktree_histedit_abort(worktree, fileindex,
12885 repo, branch, base_commit_id,
12886 abort_progress, &upa);
12887 print_merge_progress_stats(&upa);
12888 goto done;
12890 } else {
12891 const char *branch_name;
12892 branch_name = got_ref_get_symref_target(branch);
12893 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12894 branch_name += 11;
12895 error = histedit_edit_script(&histedit_cmds, &commits,
12896 branch_name, edit_logmsg_only, fold_only,
12897 drop_only, edit_only, repo);
12898 if (error) {
12899 got_worktree_histedit_abort(worktree, fileindex,
12900 repo, branch, base_commit_id,
12901 abort_progress, &upa);
12902 print_merge_progress_stats(&upa);
12903 goto done;
12908 error = histedit_save_list(&histedit_cmds, worktree,
12909 repo);
12910 if (error) {
12911 got_worktree_histedit_abort(worktree, fileindex,
12912 repo, branch, base_commit_id,
12913 abort_progress, &upa);
12914 print_merge_progress_stats(&upa);
12915 goto done;
12920 error = histedit_check_script(&histedit_cmds, &commits, repo);
12921 if (error)
12922 goto done;
12924 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12925 if (resume_commit_id) {
12926 if (got_object_id_cmp(hle->commit_id,
12927 resume_commit_id) != 0)
12928 continue;
12930 resume_commit_id = NULL;
12931 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12932 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12933 error = histedit_skip_commit(hle, worktree,
12934 repo);
12935 if (error)
12936 goto done;
12937 } else {
12938 struct got_pathlist_head paths;
12939 int have_changes = 0;
12941 TAILQ_INIT(&paths);
12942 error = got_pathlist_append(&paths, "", NULL);
12943 if (error)
12944 goto done;
12945 error = got_worktree_status(worktree, &paths,
12946 repo, 0, check_local_changes, &have_changes,
12947 check_cancelled, NULL);
12948 got_pathlist_free(&paths,
12949 GOT_PATHLIST_FREE_NONE);
12950 if (error) {
12951 if (error->code != GOT_ERR_CANCELLED)
12952 goto done;
12953 if (sigint_received || sigpipe_received)
12954 goto done;
12956 if (have_changes) {
12957 error = histedit_commit(NULL, worktree,
12958 fileindex, tmp_branch, hle,
12959 committer, allow_conflict, repo);
12960 if (error)
12961 goto done;
12962 } else {
12963 error = got_object_open_as_commit(
12964 &commit, repo, hle->commit_id);
12965 if (error)
12966 goto done;
12967 error = show_histedit_progress(commit,
12968 hle, NULL);
12969 got_object_commit_close(commit);
12970 commit = NULL;
12971 if (error)
12972 goto done;
12975 continue;
12978 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12979 error = histedit_skip_commit(hle, worktree, repo);
12980 if (error)
12981 goto done;
12982 continue;
12985 error = got_object_open_as_commit(&commit, repo,
12986 hle->commit_id);
12987 if (error)
12988 goto done;
12989 parent_ids = got_object_commit_get_parent_ids(commit);
12990 pid = STAILQ_FIRST(parent_ids);
12992 error = got_worktree_histedit_merge_files(&merged_paths,
12993 worktree, fileindex, &pid->id, hle->commit_id, repo,
12994 update_progress, &upa, check_cancelled, NULL);
12995 if (error)
12996 goto done;
12997 got_object_commit_close(commit);
12998 commit = NULL;
13000 print_merge_progress_stats(&upa);
13001 if (upa.conflicts > 0 || upa.missing > 0 ||
13002 upa.not_deleted > 0 || upa.unversioned > 0) {
13003 if (upa.conflicts > 0) {
13004 error = show_rebase_merge_conflict(
13005 hle->commit_id, repo);
13006 if (error)
13007 goto done;
13009 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13010 break;
13013 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13014 char *id_str;
13015 error = got_object_id_str(&id_str, hle->commit_id);
13016 if (error)
13017 goto done;
13018 printf("Stopping histedit for amending commit %s\n",
13019 id_str);
13020 free(id_str);
13021 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13022 error = got_worktree_histedit_postpone(worktree,
13023 fileindex);
13024 goto done;
13027 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13028 error = histedit_skip_commit(hle, worktree, repo);
13029 if (error)
13030 goto done;
13031 continue;
13034 error = histedit_commit(&merged_paths, worktree, fileindex,
13035 tmp_branch, hle, committer, allow_conflict, repo);
13036 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13037 if (error)
13038 goto done;
13041 if (upa.conflicts > 0 || upa.missing > 0 ||
13042 upa.not_deleted > 0 || upa.unversioned > 0) {
13043 error = got_worktree_histedit_postpone(worktree, fileindex);
13044 if (error)
13045 goto done;
13046 if (upa.conflicts > 0 && upa.missing == 0 &&
13047 upa.not_deleted == 0 && upa.unversioned == 0) {
13048 error = got_error_msg(GOT_ERR_CONFLICTS,
13049 "conflicts must be resolved before histedit "
13050 "can continue");
13051 } else if (upa.conflicts > 0) {
13052 error = got_error_msg(GOT_ERR_CONFLICTS,
13053 "conflicts must be resolved before histedit "
13054 "can continue; changes destined for some "
13055 "files were not yet merged and should be "
13056 "merged manually if required before the "
13057 "histedit operation is continued");
13058 } else {
13059 error = got_error_msg(GOT_ERR_CONFLICTS,
13060 "changes destined for some files were not "
13061 "yet merged and should be merged manually "
13062 "if required before the histedit operation "
13063 "is continued");
13065 } else
13066 error = histedit_complete(worktree, fileindex, tmp_branch,
13067 branch, repo);
13068 done:
13069 free(cwd);
13070 free(committer);
13071 free(gitconfig_path);
13072 got_object_id_queue_free(&commits);
13073 histedit_free_list(&histedit_cmds);
13074 free(head_commit_id);
13075 free(base_commit_id);
13076 free(resume_commit_id);
13077 if (commit)
13078 got_object_commit_close(commit);
13079 if (branch)
13080 got_ref_close(branch);
13081 if (tmp_branch)
13082 got_ref_close(tmp_branch);
13083 if (worktree)
13084 got_worktree_close(worktree);
13085 if (repo) {
13086 const struct got_error *close_err = got_repo_close(repo);
13087 if (error == NULL)
13088 error = close_err;
13090 if (pack_fds) {
13091 const struct got_error *pack_err =
13092 got_repo_pack_fds_close(pack_fds);
13093 if (error == NULL)
13094 error = pack_err;
13096 return error;
13099 __dead static void
13100 usage_integrate(void)
13102 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13103 exit(1);
13106 static const struct got_error *
13107 cmd_integrate(int argc, char *argv[])
13109 const struct got_error *error = NULL;
13110 struct got_repository *repo = NULL;
13111 struct got_worktree *worktree = NULL;
13112 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13113 const char *branch_arg = NULL;
13114 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13115 struct got_fileindex *fileindex = NULL;
13116 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13117 int ch;
13118 struct got_update_progress_arg upa;
13119 int *pack_fds = NULL;
13121 #ifndef PROFILE
13122 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13123 "unveil", NULL) == -1)
13124 err(1, "pledge");
13125 #endif
13127 while ((ch = getopt(argc, argv, "")) != -1) {
13128 switch (ch) {
13129 default:
13130 usage_integrate();
13131 /* NOTREACHED */
13135 argc -= optind;
13136 argv += optind;
13138 if (argc != 1)
13139 usage_integrate();
13140 branch_arg = argv[0];
13142 cwd = getcwd(NULL, 0);
13143 if (cwd == NULL) {
13144 error = got_error_from_errno("getcwd");
13145 goto done;
13148 error = got_repo_pack_fds_open(&pack_fds);
13149 if (error != NULL)
13150 goto done;
13152 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13153 if (error) {
13154 if (error->code == GOT_ERR_NOT_WORKTREE)
13155 error = wrap_not_worktree_error(error, "integrate",
13156 cwd);
13157 goto done;
13160 error = check_rebase_or_histedit_in_progress(worktree);
13161 if (error)
13162 goto done;
13164 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13165 NULL, pack_fds);
13166 if (error != NULL)
13167 goto done;
13169 error = apply_unveil(got_repo_get_path(repo), 0,
13170 got_worktree_get_root_path(worktree));
13171 if (error)
13172 goto done;
13174 error = check_merge_in_progress(worktree, repo);
13175 if (error)
13176 goto done;
13178 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13179 error = got_error_from_errno("asprintf");
13180 goto done;
13183 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13184 &base_branch_ref, worktree, refname, repo);
13185 if (error)
13186 goto done;
13188 refname = strdup(got_ref_get_name(branch_ref));
13189 if (refname == NULL) {
13190 error = got_error_from_errno("strdup");
13191 got_worktree_integrate_abort(worktree, fileindex, repo,
13192 branch_ref, base_branch_ref);
13193 goto done;
13195 base_refname = strdup(got_ref_get_name(base_branch_ref));
13196 if (base_refname == NULL) {
13197 error = got_error_from_errno("strdup");
13198 got_worktree_integrate_abort(worktree, fileindex, repo,
13199 branch_ref, base_branch_ref);
13200 goto done;
13202 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13203 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13204 got_worktree_integrate_abort(worktree, fileindex, repo,
13205 branch_ref, base_branch_ref);
13206 goto done;
13209 error = got_ref_resolve(&commit_id, repo, branch_ref);
13210 if (error)
13211 goto done;
13213 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13214 if (error)
13215 goto done;
13217 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13218 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13219 "specified branch has already been integrated");
13220 got_worktree_integrate_abort(worktree, fileindex, repo,
13221 branch_ref, base_branch_ref);
13222 goto done;
13225 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13226 if (error) {
13227 if (error->code == GOT_ERR_ANCESTRY)
13228 error = got_error(GOT_ERR_REBASE_REQUIRED);
13229 got_worktree_integrate_abort(worktree, fileindex, repo,
13230 branch_ref, base_branch_ref);
13231 goto done;
13234 memset(&upa, 0, sizeof(upa));
13235 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13236 branch_ref, base_branch_ref, update_progress, &upa,
13237 check_cancelled, NULL);
13238 if (error)
13239 goto done;
13241 printf("Integrated %s into %s\n", refname, base_refname);
13242 print_update_progress_stats(&upa);
13243 done:
13244 if (repo) {
13245 const struct got_error *close_err = got_repo_close(repo);
13246 if (error == NULL)
13247 error = close_err;
13249 if (worktree)
13250 got_worktree_close(worktree);
13251 if (pack_fds) {
13252 const struct got_error *pack_err =
13253 got_repo_pack_fds_close(pack_fds);
13254 if (error == NULL)
13255 error = pack_err;
13257 free(cwd);
13258 free(base_commit_id);
13259 free(commit_id);
13260 free(refname);
13261 free(base_refname);
13262 return error;
13265 __dead static void
13266 usage_merge(void)
13268 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13269 exit(1);
13272 static const struct got_error *
13273 cmd_merge(int argc, char *argv[])
13275 const struct got_error *error = NULL;
13276 struct got_worktree *worktree = NULL;
13277 struct got_repository *repo = NULL;
13278 struct got_fileindex *fileindex = NULL;
13279 char *cwd = NULL, *id_str = NULL, *author = NULL;
13280 char *gitconfig_path = NULL;
13281 struct got_reference *branch = NULL, *wt_branch = NULL;
13282 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13283 struct got_object_id *wt_branch_tip = NULL;
13284 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13285 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13286 struct got_update_progress_arg upa;
13287 struct got_object_id *merge_commit_id = NULL;
13288 char *branch_name = NULL;
13289 int *pack_fds = NULL;
13291 memset(&upa, 0, sizeof(upa));
13293 #ifndef PROFILE
13294 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13295 "unveil", NULL) == -1)
13296 err(1, "pledge");
13297 #endif
13299 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13300 switch (ch) {
13301 case 'a':
13302 abort_merge = 1;
13303 break;
13304 case 'C':
13305 allow_conflict = 1;
13306 break;
13307 case 'c':
13308 continue_merge = 1;
13309 break;
13310 case 'M':
13311 prefer_fast_forward = 0;
13312 break;
13313 case 'n':
13314 interrupt_merge = 1;
13315 break;
13316 default:
13317 usage_merge();
13318 /* NOTREACHED */
13322 argc -= optind;
13323 argv += optind;
13325 if (abort_merge) {
13326 if (continue_merge)
13327 option_conflict('a', 'c');
13328 if (!prefer_fast_forward)
13329 option_conflict('a', 'M');
13330 if (interrupt_merge)
13331 option_conflict('a', 'n');
13332 } else if (continue_merge) {
13333 if (!prefer_fast_forward)
13334 option_conflict('c', 'M');
13335 if (interrupt_merge)
13336 option_conflict('c', 'n');
13338 if (allow_conflict) {
13339 if (!continue_merge)
13340 errx(1, "-C option requires -c");
13342 if (abort_merge || continue_merge) {
13343 if (argc != 0)
13344 usage_merge();
13345 } else if (argc != 1)
13346 usage_merge();
13348 cwd = getcwd(NULL, 0);
13349 if (cwd == NULL) {
13350 error = got_error_from_errno("getcwd");
13351 goto done;
13354 error = got_repo_pack_fds_open(&pack_fds);
13355 if (error != NULL)
13356 goto done;
13358 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13359 if (error) {
13360 if (error->code == GOT_ERR_NOT_WORKTREE)
13361 error = wrap_not_worktree_error(error,
13362 "merge", cwd);
13363 goto done;
13366 error = get_gitconfig_path(&gitconfig_path);
13367 if (error)
13368 goto done;
13369 error = got_repo_open(&repo,
13370 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13371 gitconfig_path, pack_fds);
13372 if (error != NULL)
13373 goto done;
13375 if (worktree != NULL) {
13376 error = worktree_has_logmsg_ref("merge", worktree, repo);
13377 if (error)
13378 goto done;
13381 error = apply_unveil(got_repo_get_path(repo), 0,
13382 worktree ? got_worktree_get_root_path(worktree) : NULL);
13383 if (error)
13384 goto done;
13386 error = check_rebase_or_histedit_in_progress(worktree);
13387 if (error)
13388 goto done;
13390 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13391 repo);
13392 if (error)
13393 goto done;
13395 if (merge_in_progress && !(abort_merge || continue_merge)) {
13396 error = got_error(GOT_ERR_MERGE_BUSY);
13397 goto done;
13400 if (!merge_in_progress && (abort_merge || continue_merge)) {
13401 error = got_error(GOT_ERR_NOT_MERGING);
13402 goto done;
13405 if (abort_merge) {
13406 error = got_worktree_merge_continue(&branch_name,
13407 &branch_tip, &fileindex, worktree, repo);
13408 if (error)
13409 goto done;
13410 error = got_worktree_merge_abort(worktree, fileindex, repo,
13411 abort_progress, &upa);
13412 if (error)
13413 goto done;
13414 printf("Merge of %s aborted\n", branch_name);
13415 goto done; /* nothing else to do */
13418 if (strncmp(got_worktree_get_head_ref_name(worktree),
13419 "refs/heads/", 11) != 0) {
13420 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13421 "work tree's current branch %s is outside the "
13422 "\"refs/heads/\" reference namespace; "
13423 "update -b required",
13424 got_worktree_get_head_ref_name(worktree));
13425 goto done;
13428 error = get_author(&author, repo, worktree);
13429 if (error)
13430 goto done;
13432 error = got_ref_open(&wt_branch, repo,
13433 got_worktree_get_head_ref_name(worktree), 0);
13434 if (error)
13435 goto done;
13436 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13437 if (error)
13438 goto done;
13440 if (continue_merge) {
13441 struct got_object_id *base_commit_id;
13442 base_commit_id = got_worktree_get_base_commit_id(worktree);
13443 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13444 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13445 goto done;
13447 error = got_worktree_merge_continue(&branch_name,
13448 &branch_tip, &fileindex, worktree, repo);
13449 if (error)
13450 goto done;
13451 } else {
13452 error = got_ref_open(&branch, repo, argv[0], 0);
13453 if (error != NULL)
13454 goto done;
13455 branch_name = strdup(got_ref_get_name(branch));
13456 if (branch_name == NULL) {
13457 error = got_error_from_errno("strdup");
13458 goto done;
13460 error = got_ref_resolve(&branch_tip, repo, branch);
13461 if (error)
13462 goto done;
13465 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13466 wt_branch_tip, branch_tip, 0, repo,
13467 check_cancelled, NULL);
13468 if (error && error->code != GOT_ERR_ANCESTRY)
13469 goto done;
13471 if (!continue_merge) {
13472 error = check_path_prefix(wt_branch_tip, branch_tip,
13473 got_worktree_get_path_prefix(worktree),
13474 GOT_ERR_MERGE_PATH, repo);
13475 if (error)
13476 goto done;
13477 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13478 if (error)
13479 goto done;
13480 if (prefer_fast_forward && yca_id &&
13481 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13482 struct got_pathlist_head paths;
13483 if (interrupt_merge) {
13484 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13485 "there are no changes to merge since %s "
13486 "is already based on %s; merge cannot be "
13487 "interrupted for amending; -n",
13488 branch_name, got_ref_get_name(wt_branch));
13489 goto done;
13491 printf("Forwarding %s to %s\n",
13492 got_ref_get_name(wt_branch), branch_name);
13493 error = got_ref_change_ref(wt_branch, branch_tip);
13494 if (error)
13495 goto done;
13496 error = got_ref_write(wt_branch, repo);
13497 if (error)
13498 goto done;
13499 error = got_worktree_set_base_commit_id(worktree, repo,
13500 branch_tip);
13501 if (error)
13502 goto done;
13503 TAILQ_INIT(&paths);
13504 error = got_pathlist_append(&paths, "", NULL);
13505 if (error)
13506 goto done;
13507 error = got_worktree_checkout_files(worktree,
13508 &paths, repo, update_progress, &upa,
13509 check_cancelled, NULL);
13510 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13511 if (error)
13512 goto done;
13513 if (upa.did_something) {
13514 char *id_str;
13515 error = got_object_id_str(&id_str, branch_tip);
13516 if (error)
13517 goto done;
13518 printf("Updated to commit %s\n", id_str);
13519 free(id_str);
13520 } else
13521 printf("Already up-to-date\n");
13522 print_update_progress_stats(&upa);
13523 goto done;
13525 error = got_worktree_merge_write_refs(worktree, branch, repo);
13526 if (error)
13527 goto done;
13529 error = got_worktree_merge_branch(worktree, fileindex,
13530 yca_id, branch_tip, repo, update_progress, &upa,
13531 check_cancelled, NULL);
13532 if (error)
13533 goto done;
13534 print_merge_progress_stats(&upa);
13535 if (!upa.did_something) {
13536 error = got_worktree_merge_abort(worktree, fileindex,
13537 repo, abort_progress, &upa);
13538 if (error)
13539 goto done;
13540 printf("Already up-to-date\n");
13541 goto done;
13545 if (interrupt_merge) {
13546 error = got_worktree_merge_postpone(worktree, fileindex);
13547 if (error)
13548 goto done;
13549 printf("Merge of %s interrupted on request\n", branch_name);
13550 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13551 upa.not_deleted > 0 || upa.unversioned > 0) {
13552 error = got_worktree_merge_postpone(worktree, fileindex);
13553 if (error)
13554 goto done;
13555 if (upa.conflicts > 0 && upa.missing == 0 &&
13556 upa.not_deleted == 0 && upa.unversioned == 0) {
13557 error = got_error_msg(GOT_ERR_CONFLICTS,
13558 "conflicts must be resolved before merging "
13559 "can continue");
13560 } else if (upa.conflicts > 0) {
13561 error = got_error_msg(GOT_ERR_CONFLICTS,
13562 "conflicts must be resolved before merging "
13563 "can continue; changes destined for some "
13564 "files were not yet merged and "
13565 "should be merged manually if required before the "
13566 "merge operation is continued");
13567 } else {
13568 error = got_error_msg(GOT_ERR_CONFLICTS,
13569 "changes destined for some "
13570 "files were not yet merged and should be "
13571 "merged manually if required before the "
13572 "merge operation is continued");
13574 goto done;
13575 } else {
13576 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13577 fileindex, author, NULL, 1, branch_tip, branch_name,
13578 allow_conflict, repo, continue_merge ? print_status : NULL,
13579 NULL);
13580 if (error)
13581 goto done;
13582 error = got_worktree_merge_complete(worktree, fileindex, repo);
13583 if (error)
13584 goto done;
13585 error = got_object_id_str(&id_str, merge_commit_id);
13586 if (error)
13587 goto done;
13588 printf("Merged %s into %s: %s\n", branch_name,
13589 got_worktree_get_head_ref_name(worktree),
13590 id_str);
13593 done:
13594 free(gitconfig_path);
13595 free(id_str);
13596 free(merge_commit_id);
13597 free(author);
13598 free(branch_tip);
13599 free(branch_name);
13600 free(yca_id);
13601 if (branch)
13602 got_ref_close(branch);
13603 if (wt_branch)
13604 got_ref_close(wt_branch);
13605 if (worktree)
13606 got_worktree_close(worktree);
13607 if (repo) {
13608 const struct got_error *close_err = got_repo_close(repo);
13609 if (error == NULL)
13610 error = close_err;
13612 if (pack_fds) {
13613 const struct got_error *pack_err =
13614 got_repo_pack_fds_close(pack_fds);
13615 if (error == NULL)
13616 error = pack_err;
13618 return error;
13621 __dead static void
13622 usage_stage(void)
13624 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13625 "[path ...]\n", getprogname());
13626 exit(1);
13629 static const struct got_error *
13630 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13631 const char *path, struct got_object_id *blob_id,
13632 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13633 int dirfd, const char *de_name)
13635 const struct got_error *err = NULL;
13636 char *id_str = NULL;
13638 if (staged_status != GOT_STATUS_ADD &&
13639 staged_status != GOT_STATUS_MODIFY &&
13640 staged_status != GOT_STATUS_DELETE)
13641 return NULL;
13643 if (staged_status == GOT_STATUS_ADD ||
13644 staged_status == GOT_STATUS_MODIFY)
13645 err = got_object_id_str(&id_str, staged_blob_id);
13646 else
13647 err = got_object_id_str(&id_str, blob_id);
13648 if (err)
13649 return err;
13651 printf("%s %c %s\n", id_str, staged_status, path);
13652 free(id_str);
13653 return NULL;
13656 static const struct got_error *
13657 cmd_stage(int argc, char *argv[])
13659 const struct got_error *error = NULL;
13660 struct got_repository *repo = NULL;
13661 struct got_worktree *worktree = NULL;
13662 char *cwd = NULL;
13663 struct got_pathlist_head paths;
13664 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13665 FILE *patch_script_file = NULL;
13666 const char *patch_script_path = NULL;
13667 struct choose_patch_arg cpa;
13668 int *pack_fds = NULL;
13670 TAILQ_INIT(&paths);
13672 #ifndef PROFILE
13673 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13674 "unveil", NULL) == -1)
13675 err(1, "pledge");
13676 #endif
13678 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13679 switch (ch) {
13680 case 'F':
13681 patch_script_path = optarg;
13682 break;
13683 case 'l':
13684 list_stage = 1;
13685 break;
13686 case 'p':
13687 pflag = 1;
13688 break;
13689 case 'S':
13690 allow_bad_symlinks = 1;
13691 break;
13692 default:
13693 usage_stage();
13694 /* NOTREACHED */
13698 argc -= optind;
13699 argv += optind;
13701 if (list_stage && (pflag || patch_script_path))
13702 errx(1, "-l option cannot be used with other options");
13703 if (patch_script_path && !pflag)
13704 errx(1, "-F option can only be used together with -p option");
13706 cwd = getcwd(NULL, 0);
13707 if (cwd == NULL) {
13708 error = got_error_from_errno("getcwd");
13709 goto done;
13712 error = got_repo_pack_fds_open(&pack_fds);
13713 if (error != NULL)
13714 goto done;
13716 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13717 if (error) {
13718 if (error->code == GOT_ERR_NOT_WORKTREE)
13719 error = wrap_not_worktree_error(error, "stage", cwd);
13720 goto done;
13723 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13724 NULL, pack_fds);
13725 if (error != NULL)
13726 goto done;
13728 if (patch_script_path) {
13729 patch_script_file = fopen(patch_script_path, "re");
13730 if (patch_script_file == NULL) {
13731 error = got_error_from_errno2("fopen",
13732 patch_script_path);
13733 goto done;
13736 error = apply_unveil(got_repo_get_path(repo), 0,
13737 got_worktree_get_root_path(worktree));
13738 if (error)
13739 goto done;
13741 error = check_merge_in_progress(worktree, repo);
13742 if (error)
13743 goto done;
13745 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13746 if (error)
13747 goto done;
13749 if (list_stage)
13750 error = got_worktree_status(worktree, &paths, repo, 0,
13751 print_stage, NULL, check_cancelled, NULL);
13752 else {
13753 cpa.patch_script_file = patch_script_file;
13754 cpa.action = "stage";
13755 error = got_worktree_stage(worktree, &paths,
13756 pflag ? NULL : print_status, NULL,
13757 pflag ? choose_patch : NULL, &cpa,
13758 allow_bad_symlinks, repo);
13760 done:
13761 if (patch_script_file && fclose(patch_script_file) == EOF &&
13762 error == NULL)
13763 error = got_error_from_errno2("fclose", patch_script_path);
13764 if (repo) {
13765 const struct got_error *close_err = got_repo_close(repo);
13766 if (error == NULL)
13767 error = close_err;
13769 if (worktree)
13770 got_worktree_close(worktree);
13771 if (pack_fds) {
13772 const struct got_error *pack_err =
13773 got_repo_pack_fds_close(pack_fds);
13774 if (error == NULL)
13775 error = pack_err;
13777 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13778 free(cwd);
13779 return error;
13782 __dead static void
13783 usage_unstage(void)
13785 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13786 "[path ...]\n", getprogname());
13787 exit(1);
13791 static const struct got_error *
13792 cmd_unstage(int argc, char *argv[])
13794 const struct got_error *error = NULL;
13795 struct got_repository *repo = NULL;
13796 struct got_worktree *worktree = NULL;
13797 char *cwd = NULL;
13798 struct got_pathlist_head paths;
13799 int ch, pflag = 0;
13800 struct got_update_progress_arg upa;
13801 FILE *patch_script_file = NULL;
13802 const char *patch_script_path = NULL;
13803 struct choose_patch_arg cpa;
13804 int *pack_fds = NULL;
13806 TAILQ_INIT(&paths);
13808 #ifndef PROFILE
13809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13810 "unveil", NULL) == -1)
13811 err(1, "pledge");
13812 #endif
13814 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13815 switch (ch) {
13816 case 'F':
13817 patch_script_path = optarg;
13818 break;
13819 case 'p':
13820 pflag = 1;
13821 break;
13822 default:
13823 usage_unstage();
13824 /* NOTREACHED */
13828 argc -= optind;
13829 argv += optind;
13831 if (patch_script_path && !pflag)
13832 errx(1, "-F option can only be used together with -p option");
13834 cwd = getcwd(NULL, 0);
13835 if (cwd == NULL) {
13836 error = got_error_from_errno("getcwd");
13837 goto done;
13840 error = got_repo_pack_fds_open(&pack_fds);
13841 if (error != NULL)
13842 goto done;
13844 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13845 if (error) {
13846 if (error->code == GOT_ERR_NOT_WORKTREE)
13847 error = wrap_not_worktree_error(error, "unstage", cwd);
13848 goto done;
13851 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13852 NULL, pack_fds);
13853 if (error != NULL)
13854 goto done;
13856 if (patch_script_path) {
13857 patch_script_file = fopen(patch_script_path, "re");
13858 if (patch_script_file == NULL) {
13859 error = got_error_from_errno2("fopen",
13860 patch_script_path);
13861 goto done;
13865 error = apply_unveil(got_repo_get_path(repo), 0,
13866 got_worktree_get_root_path(worktree));
13867 if (error)
13868 goto done;
13870 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13871 if (error)
13872 goto done;
13874 cpa.patch_script_file = patch_script_file;
13875 cpa.action = "unstage";
13876 memset(&upa, 0, sizeof(upa));
13877 error = got_worktree_unstage(worktree, &paths, update_progress,
13878 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13879 if (!error)
13880 print_merge_progress_stats(&upa);
13881 done:
13882 if (patch_script_file && fclose(patch_script_file) == EOF &&
13883 error == NULL)
13884 error = got_error_from_errno2("fclose", patch_script_path);
13885 if (repo) {
13886 const struct got_error *close_err = got_repo_close(repo);
13887 if (error == NULL)
13888 error = close_err;
13890 if (worktree)
13891 got_worktree_close(worktree);
13892 if (pack_fds) {
13893 const struct got_error *pack_err =
13894 got_repo_pack_fds_close(pack_fds);
13895 if (error == NULL)
13896 error = pack_err;
13898 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13899 free(cwd);
13900 return error;
13903 __dead static void
13904 usage_cat(void)
13906 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13907 "arg ...\n", getprogname());
13908 exit(1);
13911 static const struct got_error *
13912 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13914 const struct got_error *err;
13915 struct got_blob_object *blob;
13916 int fd = -1;
13918 fd = got_opentempfd();
13919 if (fd == -1)
13920 return got_error_from_errno("got_opentempfd");
13922 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13923 if (err)
13924 goto done;
13926 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13927 done:
13928 if (fd != -1 && close(fd) == -1 && err == NULL)
13929 err = got_error_from_errno("close");
13930 if (blob)
13931 got_object_blob_close(blob);
13932 return err;
13935 static const struct got_error *
13936 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13938 const struct got_error *err;
13939 struct got_tree_object *tree;
13940 int nentries, i;
13942 err = got_object_open_as_tree(&tree, repo, id);
13943 if (err)
13944 return err;
13946 nentries = got_object_tree_get_nentries(tree);
13947 for (i = 0; i < nentries; i++) {
13948 struct got_tree_entry *te;
13949 char *id_str;
13950 if (sigint_received || sigpipe_received)
13951 break;
13952 te = got_object_tree_get_entry(tree, i);
13953 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13954 if (err)
13955 break;
13956 fprintf(outfile, "%s %.7o %s\n", id_str,
13957 got_tree_entry_get_mode(te),
13958 got_tree_entry_get_name(te));
13959 free(id_str);
13962 got_object_tree_close(tree);
13963 return err;
13966 static const struct got_error *
13967 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13969 const struct got_error *err;
13970 struct got_commit_object *commit;
13971 const struct got_object_id_queue *parent_ids;
13972 struct got_object_qid *pid;
13973 char *id_str = NULL;
13974 const char *logmsg = NULL;
13975 char gmtoff[6];
13977 err = got_object_open_as_commit(&commit, repo, id);
13978 if (err)
13979 return err;
13981 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13982 if (err)
13983 goto done;
13985 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13986 parent_ids = got_object_commit_get_parent_ids(commit);
13987 fprintf(outfile, "numparents %d\n",
13988 got_object_commit_get_nparents(commit));
13989 STAILQ_FOREACH(pid, parent_ids, entry) {
13990 char *pid_str;
13991 err = got_object_id_str(&pid_str, &pid->id);
13992 if (err)
13993 goto done;
13994 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13995 free(pid_str);
13997 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13998 got_object_commit_get_author_gmtoff(commit));
13999 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14000 got_object_commit_get_author(commit),
14001 (long long)got_object_commit_get_author_time(commit),
14002 gmtoff);
14004 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14005 got_object_commit_get_committer_gmtoff(commit));
14006 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14007 got_object_commit_get_committer(commit),
14008 (long long)got_object_commit_get_committer_time(commit),
14009 gmtoff);
14011 logmsg = got_object_commit_get_logmsg_raw(commit);
14012 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14013 fprintf(outfile, "%s", logmsg);
14014 done:
14015 free(id_str);
14016 got_object_commit_close(commit);
14017 return err;
14020 static const struct got_error *
14021 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14023 const struct got_error *err;
14024 struct got_tag_object *tag;
14025 char *id_str = NULL;
14026 const char *tagmsg = NULL;
14027 char gmtoff[6];
14029 err = got_object_open_as_tag(&tag, repo, id);
14030 if (err)
14031 return err;
14033 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14034 if (err)
14035 goto done;
14037 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14039 switch (got_object_tag_get_object_type(tag)) {
14040 case GOT_OBJ_TYPE_BLOB:
14041 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14042 GOT_OBJ_LABEL_BLOB);
14043 break;
14044 case GOT_OBJ_TYPE_TREE:
14045 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14046 GOT_OBJ_LABEL_TREE);
14047 break;
14048 case GOT_OBJ_TYPE_COMMIT:
14049 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14050 GOT_OBJ_LABEL_COMMIT);
14051 break;
14052 case GOT_OBJ_TYPE_TAG:
14053 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14054 GOT_OBJ_LABEL_TAG);
14055 break;
14056 default:
14057 break;
14060 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14061 got_object_tag_get_name(tag));
14063 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14064 got_object_tag_get_tagger_gmtoff(tag));
14065 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14066 got_object_tag_get_tagger(tag),
14067 (long long)got_object_tag_get_tagger_time(tag),
14068 gmtoff);
14070 tagmsg = got_object_tag_get_message(tag);
14071 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14072 fprintf(outfile, "%s", tagmsg);
14073 done:
14074 free(id_str);
14075 got_object_tag_close(tag);
14076 return err;
14079 static const struct got_error *
14080 cmd_cat(int argc, char *argv[])
14082 const struct got_error *error;
14083 struct got_repository *repo = NULL;
14084 struct got_worktree *worktree = NULL;
14085 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14086 char *keyword_idstr = NULL;
14087 const char *commit_id_str = NULL;
14088 struct got_object_id *id = NULL, *commit_id = NULL;
14089 struct got_commit_object *commit = NULL;
14090 int ch, obj_type, i, force_path = 0;
14091 struct got_reflist_head refs;
14092 int *pack_fds = NULL;
14094 TAILQ_INIT(&refs);
14096 #ifndef PROFILE
14097 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14098 NULL) == -1)
14099 err(1, "pledge");
14100 #endif
14102 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14103 switch (ch) {
14104 case 'c':
14105 commit_id_str = optarg;
14106 break;
14107 case 'P':
14108 force_path = 1;
14109 break;
14110 case 'r':
14111 repo_path = realpath(optarg, NULL);
14112 if (repo_path == NULL)
14113 return got_error_from_errno2("realpath",
14114 optarg);
14115 got_path_strip_trailing_slashes(repo_path);
14116 break;
14117 default:
14118 usage_cat();
14119 /* NOTREACHED */
14123 argc -= optind;
14124 argv += optind;
14126 cwd = getcwd(NULL, 0);
14127 if (cwd == NULL) {
14128 error = got_error_from_errno("getcwd");
14129 goto done;
14132 error = got_repo_pack_fds_open(&pack_fds);
14133 if (error != NULL)
14134 goto done;
14136 if (repo_path == NULL) {
14137 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14138 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14139 goto done;
14140 if (worktree) {
14141 repo_path = strdup(
14142 got_worktree_get_repo_path(worktree));
14143 if (repo_path == NULL) {
14144 error = got_error_from_errno("strdup");
14145 goto done;
14148 if (commit_id_str == NULL) {
14149 /* Release work tree lock. */
14150 got_worktree_close(worktree);
14151 worktree = NULL;
14156 if (repo_path == NULL) {
14157 repo_path = strdup(cwd);
14158 if (repo_path == NULL)
14159 return got_error_from_errno("strdup");
14162 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14163 free(repo_path);
14164 if (error != NULL)
14165 goto done;
14167 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14168 if (error)
14169 goto done;
14171 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14172 if (error)
14173 goto done;
14175 if (commit_id_str != NULL) {
14176 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14177 repo, worktree);
14178 if (error != NULL)
14179 goto done;
14180 if (keyword_idstr != NULL)
14181 commit_id_str = keyword_idstr;
14182 if (worktree != NULL) {
14183 got_worktree_close(worktree);
14184 worktree = NULL;
14186 } else
14187 commit_id_str = GOT_REF_HEAD;
14188 error = got_repo_match_object_id(&commit_id, NULL,
14189 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14190 if (error)
14191 goto done;
14193 error = got_object_open_as_commit(&commit, repo, commit_id);
14194 if (error)
14195 goto done;
14197 for (i = 0; i < argc; i++) {
14198 if (force_path) {
14199 error = got_object_id_by_path(&id, repo, commit,
14200 argv[i]);
14201 if (error)
14202 break;
14203 } else {
14204 error = got_repo_match_object_id(&id, &label, argv[i],
14205 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14206 repo);
14207 if (error) {
14208 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14209 error->code != GOT_ERR_NOT_REF)
14210 break;
14211 error = got_object_id_by_path(&id, repo,
14212 commit, argv[i]);
14213 if (error)
14214 break;
14218 error = got_object_get_type(&obj_type, repo, id);
14219 if (error)
14220 break;
14222 switch (obj_type) {
14223 case GOT_OBJ_TYPE_BLOB:
14224 error = cat_blob(id, repo, stdout);
14225 break;
14226 case GOT_OBJ_TYPE_TREE:
14227 error = cat_tree(id, repo, stdout);
14228 break;
14229 case GOT_OBJ_TYPE_COMMIT:
14230 error = cat_commit(id, repo, stdout);
14231 break;
14232 case GOT_OBJ_TYPE_TAG:
14233 error = cat_tag(id, repo, stdout);
14234 break;
14235 default:
14236 error = got_error(GOT_ERR_OBJ_TYPE);
14237 break;
14239 if (error)
14240 break;
14241 free(label);
14242 label = NULL;
14243 free(id);
14244 id = NULL;
14246 done:
14247 free(label);
14248 free(id);
14249 free(commit_id);
14250 free(keyword_idstr);
14251 if (commit)
14252 got_object_commit_close(commit);
14253 if (worktree)
14254 got_worktree_close(worktree);
14255 if (repo) {
14256 const struct got_error *close_err = got_repo_close(repo);
14257 if (error == NULL)
14258 error = close_err;
14260 if (pack_fds) {
14261 const struct got_error *pack_err =
14262 got_repo_pack_fds_close(pack_fds);
14263 if (error == NULL)
14264 error = pack_err;
14267 got_ref_list_free(&refs);
14268 return error;
14271 __dead static void
14272 usage_info(void)
14274 fprintf(stderr, "usage: %s info [path ...]\n",
14275 getprogname());
14276 exit(1);
14279 static const struct got_error *
14280 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14281 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14282 struct got_object_id *commit_id)
14284 const struct got_error *err = NULL;
14285 char *id_str = NULL;
14286 char datebuf[128];
14287 struct tm mytm, *tm;
14288 struct got_pathlist_head *paths = arg;
14289 struct got_pathlist_entry *pe;
14292 * Clear error indication from any of the path arguments which
14293 * would cause this file index entry to be displayed.
14295 TAILQ_FOREACH(pe, paths, entry) {
14296 if (got_path_cmp(path, pe->path, strlen(path),
14297 pe->path_len) == 0 ||
14298 got_path_is_child(path, pe->path, pe->path_len))
14299 pe->data = NULL; /* no error */
14302 printf(GOT_COMMIT_SEP_STR);
14303 if (S_ISLNK(mode))
14304 printf("symlink: %s\n", path);
14305 else if (S_ISREG(mode)) {
14306 printf("file: %s\n", path);
14307 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14308 } else if (S_ISDIR(mode))
14309 printf("directory: %s\n", path);
14310 else
14311 printf("something: %s\n", path);
14313 tm = localtime_r(&mtime, &mytm);
14314 if (tm == NULL)
14315 return NULL;
14316 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14317 return got_error(GOT_ERR_NO_SPACE);
14318 printf("timestamp: %s\n", datebuf);
14320 if (blob_id) {
14321 err = got_object_id_str(&id_str, blob_id);
14322 if (err)
14323 return err;
14324 printf("based on blob: %s\n", id_str);
14325 free(id_str);
14328 if (staged_blob_id) {
14329 err = got_object_id_str(&id_str, staged_blob_id);
14330 if (err)
14331 return err;
14332 printf("based on staged blob: %s\n", id_str);
14333 free(id_str);
14336 if (commit_id) {
14337 err = got_object_id_str(&id_str, commit_id);
14338 if (err)
14339 return err;
14340 printf("based on commit: %s\n", id_str);
14341 free(id_str);
14344 return NULL;
14347 static const struct got_error *
14348 cmd_info(int argc, char *argv[])
14350 const struct got_error *error = NULL;
14351 struct got_worktree *worktree = NULL;
14352 char *cwd = NULL, *id_str = NULL;
14353 struct got_pathlist_head paths;
14354 char *uuidstr = NULL;
14355 int ch, show_files = 0;
14357 TAILQ_INIT(&paths);
14359 #ifndef PROFILE
14360 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14361 NULL) == -1)
14362 err(1, "pledge");
14363 #endif
14365 while ((ch = getopt(argc, argv, "")) != -1) {
14366 switch (ch) {
14367 default:
14368 usage_info();
14369 /* NOTREACHED */
14373 argc -= optind;
14374 argv += optind;
14376 cwd = getcwd(NULL, 0);
14377 if (cwd == NULL) {
14378 error = got_error_from_errno("getcwd");
14379 goto done;
14382 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14383 if (error) {
14384 if (error->code == GOT_ERR_NOT_WORKTREE)
14385 error = wrap_not_worktree_error(error, "info", cwd);
14386 goto done;
14389 #ifndef PROFILE
14390 /* Remove "wpath cpath proc exec sendfd" promises. */
14391 if (pledge("stdio rpath flock unveil", NULL) == -1)
14392 err(1, "pledge");
14393 #endif
14394 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14395 if (error)
14396 goto done;
14398 if (argc >= 1) {
14399 error = get_worktree_paths_from_argv(&paths, argc, argv,
14400 worktree);
14401 if (error)
14402 goto done;
14403 show_files = 1;
14406 error = got_object_id_str(&id_str,
14407 got_worktree_get_base_commit_id(worktree));
14408 if (error)
14409 goto done;
14411 error = got_worktree_get_uuid(&uuidstr, worktree);
14412 if (error)
14413 goto done;
14415 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14416 printf("work tree base commit: %s\n", id_str);
14417 printf("work tree path prefix: %s\n",
14418 got_worktree_get_path_prefix(worktree));
14419 printf("work tree branch reference: %s\n",
14420 got_worktree_get_head_ref_name(worktree));
14421 printf("work tree UUID: %s\n", uuidstr);
14422 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14424 if (show_files) {
14425 struct got_pathlist_entry *pe;
14426 TAILQ_FOREACH(pe, &paths, entry) {
14427 if (pe->path_len == 0)
14428 continue;
14430 * Assume this path will fail. This will be corrected
14431 * in print_path_info() in case the path does suceeed.
14433 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14435 error = got_worktree_path_info(worktree, &paths,
14436 print_path_info, &paths, check_cancelled, NULL);
14437 if (error)
14438 goto done;
14439 TAILQ_FOREACH(pe, &paths, entry) {
14440 if (pe->data != NULL) {
14441 const struct got_error *perr;
14443 perr = pe->data;
14444 error = got_error_fmt(perr->code, "%s",
14445 pe->path);
14446 break;
14450 done:
14451 if (worktree)
14452 got_worktree_close(worktree);
14453 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14454 free(cwd);
14455 free(id_str);
14456 free(uuidstr);
14457 return error;