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 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3080 got_path_is_child(repo_path, worktree_path,
3081 strlen(worktree_path))) {
3082 error = got_error_fmt(GOT_ERR_BAD_PATH,
3083 "work tree and repository paths may not overlap: %s",
3084 worktree_path);
3085 goto done;
3088 error = got_repo_pack_fds_open(&pack_fds);
3089 if (error != NULL)
3090 goto done;
3092 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3093 if (error != NULL)
3094 goto done;
3096 /* Pre-create work tree path for unveil(2) */
3097 error = got_path_mkdir(worktree_path);
3098 if (error) {
3099 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3100 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3101 goto done;
3102 if (!allow_nonempty &&
3103 !got_path_dir_is_empty(worktree_path)) {
3104 error = got_error_path(worktree_path,
3105 GOT_ERR_DIR_NOT_EMPTY);
3106 goto done;
3110 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3111 if (error)
3112 goto done;
3114 error = got_ref_open(&head_ref, repo, branch_name, 0);
3115 if (error != NULL)
3116 goto done;
3118 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3119 GOT_WORKTREE_GOT_DIR, repo);
3120 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3121 goto done;
3123 error = got_worktree_open(&worktree, worktree_path,
3124 GOT_WORKTREE_GOT_DIR);
3125 if (error != NULL)
3126 goto done;
3128 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3129 path_prefix);
3130 if (error != NULL)
3131 goto done;
3132 if (!same_path_prefix) {
3133 error = got_error(GOT_ERR_PATH_PREFIX);
3134 goto done;
3137 if (commit_id_str) {
3138 struct got_reflist_head refs;
3139 TAILQ_INIT(&refs);
3140 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3141 NULL);
3142 if (error)
3143 goto done;
3145 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3146 repo, worktree);
3147 if (error != NULL)
3148 goto done;
3149 if (keyword_idstr != NULL) {
3150 free(commit_id_str);
3151 commit_id_str = keyword_idstr;
3154 error = got_repo_match_object_id(&commit_id, NULL,
3155 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3156 got_ref_list_free(&refs);
3157 if (error)
3158 goto done;
3159 error = check_linear_ancestry(commit_id,
3160 got_worktree_get_base_commit_id(worktree), 0, repo);
3161 if (error != NULL) {
3162 if (error->code == GOT_ERR_ANCESTRY) {
3163 error = checkout_ancestry_error(
3164 head_ref, commit_id_str);
3166 goto done;
3168 error = check_same_branch(commit_id, head_ref, repo);
3169 if (error) {
3170 if (error->code == GOT_ERR_ANCESTRY) {
3171 error = checkout_ancestry_error(
3172 head_ref, commit_id_str);
3174 goto done;
3176 error = got_worktree_set_base_commit_id(worktree, repo,
3177 commit_id);
3178 if (error)
3179 goto done;
3180 /* Expand potentially abbreviated commit ID string. */
3181 free(commit_id_str);
3182 error = got_object_id_str(&commit_id_str, commit_id);
3183 if (error)
3184 goto done;
3185 } else {
3186 commit_id = got_object_id_dup(
3187 got_worktree_get_base_commit_id(worktree));
3188 if (commit_id == NULL) {
3189 error = got_error_from_errno("got_object_id_dup");
3190 goto done;
3192 error = got_object_id_str(&commit_id_str, commit_id);
3193 if (error)
3194 goto done;
3197 error = got_pathlist_append(&paths, "", NULL);
3198 if (error)
3199 goto done;
3200 cpa.worktree_path = worktree_path;
3201 cpa.had_base_commit_ref_error = 0;
3202 cpa.verbosity = verbosity;
3203 error = got_worktree_checkout_files(worktree, &paths, repo,
3204 checkout_progress, &cpa, check_cancelled, NULL);
3205 if (error != NULL)
3206 goto done;
3208 if (got_ref_is_symbolic(head_ref)) {
3209 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3210 if (error)
3211 goto done;
3212 refname = got_ref_get_name(ref);
3213 } else
3214 refname = got_ref_get_name(head_ref);
3215 printf("Checked out %s: %s\n", refname, commit_id_str);
3216 printf("Now shut up and hack\n");
3217 if (cpa.had_base_commit_ref_error)
3218 show_worktree_base_ref_warning();
3219 done:
3220 if (pack_fds) {
3221 const struct got_error *pack_err =
3222 got_repo_pack_fds_close(pack_fds);
3223 if (error == NULL)
3224 error = pack_err;
3226 if (head_ref)
3227 got_ref_close(head_ref);
3228 if (ref)
3229 got_ref_close(ref);
3230 if (repo) {
3231 const struct got_error *close_err = got_repo_close(repo);
3232 if (error == NULL)
3233 error = close_err;
3235 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3236 free(commit_id_str);
3237 free(commit_id);
3238 free(repo_path);
3239 free(worktree_path);
3240 free(cwd);
3241 return error;
3244 struct got_update_progress_arg {
3245 int did_something;
3246 int conflicts;
3247 int obstructed;
3248 int not_updated;
3249 int missing;
3250 int not_deleted;
3251 int unversioned;
3252 int verbosity;
3255 static void
3256 print_update_progress_stats(struct got_update_progress_arg *upa)
3258 if (!upa->did_something)
3259 return;
3261 if (upa->conflicts > 0)
3262 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3263 if (upa->obstructed > 0)
3264 printf("File paths obstructed by a non-regular file: %d\n",
3265 upa->obstructed);
3266 if (upa->not_updated > 0)
3267 printf("Files not updated because of existing merge "
3268 "conflicts: %d\n", upa->not_updated);
3272 * The meaning of some status codes differs between merge-style operations and
3273 * update operations. For example, the ! status code means "file was missing"
3274 * if changes were merged into the work tree, and "missing file was restored"
3275 * if the work tree was updated. This function should be used by any operation
3276 * which merges changes into the work tree without updating the work tree.
3278 static void
3279 print_merge_progress_stats(struct got_update_progress_arg *upa)
3281 if (!upa->did_something)
3282 return;
3284 if (upa->conflicts > 0)
3285 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3286 if (upa->obstructed > 0)
3287 printf("File paths obstructed by a non-regular file: %d\n",
3288 upa->obstructed);
3289 if (upa->missing > 0)
3290 printf("Files which had incoming changes but could not be "
3291 "found in the work tree: %d\n", upa->missing);
3292 if (upa->not_deleted > 0)
3293 printf("Files not deleted due to differences in deleted "
3294 "content: %d\n", upa->not_deleted);
3295 if (upa->unversioned > 0)
3296 printf("Files not merged because an unversioned file was "
3297 "found in the work tree: %d\n", upa->unversioned);
3300 __dead static void
3301 usage_update(void)
3303 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3304 "[path ...]\n", getprogname());
3305 exit(1);
3308 static const struct got_error *
3309 update_progress(void *arg, unsigned char status, const char *path)
3311 struct got_update_progress_arg *upa = arg;
3313 if (status == GOT_STATUS_EXISTS ||
3314 status == GOT_STATUS_BASE_REF_ERR)
3315 return NULL;
3317 upa->did_something = 1;
3319 /* Base commit bump happens silently. */
3320 if (status == GOT_STATUS_BUMP_BASE)
3321 return NULL;
3323 if (status == GOT_STATUS_CONFLICT)
3324 upa->conflicts++;
3325 if (status == GOT_STATUS_OBSTRUCTED)
3326 upa->obstructed++;
3327 if (status == GOT_STATUS_CANNOT_UPDATE)
3328 upa->not_updated++;
3329 if (status == GOT_STATUS_MISSING)
3330 upa->missing++;
3331 if (status == GOT_STATUS_CANNOT_DELETE)
3332 upa->not_deleted++;
3333 if (status == GOT_STATUS_UNVERSIONED)
3334 upa->unversioned++;
3336 while (path[0] == '/')
3337 path++;
3338 if (upa->verbosity >= 0)
3339 printf("%c %s\n", status, path);
3341 return NULL;
3344 static const struct got_error *
3345 switch_head_ref(struct got_reference *head_ref,
3346 struct got_object_id *commit_id, struct got_worktree *worktree,
3347 struct got_repository *repo)
3349 const struct got_error *err = NULL;
3350 char *base_id_str;
3351 int ref_has_moved = 0;
3353 /* Trivial case: switching between two different references. */
3354 if (strcmp(got_ref_get_name(head_ref),
3355 got_worktree_get_head_ref_name(worktree)) != 0) {
3356 printf("Switching work tree from %s to %s\n",
3357 got_worktree_get_head_ref_name(worktree),
3358 got_ref_get_name(head_ref));
3359 return got_worktree_set_head_ref(worktree, head_ref);
3362 err = check_linear_ancestry(commit_id,
3363 got_worktree_get_base_commit_id(worktree), 0, repo);
3364 if (err) {
3365 if (err->code != GOT_ERR_ANCESTRY)
3366 return err;
3367 ref_has_moved = 1;
3369 if (!ref_has_moved)
3370 return NULL;
3372 /* Switching to a rebased branch with the same reference name. */
3373 err = got_object_id_str(&base_id_str,
3374 got_worktree_get_base_commit_id(worktree));
3375 if (err)
3376 return err;
3377 printf("Reference %s now points at a different branch\n",
3378 got_worktree_get_head_ref_name(worktree));
3379 printf("Switching work tree from %s to %s\n", base_id_str,
3380 got_worktree_get_head_ref_name(worktree));
3381 return NULL;
3384 static const struct got_error *
3385 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3387 const struct got_error *err;
3388 int in_progress;
3390 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3391 if (err)
3392 return err;
3393 if (in_progress)
3394 return got_error(GOT_ERR_REBASING);
3396 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3397 if (err)
3398 return err;
3399 if (in_progress)
3400 return got_error(GOT_ERR_HISTEDIT_BUSY);
3402 return NULL;
3405 static const struct got_error *
3406 check_merge_in_progress(struct got_worktree *worktree,
3407 struct got_repository *repo)
3409 const struct got_error *err;
3410 int in_progress;
3412 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3413 if (err)
3414 return err;
3415 if (in_progress)
3416 return got_error(GOT_ERR_MERGE_BUSY);
3418 return NULL;
3421 static const struct got_error *
3422 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3423 char *argv[], struct got_worktree *worktree)
3425 const struct got_error *err = NULL;
3426 char *path;
3427 struct got_pathlist_entry *new;
3428 int i;
3430 if (argc == 0) {
3431 path = strdup("");
3432 if (path == NULL)
3433 return got_error_from_errno("strdup");
3434 return got_pathlist_append(paths, path, NULL);
3437 for (i = 0; i < argc; i++) {
3438 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3439 if (err)
3440 break;
3441 err = got_pathlist_insert(&new, paths, path, NULL);
3442 if (err || new == NULL /* duplicate */) {
3443 free(path);
3444 if (err)
3445 break;
3449 return err;
3452 static const struct got_error *
3453 wrap_not_worktree_error(const struct got_error *orig_err,
3454 const char *cmdname, const char *path)
3456 const struct got_error *err;
3457 struct got_repository *repo;
3458 static char msg[512];
3459 int *pack_fds = NULL;
3461 err = got_repo_pack_fds_open(&pack_fds);
3462 if (err)
3463 return err;
3465 err = got_repo_open(&repo, path, NULL, pack_fds);
3466 if (err)
3467 return orig_err;
3469 snprintf(msg, sizeof(msg),
3470 "'got %s' needs a work tree in addition to a git repository\n"
3471 "Work trees can be checked out from this Git repository with "
3472 "'got checkout'.\n"
3473 "The got(1) manual page contains more information.", cmdname);
3474 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3475 if (repo) {
3476 const struct got_error *close_err = got_repo_close(repo);
3477 if (err == NULL)
3478 err = close_err;
3480 if (pack_fds) {
3481 const struct got_error *pack_err =
3482 got_repo_pack_fds_close(pack_fds);
3483 if (err == NULL)
3484 err = pack_err;
3486 return err;
3489 static const struct got_error *
3490 cmd_update(int argc, char *argv[])
3492 const struct got_error *error = NULL;
3493 struct got_repository *repo = NULL;
3494 struct got_worktree *worktree = NULL;
3495 char *worktree_path = NULL;
3496 struct got_object_id *commit_id = NULL;
3497 char *commit_id_str = NULL;
3498 const char *branch_name = NULL;
3499 struct got_reference *head_ref = NULL;
3500 struct got_pathlist_head paths;
3501 struct got_pathlist_entry *pe;
3502 int ch, verbosity = 0;
3503 struct got_update_progress_arg upa;
3504 int *pack_fds = NULL;
3506 TAILQ_INIT(&paths);
3508 #ifndef PROFILE
3509 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3510 "unveil", NULL) == -1)
3511 err(1, "pledge");
3512 #endif
3514 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3515 switch (ch) {
3516 case 'b':
3517 branch_name = optarg;
3518 break;
3519 case 'c':
3520 commit_id_str = strdup(optarg);
3521 if (commit_id_str == NULL)
3522 return got_error_from_errno("strdup");
3523 break;
3524 case 'q':
3525 verbosity = -1;
3526 break;
3527 default:
3528 usage_update();
3529 /* NOTREACHED */
3533 argc -= optind;
3534 argv += optind;
3536 worktree_path = getcwd(NULL, 0);
3537 if (worktree_path == NULL) {
3538 error = got_error_from_errno("getcwd");
3539 goto done;
3542 error = got_repo_pack_fds_open(&pack_fds);
3543 if (error != NULL)
3544 goto done;
3546 error = got_worktree_open(&worktree, worktree_path,
3547 GOT_WORKTREE_GOT_DIR);
3548 if (error) {
3549 if (error->code == GOT_ERR_NOT_WORKTREE)
3550 error = wrap_not_worktree_error(error, "update",
3551 worktree_path);
3552 goto done;
3555 error = check_rebase_or_histedit_in_progress(worktree);
3556 if (error)
3557 goto done;
3559 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3560 NULL, pack_fds);
3561 if (error != NULL)
3562 goto done;
3564 error = apply_unveil(got_repo_get_path(repo), 0,
3565 got_worktree_get_root_path(worktree));
3566 if (error)
3567 goto done;
3569 error = check_merge_in_progress(worktree, repo);
3570 if (error)
3571 goto done;
3573 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3574 if (error)
3575 goto done;
3577 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3578 got_worktree_get_head_ref_name(worktree), 0);
3579 if (error != NULL)
3580 goto done;
3581 if (commit_id_str == NULL) {
3582 error = got_ref_resolve(&commit_id, repo, head_ref);
3583 if (error != NULL)
3584 goto done;
3585 error = got_object_id_str(&commit_id_str, commit_id);
3586 if (error != NULL)
3587 goto done;
3588 } else {
3589 struct got_reflist_head refs;
3590 char *keyword_idstr = NULL;
3592 TAILQ_INIT(&refs);
3594 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3595 NULL);
3596 if (error)
3597 goto done;
3599 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3600 repo, worktree);
3601 if (error != NULL)
3602 goto done;
3603 if (keyword_idstr != NULL) {
3604 free(commit_id_str);
3605 commit_id_str = keyword_idstr;
3608 error = got_repo_match_object_id(&commit_id, NULL,
3609 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3610 got_ref_list_free(&refs);
3611 free(commit_id_str);
3612 commit_id_str = NULL;
3613 if (error)
3614 goto done;
3615 error = got_object_id_str(&commit_id_str, commit_id);
3616 if (error)
3617 goto done;
3620 if (branch_name) {
3621 struct got_object_id *head_commit_id;
3622 TAILQ_FOREACH(pe, &paths, entry) {
3623 if (pe->path_len == 0)
3624 continue;
3625 error = got_error_msg(GOT_ERR_BAD_PATH,
3626 "switching between branches requires that "
3627 "the entire work tree gets updated");
3628 goto done;
3630 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3631 if (error)
3632 goto done;
3633 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3634 repo);
3635 free(head_commit_id);
3636 if (error != NULL)
3637 goto done;
3638 error = check_same_branch(commit_id, head_ref, repo);
3639 if (error)
3640 goto done;
3641 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3642 if (error)
3643 goto done;
3644 } else {
3645 error = check_linear_ancestry(commit_id,
3646 got_worktree_get_base_commit_id(worktree), 0, repo);
3647 if (error != NULL) {
3648 if (error->code == GOT_ERR_ANCESTRY)
3649 error = got_error(GOT_ERR_BRANCH_MOVED);
3650 goto done;
3652 error = check_same_branch(commit_id, head_ref, repo);
3653 if (error)
3654 goto done;
3657 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3658 commit_id) != 0) {
3659 error = got_worktree_set_base_commit_id(worktree, repo,
3660 commit_id);
3661 if (error)
3662 goto done;
3665 memset(&upa, 0, sizeof(upa));
3666 upa.verbosity = verbosity;
3667 error = got_worktree_checkout_files(worktree, &paths, repo,
3668 update_progress, &upa, check_cancelled, NULL);
3669 if (error != NULL)
3670 goto done;
3672 if (upa.did_something) {
3673 printf("Updated to %s: %s\n",
3674 got_worktree_get_head_ref_name(worktree), commit_id_str);
3675 } else
3676 printf("Already up-to-date\n");
3678 print_update_progress_stats(&upa);
3679 done:
3680 if (pack_fds) {
3681 const struct got_error *pack_err =
3682 got_repo_pack_fds_close(pack_fds);
3683 if (error == NULL)
3684 error = pack_err;
3686 if (repo) {
3687 const struct got_error *close_err = got_repo_close(repo);
3688 if (error == NULL)
3689 error = close_err;
3691 if (head_ref != NULL)
3692 got_ref_close(head_ref);
3693 free(worktree_path);
3694 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3695 free(commit_id);
3696 free(commit_id_str);
3697 return error;
3700 static const struct got_error *
3701 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3702 const char *path, int diff_context, int ignore_whitespace,
3703 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3704 struct got_repository *repo, FILE *outfile)
3706 const struct got_error *err = NULL;
3707 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3708 FILE *f1 = NULL, *f2 = NULL;
3709 int fd1 = -1, fd2 = -1;
3711 fd1 = got_opentempfd();
3712 if (fd1 == -1)
3713 return got_error_from_errno("got_opentempfd");
3714 fd2 = got_opentempfd();
3715 if (fd2 == -1) {
3716 err = got_error_from_errno("got_opentempfd");
3717 goto done;
3720 if (blob_id1) {
3721 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3722 fd1);
3723 if (err)
3724 goto done;
3727 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3728 if (err)
3729 goto done;
3731 f1 = got_opentemp();
3732 if (f1 == NULL) {
3733 err = got_error_from_errno("got_opentemp");
3734 goto done;
3736 f2 = got_opentemp();
3737 if (f2 == NULL) {
3738 err = got_error_from_errno("got_opentemp");
3739 goto done;
3742 while (path[0] == '/')
3743 path++;
3744 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3745 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3746 force_text_diff, dsa, outfile);
3747 done:
3748 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3749 err = got_error_from_errno("close");
3750 if (blob1)
3751 got_object_blob_close(blob1);
3752 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3753 err = got_error_from_errno("close");
3754 if (blob2)
3755 got_object_blob_close(blob2);
3756 if (f1 && fclose(f1) == EOF && err == NULL)
3757 err = got_error_from_errno("fclose");
3758 if (f2 && fclose(f2) == EOF && err == NULL)
3759 err = got_error_from_errno("fclose");
3760 return err;
3763 static const struct got_error *
3764 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3765 const char *path, int diff_context, int ignore_whitespace,
3766 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3767 struct got_repository *repo, FILE *outfile)
3769 const struct got_error *err = NULL;
3770 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3771 struct got_diff_blob_output_unidiff_arg arg;
3772 FILE *f1 = NULL, *f2 = NULL;
3773 int fd1 = -1, fd2 = -1;
3775 if (tree_id1) {
3776 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3777 if (err)
3778 goto done;
3779 fd1 = got_opentempfd();
3780 if (fd1 == -1) {
3781 err = got_error_from_errno("got_opentempfd");
3782 goto done;
3786 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3787 if (err)
3788 goto done;
3790 f1 = got_opentemp();
3791 if (f1 == NULL) {
3792 err = got_error_from_errno("got_opentemp");
3793 goto done;
3796 f2 = got_opentemp();
3797 if (f2 == NULL) {
3798 err = got_error_from_errno("got_opentemp");
3799 goto done;
3801 fd2 = got_opentempfd();
3802 if (fd2 == -1) {
3803 err = got_error_from_errno("got_opentempfd");
3804 goto done;
3806 arg.diff_context = diff_context;
3807 arg.ignore_whitespace = ignore_whitespace;
3808 arg.force_text_diff = force_text_diff;
3809 arg.diffstat = dsa;
3810 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3811 arg.outfile = outfile;
3812 arg.lines = NULL;
3813 arg.nlines = 0;
3814 while (path[0] == '/')
3815 path++;
3816 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3817 got_diff_blob_output_unidiff, &arg, 1);
3818 done:
3819 if (tree1)
3820 got_object_tree_close(tree1);
3821 if (tree2)
3822 got_object_tree_close(tree2);
3823 if (f1 && fclose(f1) == EOF && err == NULL)
3824 err = got_error_from_errno("fclose");
3825 if (f2 && fclose(f2) == EOF && err == NULL)
3826 err = got_error_from_errno("fclose");
3827 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3828 err = got_error_from_errno("close");
3829 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3830 err = got_error_from_errno("close");
3831 return err;
3834 static const struct got_error *
3835 get_changed_paths(struct got_pathlist_head *paths,
3836 struct got_commit_object *commit, struct got_repository *repo,
3837 struct got_diffstat_cb_arg *dsa)
3839 const struct got_error *err = NULL;
3840 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3841 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3842 struct got_object_qid *qid;
3843 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3844 FILE *f1 = NULL, *f2 = NULL;
3845 int fd1 = -1, fd2 = -1;
3847 if (dsa) {
3848 cb = got_diff_tree_compute_diffstat;
3850 f1 = got_opentemp();
3851 if (f1 == NULL) {
3852 err = got_error_from_errno("got_opentemp");
3853 goto done;
3855 f2 = got_opentemp();
3856 if (f2 == NULL) {
3857 err = got_error_from_errno("got_opentemp");
3858 goto done;
3860 fd1 = got_opentempfd();
3861 if (fd1 == -1) {
3862 err = got_error_from_errno("got_opentempfd");
3863 goto done;
3865 fd2 = got_opentempfd();
3866 if (fd2 == -1) {
3867 err = got_error_from_errno("got_opentempfd");
3868 goto done;
3872 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3873 if (qid != NULL) {
3874 struct got_commit_object *pcommit;
3875 err = got_object_open_as_commit(&pcommit, repo,
3876 &qid->id);
3877 if (err)
3878 return err;
3880 tree_id1 = got_object_id_dup(
3881 got_object_commit_get_tree_id(pcommit));
3882 if (tree_id1 == NULL) {
3883 got_object_commit_close(pcommit);
3884 return got_error_from_errno("got_object_id_dup");
3886 got_object_commit_close(pcommit);
3890 if (tree_id1) {
3891 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3892 if (err)
3893 goto done;
3896 tree_id2 = got_object_commit_get_tree_id(commit);
3897 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3898 if (err)
3899 goto done;
3901 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3902 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3903 done:
3904 if (tree1)
3905 got_object_tree_close(tree1);
3906 if (tree2)
3907 got_object_tree_close(tree2);
3908 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3909 err = got_error_from_errno("close");
3910 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3911 err = got_error_from_errno("close");
3912 if (f1 && fclose(f1) == EOF && err == NULL)
3913 err = got_error_from_errno("fclose");
3914 if (f2 && fclose(f2) == EOF && err == NULL)
3915 err = got_error_from_errno("fclose");
3916 free(tree_id1);
3917 return err;
3920 static const struct got_error *
3921 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3922 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3923 struct got_repository *repo, FILE *outfile)
3925 const struct got_error *err = NULL;
3926 struct got_commit_object *pcommit = NULL;
3927 char *id_str1 = NULL, *id_str2 = NULL;
3928 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3929 struct got_object_qid *qid;
3931 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3932 if (qid != NULL) {
3933 err = got_object_open_as_commit(&pcommit, repo,
3934 &qid->id);
3935 if (err)
3936 return err;
3937 err = got_object_id_str(&id_str1, &qid->id);
3938 if (err)
3939 goto done;
3942 err = got_object_id_str(&id_str2, id);
3943 if (err)
3944 goto done;
3946 if (path && path[0] != '\0') {
3947 int obj_type;
3948 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3949 if (err)
3950 goto done;
3951 if (pcommit) {
3952 err = got_object_id_by_path(&obj_id1, repo,
3953 pcommit, path);
3954 if (err) {
3955 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3956 free(obj_id2);
3957 goto done;
3961 err = got_object_get_type(&obj_type, repo, obj_id2);
3962 if (err) {
3963 free(obj_id2);
3964 goto done;
3966 fprintf(outfile,
3967 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3968 fprintf(outfile, "commit - %s\n",
3969 id_str1 ? id_str1 : "/dev/null");
3970 fprintf(outfile, "commit + %s\n", id_str2);
3971 switch (obj_type) {
3972 case GOT_OBJ_TYPE_BLOB:
3973 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3974 0, 0, dsa, repo, outfile);
3975 break;
3976 case GOT_OBJ_TYPE_TREE:
3977 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3978 0, 0, dsa, repo, outfile);
3979 break;
3980 default:
3981 err = got_error(GOT_ERR_OBJ_TYPE);
3982 break;
3984 free(obj_id1);
3985 free(obj_id2);
3986 } else {
3987 obj_id2 = got_object_commit_get_tree_id(commit);
3988 if (pcommit)
3989 obj_id1 = got_object_commit_get_tree_id(pcommit);
3990 fprintf(outfile,
3991 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3992 fprintf(outfile, "commit - %s\n",
3993 id_str1 ? id_str1 : "/dev/null");
3994 fprintf(outfile, "commit + %s\n", id_str2);
3995 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3996 dsa, repo, outfile);
3998 done:
3999 free(id_str1);
4000 free(id_str2);
4001 if (pcommit)
4002 got_object_commit_close(pcommit);
4003 return err;
4006 static char *
4007 get_datestr(time_t *time, char *datebuf)
4009 struct tm mytm, *tm;
4010 char *p, *s;
4012 tm = gmtime_r(time, &mytm);
4013 if (tm == NULL)
4014 return NULL;
4015 s = asctime_r(tm, datebuf);
4016 if (s == NULL)
4017 return NULL;
4018 p = strchr(s, '\n');
4019 if (p)
4020 *p = '\0';
4021 return s;
4024 static const struct got_error *
4025 match_commit(int *have_match, struct got_object_id *id,
4026 struct got_commit_object *commit, regex_t *regex)
4028 const struct got_error *err = NULL;
4029 regmatch_t regmatch;
4030 char *id_str = NULL, *logmsg = NULL;
4032 *have_match = 0;
4034 err = got_object_id_str(&id_str, id);
4035 if (err)
4036 return err;
4038 err = got_object_commit_get_logmsg(&logmsg, commit);
4039 if (err)
4040 goto done;
4042 if (regexec(regex, got_object_commit_get_author(commit), 1,
4043 &regmatch, 0) == 0 ||
4044 regexec(regex, got_object_commit_get_committer(commit), 1,
4045 &regmatch, 0) == 0 ||
4046 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4047 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4048 *have_match = 1;
4049 done:
4050 free(id_str);
4051 free(logmsg);
4052 return err;
4055 static void
4056 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4057 regex_t *regex)
4059 regmatch_t regmatch;
4060 struct got_pathlist_entry *pe;
4062 *have_match = 0;
4064 TAILQ_FOREACH(pe, changed_paths, entry) {
4065 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4066 *have_match = 1;
4067 break;
4072 static const struct got_error *
4073 match_patch(int *have_match, struct got_commit_object *commit,
4074 struct got_object_id *id, const char *path, int diff_context,
4075 struct got_repository *repo, regex_t *regex, FILE *f)
4077 const struct got_error *err = NULL;
4078 char *line = NULL;
4079 size_t linesize = 0;
4080 regmatch_t regmatch;
4082 *have_match = 0;
4084 err = got_opentemp_truncate(f);
4085 if (err)
4086 return err;
4088 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4089 if (err)
4090 goto done;
4092 if (fseeko(f, 0L, SEEK_SET) == -1) {
4093 err = got_error_from_errno("fseeko");
4094 goto done;
4097 while (getline(&line, &linesize, f) != -1) {
4098 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4099 *have_match = 1;
4100 break;
4103 done:
4104 free(line);
4105 return err;
4108 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4110 static const struct got_error*
4111 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4112 struct got_object_id *id, struct got_repository *repo,
4113 int local_only)
4115 static const struct got_error *err = NULL;
4116 struct got_reflist_entry *re;
4117 char *s;
4118 const char *name;
4120 *refs_str = NULL;
4122 TAILQ_FOREACH(re, refs, entry) {
4123 struct got_tag_object *tag = NULL;
4124 struct got_object_id *ref_id;
4125 int cmp;
4127 name = got_ref_get_name(re->ref);
4128 if (strcmp(name, GOT_REF_HEAD) == 0)
4129 continue;
4130 if (strncmp(name, "refs/", 5) == 0)
4131 name += 5;
4132 if (strncmp(name, "got/", 4) == 0)
4133 continue;
4134 if (strncmp(name, "heads/", 6) == 0)
4135 name += 6;
4136 if (strncmp(name, "remotes/", 8) == 0) {
4137 if (local_only)
4138 continue;
4139 name += 8;
4140 s = strstr(name, "/" GOT_REF_HEAD);
4141 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4142 continue;
4144 err = got_ref_resolve(&ref_id, repo, re->ref);
4145 if (err)
4146 break;
4147 if (strncmp(name, "tags/", 5) == 0) {
4148 err = got_object_open_as_tag(&tag, repo, ref_id);
4149 if (err) {
4150 if (err->code != GOT_ERR_OBJ_TYPE) {
4151 free(ref_id);
4152 break;
4154 /* Ref points at something other than a tag. */
4155 err = NULL;
4156 tag = NULL;
4159 cmp = got_object_id_cmp(tag ?
4160 got_object_tag_get_object_id(tag) : ref_id, id);
4161 free(ref_id);
4162 if (tag)
4163 got_object_tag_close(tag);
4164 if (cmp != 0)
4165 continue;
4166 s = *refs_str;
4167 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4168 s ? ", " : "", name) == -1) {
4169 err = got_error_from_errno("asprintf");
4170 free(s);
4171 *refs_str = NULL;
4172 break;
4174 free(s);
4177 return err;
4180 static const struct got_error *
4181 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4182 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4184 const struct got_error *err = NULL;
4185 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4186 char *comma, *s, *nl;
4187 struct got_reflist_head *refs;
4188 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4189 struct tm tm;
4190 time_t committer_time;
4192 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4193 if (refs) {
4194 err = build_refs_str(&ref_str, refs, id, repo, 1);
4195 if (err)
4196 return err;
4198 /* Display the first matching ref only. */
4199 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4200 *comma = '\0';
4203 if (ref_str == NULL) {
4204 err = got_object_id_str(&id_str, id);
4205 if (err)
4206 return err;
4209 committer_time = got_object_commit_get_committer_time(commit);
4210 if (gmtime_r(&committer_time, &tm) == NULL) {
4211 err = got_error_from_errno("gmtime_r");
4212 goto done;
4214 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4215 err = got_error(GOT_ERR_NO_SPACE);
4216 goto done;
4219 err = got_object_commit_get_logmsg(&logmsg0, commit);
4220 if (err)
4221 goto done;
4223 s = logmsg0;
4224 while (isspace((unsigned char)s[0]))
4225 s++;
4227 nl = strchr(s, '\n');
4228 if (nl) {
4229 *nl = '\0';
4232 if (ref_str)
4233 printf("%s%-7s %s\n", datebuf, ref_str, s);
4234 else
4235 printf("%s%.7s %s\n", datebuf, id_str, s);
4237 if (fflush(stdout) != 0 && err == NULL)
4238 err = got_error_from_errno("fflush");
4239 done:
4240 free(id_str);
4241 free(ref_str);
4242 free(logmsg0);
4243 return err;
4246 static const struct got_error *
4247 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4249 struct got_pathlist_entry *pe;
4251 if (header != NULL)
4252 printf("%s\n", header);
4254 TAILQ_FOREACH(pe, dsa->paths, entry) {
4255 struct got_diff_changed_path *cp = pe->data;
4256 int pad = dsa->max_path_len - pe->path_len + 1;
4258 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4259 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4261 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4262 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4263 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4265 if (fflush(stdout) != 0)
4266 return got_error_from_errno("fflush");
4268 return NULL;
4271 static const struct got_error *
4272 printfile(FILE *f)
4274 char buf[8192];
4275 size_t r;
4277 if (fseeko(f, 0L, SEEK_SET) == -1)
4278 return got_error_from_errno("fseek");
4280 for (;;) {
4281 r = fread(buf, 1, sizeof(buf), f);
4282 if (r == 0) {
4283 if (ferror(f))
4284 return got_error_from_errno("fread");
4285 if (feof(f))
4286 break;
4288 if (fwrite(buf, 1, r, stdout) != r)
4289 return got_ferror(stdout, GOT_ERR_IO);
4292 return NULL;
4295 static const struct got_error *
4296 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4297 struct got_repository *repo, const char *path,
4298 struct got_pathlist_head *changed_paths,
4299 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4300 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4301 const char *prefix)
4303 const struct got_error *err = NULL;
4304 FILE *f = NULL;
4305 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4306 char datebuf[26];
4307 time_t committer_time;
4308 const char *author, *committer;
4309 char *refs_str = NULL;
4311 err = got_object_id_str(&id_str, id);
4312 if (err)
4313 return err;
4315 if (custom_refs_str == NULL) {
4316 struct got_reflist_head *refs;
4317 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4318 if (refs) {
4319 err = build_refs_str(&refs_str, refs, id, repo, 0);
4320 if (err)
4321 goto done;
4325 printf(GOT_COMMIT_SEP_STR);
4326 if (custom_refs_str)
4327 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4328 custom_refs_str);
4329 else
4330 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4331 refs_str ? " (" : "", refs_str ? refs_str : "",
4332 refs_str ? ")" : "");
4333 free(id_str);
4334 id_str = NULL;
4335 free(refs_str);
4336 refs_str = NULL;
4337 printf("from: %s\n", got_object_commit_get_author(commit));
4338 author = got_object_commit_get_author(commit);
4339 committer = got_object_commit_get_committer(commit);
4340 if (strcmp(author, committer) != 0)
4341 printf("via: %s\n", committer);
4342 committer_time = got_object_commit_get_committer_time(commit);
4343 datestr = get_datestr(&committer_time, datebuf);
4344 if (datestr)
4345 printf("date: %s UTC\n", datestr);
4346 if (got_object_commit_get_nparents(commit) > 1) {
4347 const struct got_object_id_queue *parent_ids;
4348 struct got_object_qid *qid;
4349 int n = 1;
4350 parent_ids = got_object_commit_get_parent_ids(commit);
4351 STAILQ_FOREACH(qid, parent_ids, entry) {
4352 err = got_object_id_str(&id_str, &qid->id);
4353 if (err)
4354 goto done;
4355 printf("parent %d: %s\n", n++, id_str);
4356 free(id_str);
4357 id_str = NULL;
4361 err = got_object_commit_get_logmsg(&logmsg0, commit);
4362 if (err)
4363 goto done;
4365 logmsg = logmsg0;
4366 do {
4367 line = strsep(&logmsg, "\n");
4368 if (line)
4369 printf(" %s\n", line);
4370 } while (line);
4371 free(logmsg0);
4373 if (changed_paths && diffstat == NULL) {
4374 struct got_pathlist_entry *pe;
4376 TAILQ_FOREACH(pe, changed_paths, entry) {
4377 struct got_diff_changed_path *cp = pe->data;
4379 printf(" %c %s\n", cp->status, pe->path);
4381 printf("\n");
4383 if (show_patch) {
4384 if (diffstat) {
4385 f = got_opentemp();
4386 if (f == NULL) {
4387 err = got_error_from_errno("got_opentemp");
4388 goto done;
4392 err = print_patch(commit, id, path, diff_context, diffstat,
4393 repo, diffstat == NULL ? stdout : f);
4394 if (err)
4395 goto done;
4397 if (diffstat) {
4398 err = print_diffstat(diffstat, NULL);
4399 if (err)
4400 goto done;
4401 if (show_patch) {
4402 err = printfile(f);
4403 if (err)
4404 goto done;
4407 if (show_patch)
4408 printf("\n");
4410 if (fflush(stdout) != 0 && err == NULL)
4411 err = got_error_from_errno("fflush");
4412 done:
4413 if (f && fclose(f) == EOF && err == NULL)
4414 err = got_error_from_errno("fclose");
4415 free(id_str);
4416 free(refs_str);
4417 return err;
4420 static const struct got_error *
4421 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4422 struct got_repository *repo, const char *path, int show_changed_paths,
4423 int show_diffstat, int show_patch, const char *search_pattern,
4424 int diff_context, int limit, int log_branches, int reverse_display_order,
4425 struct got_reflist_object_id_map *refs_idmap, int one_line,
4426 FILE *tmpfile)
4428 const struct got_error *err;
4429 struct got_commit_graph *graph;
4430 regex_t regex;
4431 int have_match;
4432 struct got_object_id_queue reversed_commits;
4433 struct got_object_qid *qid;
4434 struct got_commit_object *commit;
4435 struct got_pathlist_head changed_paths;
4437 STAILQ_INIT(&reversed_commits);
4438 TAILQ_INIT(&changed_paths);
4440 if (search_pattern && regcomp(&regex, search_pattern,
4441 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4442 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4444 err = got_commit_graph_open(&graph, path, !log_branches);
4445 if (err)
4446 return err;
4447 err = got_commit_graph_iter_start(graph, root_id, repo,
4448 check_cancelled, NULL);
4449 if (err)
4450 goto done;
4451 for (;;) {
4452 struct got_object_id id;
4453 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4454 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4456 if (sigint_received || sigpipe_received)
4457 break;
4459 err = got_commit_graph_iter_next(&id, graph, repo,
4460 check_cancelled, NULL);
4461 if (err) {
4462 if (err->code == GOT_ERR_ITER_COMPLETED)
4463 err = NULL;
4464 break;
4467 err = got_object_open_as_commit(&commit, repo, &id);
4468 if (err)
4469 break;
4471 if (((show_changed_paths && !show_diffstat) ||
4472 (show_diffstat && !show_patch))
4473 && !reverse_display_order) {
4474 err = get_changed_paths(&changed_paths, commit, repo,
4475 show_diffstat ? &dsa : NULL);
4476 if (err)
4477 break;
4480 if (search_pattern) {
4481 err = match_commit(&have_match, &id, commit, &regex);
4482 if (err) {
4483 got_object_commit_close(commit);
4484 break;
4486 if (have_match == 0 && show_changed_paths)
4487 match_changed_paths(&have_match,
4488 &changed_paths, &regex);
4489 if (have_match == 0 && show_patch) {
4490 err = match_patch(&have_match, commit, &id,
4491 path, diff_context, repo, &regex, tmpfile);
4492 if (err)
4493 break;
4495 if (have_match == 0) {
4496 got_object_commit_close(commit);
4497 got_pathlist_free(&changed_paths,
4498 GOT_PATHLIST_FREE_ALL);
4499 continue;
4503 if (reverse_display_order) {
4504 err = got_object_qid_alloc(&qid, &id);
4505 if (err)
4506 break;
4507 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4508 got_object_commit_close(commit);
4509 } else {
4510 if (one_line)
4511 err = print_commit_oneline(commit, &id,
4512 repo, refs_idmap);
4513 else
4514 err = print_commit(commit, &id, repo, path,
4515 (show_changed_paths || show_diffstat) ?
4516 &changed_paths : NULL,
4517 show_diffstat ? &dsa : NULL, show_patch,
4518 diff_context, refs_idmap, NULL, NULL);
4519 got_object_commit_close(commit);
4520 if (err)
4521 break;
4523 if ((limit && --limit == 0) ||
4524 (end_id && got_object_id_cmp(&id, end_id) == 0))
4525 break;
4527 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4529 if (reverse_display_order) {
4530 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4531 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4532 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4534 err = got_object_open_as_commit(&commit, repo,
4535 &qid->id);
4536 if (err)
4537 break;
4538 if ((show_changed_paths && !show_diffstat) ||
4539 (show_diffstat && !show_patch)) {
4540 err = get_changed_paths(&changed_paths, commit,
4541 repo, show_diffstat ? &dsa : NULL);
4542 if (err)
4543 break;
4545 if (one_line)
4546 err = print_commit_oneline(commit, &qid->id,
4547 repo, refs_idmap);
4548 else
4549 err = print_commit(commit, &qid->id, repo, path,
4550 (show_changed_paths || show_diffstat) ?
4551 &changed_paths : NULL,
4552 show_diffstat ? &dsa : NULL, show_patch,
4553 diff_context, refs_idmap, NULL, NULL);
4554 got_object_commit_close(commit);
4555 if (err)
4556 break;
4557 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4560 done:
4561 while (!STAILQ_EMPTY(&reversed_commits)) {
4562 qid = STAILQ_FIRST(&reversed_commits);
4563 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4564 got_object_qid_free(qid);
4566 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4567 if (search_pattern)
4568 regfree(&regex);
4569 got_commit_graph_close(graph);
4570 return err;
4573 __dead static void
4574 usage_log(void)
4576 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4577 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4578 "[path]\n", getprogname());
4579 exit(1);
4582 static int
4583 get_default_log_limit(void)
4585 const char *got_default_log_limit;
4586 long long n;
4587 const char *errstr;
4589 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4590 if (got_default_log_limit == NULL)
4591 return 0;
4592 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4593 if (errstr != NULL)
4594 return 0;
4595 return n;
4598 static const struct got_error *
4599 cmd_log(int argc, char *argv[])
4601 const struct got_error *error;
4602 struct got_repository *repo = NULL;
4603 struct got_worktree *worktree = NULL;
4604 struct got_object_id *start_id = NULL, *end_id = NULL;
4605 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4606 char *keyword_idstr = NULL;
4607 const char *start_commit = NULL, *end_commit = NULL;
4608 const char *search_pattern = NULL;
4609 int diff_context = -1, ch;
4610 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4611 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4612 const char *errstr;
4613 struct got_reflist_head refs;
4614 struct got_reflist_object_id_map *refs_idmap = NULL;
4615 FILE *tmpfile = NULL;
4616 int *pack_fds = NULL;
4618 TAILQ_INIT(&refs);
4620 #ifndef PROFILE
4621 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4622 NULL)
4623 == -1)
4624 err(1, "pledge");
4625 #endif
4627 limit = get_default_log_limit();
4629 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4630 switch (ch) {
4631 case 'b':
4632 log_branches = 1;
4633 break;
4634 case 'C':
4635 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4636 &errstr);
4637 if (errstr != NULL)
4638 errx(1, "number of context lines is %s: %s",
4639 errstr, optarg);
4640 break;
4641 case 'c':
4642 start_commit = optarg;
4643 break;
4644 case 'd':
4645 show_diffstat = 1;
4646 break;
4647 case 'l':
4648 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4649 if (errstr != NULL)
4650 errx(1, "number of commits is %s: %s",
4651 errstr, optarg);
4652 break;
4653 case 'P':
4654 show_changed_paths = 1;
4655 break;
4656 case 'p':
4657 show_patch = 1;
4658 break;
4659 case 'R':
4660 reverse_display_order = 1;
4661 break;
4662 case 'r':
4663 repo_path = realpath(optarg, NULL);
4664 if (repo_path == NULL)
4665 return got_error_from_errno2("realpath",
4666 optarg);
4667 got_path_strip_trailing_slashes(repo_path);
4668 break;
4669 case 'S':
4670 search_pattern = optarg;
4671 break;
4672 case 's':
4673 one_line = 1;
4674 break;
4675 case 'x':
4676 end_commit = optarg;
4677 break;
4678 default:
4679 usage_log();
4680 /* NOTREACHED */
4684 argc -= optind;
4685 argv += optind;
4687 if (diff_context == -1)
4688 diff_context = 3;
4689 else if (!show_patch)
4690 errx(1, "-C requires -p");
4692 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4693 errx(1, "cannot use -s with -d, -p or -P");
4695 cwd = getcwd(NULL, 0);
4696 if (cwd == NULL) {
4697 error = got_error_from_errno("getcwd");
4698 goto done;
4701 error = got_repo_pack_fds_open(&pack_fds);
4702 if (error != NULL)
4703 goto done;
4705 if (repo_path == NULL) {
4706 error = got_worktree_open(&worktree, cwd,
4707 GOT_WORKTREE_GOT_DIR);
4708 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4709 goto done;
4710 error = NULL;
4713 if (argc == 1) {
4714 if (worktree) {
4715 error = got_worktree_resolve_path(&path, worktree,
4716 argv[0]);
4717 if (error)
4718 goto done;
4719 } else {
4720 path = strdup(argv[0]);
4721 if (path == NULL) {
4722 error = got_error_from_errno("strdup");
4723 goto done;
4726 } else if (argc != 0)
4727 usage_log();
4729 if (repo_path == NULL) {
4730 repo_path = worktree ?
4731 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4733 if (repo_path == NULL) {
4734 error = got_error_from_errno("strdup");
4735 goto done;
4738 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4739 if (error != NULL)
4740 goto done;
4742 error = apply_unveil(got_repo_get_path(repo), 1,
4743 worktree ? got_worktree_get_root_path(worktree) : NULL);
4744 if (error)
4745 goto done;
4747 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4748 if (error)
4749 goto done;
4751 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4752 if (error)
4753 goto done;
4755 if (start_commit == NULL) {
4756 struct got_reference *head_ref;
4757 struct got_commit_object *commit = NULL;
4758 error = got_ref_open(&head_ref, repo,
4759 worktree ? got_worktree_get_head_ref_name(worktree)
4760 : GOT_REF_HEAD, 0);
4761 if (error != NULL)
4762 goto done;
4763 error = got_ref_resolve(&start_id, repo, head_ref);
4764 got_ref_close(head_ref);
4765 if (error != NULL)
4766 goto done;
4767 error = got_object_open_as_commit(&commit, repo,
4768 start_id);
4769 if (error != NULL)
4770 goto done;
4771 got_object_commit_close(commit);
4772 } else {
4773 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4774 repo, worktree);
4775 if (error != NULL)
4776 goto done;
4777 if (keyword_idstr != NULL)
4778 start_commit = keyword_idstr;
4780 error = got_repo_match_object_id(&start_id, NULL,
4781 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4782 if (error != NULL)
4783 goto done;
4785 if (end_commit != NULL) {
4786 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4787 repo, worktree);
4788 if (error != NULL)
4789 goto done;
4790 if (keyword_idstr != NULL)
4791 end_commit = keyword_idstr;
4793 error = got_repo_match_object_id(&end_id, NULL,
4794 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4795 if (error != NULL)
4796 goto done;
4799 if (worktree) {
4801 * If a path was specified on the command line it was resolved
4802 * to a path in the work tree above. Prepend the work tree's
4803 * path prefix to obtain the corresponding in-repository path.
4805 if (path) {
4806 const char *prefix;
4807 prefix = got_worktree_get_path_prefix(worktree);
4808 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4809 (path[0] != '\0') ? "/" : "", path) == -1) {
4810 error = got_error_from_errno("asprintf");
4811 goto done;
4814 } else
4815 error = got_repo_map_path(&in_repo_path, repo,
4816 path ? path : "");
4817 if (error != NULL)
4818 goto done;
4819 if (in_repo_path) {
4820 free(path);
4821 path = in_repo_path;
4824 if (worktree) {
4825 /* Release work tree lock. */
4826 got_worktree_close(worktree);
4827 worktree = NULL;
4830 if (search_pattern && show_patch) {
4831 tmpfile = got_opentemp();
4832 if (tmpfile == NULL) {
4833 error = got_error_from_errno("got_opentemp");
4834 goto done;
4838 error = print_commits(start_id, end_id, repo, path ? path : "",
4839 show_changed_paths, show_diffstat, show_patch, search_pattern,
4840 diff_context, limit, log_branches, reverse_display_order,
4841 refs_idmap, one_line, tmpfile);
4842 done:
4843 free(path);
4844 free(repo_path);
4845 free(cwd);
4846 free(start_id);
4847 free(end_id);
4848 free(keyword_idstr);
4849 if (worktree)
4850 got_worktree_close(worktree);
4851 if (repo) {
4852 const struct got_error *close_err = got_repo_close(repo);
4853 if (error == NULL)
4854 error = close_err;
4856 if (pack_fds) {
4857 const struct got_error *pack_err =
4858 got_repo_pack_fds_close(pack_fds);
4859 if (error == NULL)
4860 error = pack_err;
4862 if (refs_idmap)
4863 got_reflist_object_id_map_free(refs_idmap);
4864 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4865 error = got_error_from_errno("fclose");
4866 got_ref_list_free(&refs);
4867 return error;
4870 __dead static void
4871 usage_diff(void)
4873 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4874 "[-r repository-path] [object1 object2 | path ...]\n",
4875 getprogname());
4876 exit(1);
4879 struct print_diff_arg {
4880 struct got_repository *repo;
4881 struct got_worktree *worktree;
4882 struct got_diffstat_cb_arg *diffstat;
4883 int diff_context;
4884 const char *id_str;
4885 int header_shown;
4886 int diff_staged;
4887 enum got_diff_algorithm diff_algo;
4888 int ignore_whitespace;
4889 int force_text_diff;
4890 FILE *f1;
4891 FILE *f2;
4892 FILE *outfile;
4896 * Create a file which contains the target path of a symlink so we can feed
4897 * it as content to the diff engine.
4899 static const struct got_error *
4900 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4901 const char *abspath)
4903 const struct got_error *err = NULL;
4904 char target_path[PATH_MAX];
4905 ssize_t target_len, outlen;
4907 *fd = -1;
4909 if (dirfd != -1) {
4910 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4911 if (target_len == -1)
4912 return got_error_from_errno2("readlinkat", abspath);
4913 } else {
4914 target_len = readlink(abspath, target_path, PATH_MAX);
4915 if (target_len == -1)
4916 return got_error_from_errno2("readlink", abspath);
4919 *fd = got_opentempfd();
4920 if (*fd == -1)
4921 return got_error_from_errno("got_opentempfd");
4923 outlen = write(*fd, target_path, target_len);
4924 if (outlen == -1) {
4925 err = got_error_from_errno("got_opentempfd");
4926 goto done;
4929 if (lseek(*fd, 0, SEEK_SET) == -1) {
4930 err = got_error_from_errno2("lseek", abspath);
4931 goto done;
4933 done:
4934 if (err) {
4935 close(*fd);
4936 *fd = -1;
4938 return err;
4941 static const struct got_error *
4942 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4943 const char *path, struct got_object_id *blob_id,
4944 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4945 int dirfd, const char *de_name)
4947 struct print_diff_arg *a = arg;
4948 const struct got_error *err = NULL;
4949 struct got_blob_object *blob1 = NULL;
4950 int fd = -1, fd1 = -1, fd2 = -1;
4951 FILE *f2 = NULL;
4952 char *abspath = NULL, *label1 = NULL;
4953 struct stat sb;
4954 off_t size1 = 0;
4955 int f2_exists = 0;
4957 memset(&sb, 0, sizeof(sb));
4959 if (a->diff_staged) {
4960 if (staged_status != GOT_STATUS_MODIFY &&
4961 staged_status != GOT_STATUS_ADD &&
4962 staged_status != GOT_STATUS_DELETE)
4963 return NULL;
4964 } else {
4965 if (staged_status == GOT_STATUS_DELETE)
4966 return NULL;
4967 if (status == GOT_STATUS_NONEXISTENT)
4968 return got_error_set_errno(ENOENT, path);
4969 if (status != GOT_STATUS_MODIFY &&
4970 status != GOT_STATUS_ADD &&
4971 status != GOT_STATUS_DELETE &&
4972 status != GOT_STATUS_CONFLICT)
4973 return NULL;
4976 err = got_opentemp_truncate(a->f1);
4977 if (err)
4978 return got_error_from_errno("got_opentemp_truncate");
4979 err = got_opentemp_truncate(a->f2);
4980 if (err)
4981 return got_error_from_errno("got_opentemp_truncate");
4983 if (!a->header_shown) {
4984 if (fprintf(a->outfile, "diff %s%s\n",
4985 a->diff_staged ? "-s " : "",
4986 got_worktree_get_root_path(a->worktree)) < 0) {
4987 err = got_error_from_errno("fprintf");
4988 goto done;
4990 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4991 err = got_error_from_errno("fprintf");
4992 goto done;
4994 if (fprintf(a->outfile, "path + %s%s\n",
4995 got_worktree_get_root_path(a->worktree),
4996 a->diff_staged ? " (staged changes)" : "") < 0) {
4997 err = got_error_from_errno("fprintf");
4998 goto done;
5000 a->header_shown = 1;
5003 if (a->diff_staged) {
5004 const char *label1 = NULL, *label2 = NULL;
5005 switch (staged_status) {
5006 case GOT_STATUS_MODIFY:
5007 label1 = path;
5008 label2 = path;
5009 break;
5010 case GOT_STATUS_ADD:
5011 label2 = path;
5012 break;
5013 case GOT_STATUS_DELETE:
5014 label1 = path;
5015 break;
5016 default:
5017 return got_error(GOT_ERR_FILE_STATUS);
5019 fd1 = got_opentempfd();
5020 if (fd1 == -1) {
5021 err = got_error_from_errno("got_opentempfd");
5022 goto done;
5024 fd2 = got_opentempfd();
5025 if (fd2 == -1) {
5026 err = got_error_from_errno("got_opentempfd");
5027 goto done;
5029 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5030 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5031 a->diff_algo, a->diff_context, a->ignore_whitespace,
5032 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5033 goto done;
5036 fd1 = got_opentempfd();
5037 if (fd1 == -1) {
5038 err = got_error_from_errno("got_opentempfd");
5039 goto done;
5042 if (staged_status == GOT_STATUS_ADD ||
5043 staged_status == GOT_STATUS_MODIFY) {
5044 char *id_str;
5045 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5046 8192, fd1);
5047 if (err)
5048 goto done;
5049 err = got_object_id_str(&id_str, staged_blob_id);
5050 if (err)
5051 goto done;
5052 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5053 err = got_error_from_errno("asprintf");
5054 free(id_str);
5055 goto done;
5057 free(id_str);
5058 } else if (status != GOT_STATUS_ADD) {
5059 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5060 fd1);
5061 if (err)
5062 goto done;
5065 if (status != GOT_STATUS_DELETE) {
5066 if (asprintf(&abspath, "%s/%s",
5067 got_worktree_get_root_path(a->worktree), path) == -1) {
5068 err = got_error_from_errno("asprintf");
5069 goto done;
5072 if (dirfd != -1) {
5073 fd = openat(dirfd, de_name,
5074 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5075 if (fd == -1) {
5076 if (!got_err_open_nofollow_on_symlink()) {
5077 err = got_error_from_errno2("openat",
5078 abspath);
5079 goto done;
5081 err = get_symlink_target_file(&fd, dirfd,
5082 de_name, abspath);
5083 if (err)
5084 goto done;
5086 } else {
5087 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5088 if (fd == -1) {
5089 if (!got_err_open_nofollow_on_symlink()) {
5090 err = got_error_from_errno2("open",
5091 abspath);
5092 goto done;
5094 err = get_symlink_target_file(&fd, dirfd,
5095 de_name, abspath);
5096 if (err)
5097 goto done;
5100 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5101 err = got_error_from_errno2("fstatat", abspath);
5102 goto done;
5104 f2 = fdopen(fd, "r");
5105 if (f2 == NULL) {
5106 err = got_error_from_errno2("fdopen", abspath);
5107 goto done;
5109 fd = -1;
5110 f2_exists = 1;
5113 if (blob1) {
5114 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5115 a->f1, blob1);
5116 if (err)
5117 goto done;
5120 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5121 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5122 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5123 done:
5124 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5125 err = got_error_from_errno("close");
5126 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5127 err = got_error_from_errno("close");
5128 if (blob1)
5129 got_object_blob_close(blob1);
5130 if (fd != -1 && close(fd) == -1 && err == NULL)
5131 err = got_error_from_errno("close");
5132 if (f2 && fclose(f2) == EOF && err == NULL)
5133 err = got_error_from_errno("fclose");
5134 free(abspath);
5135 return err;
5138 static const struct got_error *
5139 cmd_diff(int argc, char *argv[])
5141 const struct got_error *error;
5142 struct got_repository *repo = NULL;
5143 struct got_worktree *worktree = NULL;
5144 char *cwd = NULL, *repo_path = NULL;
5145 const char *commit_args[2] = { NULL, NULL };
5146 int ncommit_args = 0;
5147 struct got_object_id *ids[2] = { NULL, NULL };
5148 char *labels[2] = { NULL, NULL };
5149 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5150 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5151 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5152 const char *errstr;
5153 struct got_reflist_head refs;
5154 struct got_pathlist_head diffstat_paths, paths;
5155 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5156 int fd1 = -1, fd2 = -1;
5157 int *pack_fds = NULL;
5158 struct got_diffstat_cb_arg dsa;
5160 memset(&dsa, 0, sizeof(dsa));
5162 TAILQ_INIT(&refs);
5163 TAILQ_INIT(&paths);
5164 TAILQ_INIT(&diffstat_paths);
5166 #ifndef PROFILE
5167 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5168 NULL) == -1)
5169 err(1, "pledge");
5170 #endif
5172 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5173 switch (ch) {
5174 case 'a':
5175 force_text_diff = 1;
5176 break;
5177 case 'C':
5178 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5179 &errstr);
5180 if (errstr != NULL)
5181 errx(1, "number of context lines is %s: %s",
5182 errstr, optarg);
5183 break;
5184 case 'c':
5185 if (ncommit_args >= 2)
5186 errx(1, "too many -c options used");
5187 commit_args[ncommit_args++] = optarg;
5188 break;
5189 case 'd':
5190 show_diffstat = 1;
5191 break;
5192 case 'P':
5193 force_path = 1;
5194 break;
5195 case 'r':
5196 repo_path = realpath(optarg, NULL);
5197 if (repo_path == NULL)
5198 return got_error_from_errno2("realpath",
5199 optarg);
5200 got_path_strip_trailing_slashes(repo_path);
5201 rflag = 1;
5202 break;
5203 case 's':
5204 diff_staged = 1;
5205 break;
5206 case 'w':
5207 ignore_whitespace = 1;
5208 break;
5209 default:
5210 usage_diff();
5211 /* NOTREACHED */
5215 argc -= optind;
5216 argv += optind;
5218 cwd = getcwd(NULL, 0);
5219 if (cwd == NULL) {
5220 error = got_error_from_errno("getcwd");
5221 goto done;
5224 error = got_repo_pack_fds_open(&pack_fds);
5225 if (error != NULL)
5226 goto done;
5228 if (repo_path == NULL) {
5229 error = got_worktree_open(&worktree, cwd,
5230 GOT_WORKTREE_GOT_DIR);
5231 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5232 goto done;
5233 else
5234 error = NULL;
5235 if (worktree) {
5236 repo_path =
5237 strdup(got_worktree_get_repo_path(worktree));
5238 if (repo_path == NULL) {
5239 error = got_error_from_errno("strdup");
5240 goto done;
5242 } else {
5243 repo_path = strdup(cwd);
5244 if (repo_path == NULL) {
5245 error = got_error_from_errno("strdup");
5246 goto done;
5251 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5252 free(repo_path);
5253 if (error != NULL)
5254 goto done;
5256 if (show_diffstat) {
5257 dsa.paths = &diffstat_paths;
5258 dsa.force_text = force_text_diff;
5259 dsa.ignore_ws = ignore_whitespace;
5260 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5263 if (rflag || worktree == NULL || ncommit_args > 0) {
5264 if (force_path) {
5265 error = got_error_msg(GOT_ERR_NOT_IMPL,
5266 "-P option can only be used when diffing "
5267 "a work tree");
5268 goto done;
5270 if (diff_staged) {
5271 error = got_error_msg(GOT_ERR_NOT_IMPL,
5272 "-s option can only be used when diffing "
5273 "a work tree");
5274 goto done;
5278 error = apply_unveil(got_repo_get_path(repo), 1,
5279 worktree ? got_worktree_get_root_path(worktree) : NULL);
5280 if (error)
5281 goto done;
5283 if ((!force_path && argc == 2) || ncommit_args > 0) {
5284 int obj_type = (ncommit_args > 0 ?
5285 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5286 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5287 NULL);
5288 if (error)
5289 goto done;
5290 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5291 const char *arg;
5292 char *keyword_idstr = NULL;
5294 if (ncommit_args > 0)
5295 arg = commit_args[i];
5296 else
5297 arg = argv[i];
5299 error = got_keyword_to_idstr(&keyword_idstr, arg,
5300 repo, worktree);
5301 if (error != NULL)
5302 goto done;
5303 if (keyword_idstr != NULL)
5304 arg = keyword_idstr;
5306 error = got_repo_match_object_id(&ids[i], &labels[i],
5307 arg, obj_type, &refs, repo);
5308 free(keyword_idstr);
5309 if (error) {
5310 if (error->code != GOT_ERR_NOT_REF &&
5311 error->code != GOT_ERR_NO_OBJ)
5312 goto done;
5313 if (ncommit_args > 0)
5314 goto done;
5315 error = NULL;
5316 break;
5321 f1 = got_opentemp();
5322 if (f1 == NULL) {
5323 error = got_error_from_errno("got_opentemp");
5324 goto done;
5327 f2 = got_opentemp();
5328 if (f2 == NULL) {
5329 error = got_error_from_errno("got_opentemp");
5330 goto done;
5333 outfile = got_opentemp();
5334 if (outfile == NULL) {
5335 error = got_error_from_errno("got_opentemp");
5336 goto done;
5339 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5340 struct print_diff_arg arg;
5341 char *id_str;
5343 if (worktree == NULL) {
5344 if (argc == 2 && ids[0] == NULL) {
5345 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5346 goto done;
5347 } else if (argc == 2 && ids[1] == NULL) {
5348 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5349 goto done;
5350 } else if (argc > 0) {
5351 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5352 "%s", "specified paths cannot be resolved");
5353 goto done;
5354 } else {
5355 error = got_error(GOT_ERR_NOT_WORKTREE);
5356 goto done;
5360 error = get_worktree_paths_from_argv(&paths, argc, argv,
5361 worktree);
5362 if (error)
5363 goto done;
5365 error = got_object_id_str(&id_str,
5366 got_worktree_get_base_commit_id(worktree));
5367 if (error)
5368 goto done;
5369 arg.repo = repo;
5370 arg.worktree = worktree;
5371 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5372 arg.diff_context = diff_context;
5373 arg.id_str = id_str;
5374 arg.header_shown = 0;
5375 arg.diff_staged = diff_staged;
5376 arg.ignore_whitespace = ignore_whitespace;
5377 arg.force_text_diff = force_text_diff;
5378 arg.diffstat = show_diffstat ? &dsa : NULL;
5379 arg.f1 = f1;
5380 arg.f2 = f2;
5381 arg.outfile = outfile;
5383 error = got_worktree_status(worktree, &paths, repo, 0,
5384 print_diff, &arg, check_cancelled, NULL);
5385 free(id_str);
5386 if (error)
5387 goto done;
5389 if (show_diffstat && dsa.nfiles > 0) {
5390 char *header;
5392 if (asprintf(&header, "diffstat %s%s",
5393 diff_staged ? "-s " : "",
5394 got_worktree_get_root_path(worktree)) == -1) {
5395 error = got_error_from_errno("asprintf");
5396 goto done;
5399 error = print_diffstat(&dsa, header);
5400 free(header);
5401 if (error)
5402 goto done;
5405 error = printfile(outfile);
5406 goto done;
5409 if (ncommit_args == 1) {
5410 struct got_commit_object *commit;
5411 error = got_object_open_as_commit(&commit, repo, ids[0]);
5412 if (error)
5413 goto done;
5415 labels[1] = labels[0];
5416 ids[1] = ids[0];
5417 if (got_object_commit_get_nparents(commit) > 0) {
5418 const struct got_object_id_queue *pids;
5419 struct got_object_qid *pid;
5420 pids = got_object_commit_get_parent_ids(commit);
5421 pid = STAILQ_FIRST(pids);
5422 ids[0] = got_object_id_dup(&pid->id);
5423 if (ids[0] == NULL) {
5424 error = got_error_from_errno(
5425 "got_object_id_dup");
5426 got_object_commit_close(commit);
5427 goto done;
5429 error = got_object_id_str(&labels[0], ids[0]);
5430 if (error) {
5431 got_object_commit_close(commit);
5432 goto done;
5434 } else {
5435 ids[0] = NULL;
5436 labels[0] = strdup("/dev/null");
5437 if (labels[0] == NULL) {
5438 error = got_error_from_errno("strdup");
5439 got_object_commit_close(commit);
5440 goto done;
5444 got_object_commit_close(commit);
5447 if (ncommit_args == 0 && argc > 2) {
5448 error = got_error_msg(GOT_ERR_BAD_PATH,
5449 "path arguments cannot be used when diffing two objects");
5450 goto done;
5453 if (ids[0]) {
5454 error = got_object_get_type(&type1, repo, ids[0]);
5455 if (error)
5456 goto done;
5459 error = got_object_get_type(&type2, repo, ids[1]);
5460 if (error)
5461 goto done;
5462 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5463 error = got_error(GOT_ERR_OBJ_TYPE);
5464 goto done;
5466 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5467 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5468 "path arguments cannot be used when diffing blobs");
5469 goto done;
5472 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5473 char *in_repo_path;
5474 struct got_pathlist_entry *new;
5475 if (worktree) {
5476 const char *prefix;
5477 char *p;
5478 error = got_worktree_resolve_path(&p, worktree,
5479 argv[i]);
5480 if (error)
5481 goto done;
5482 prefix = got_worktree_get_path_prefix(worktree);
5483 while (prefix[0] == '/')
5484 prefix++;
5485 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5486 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5487 p) == -1) {
5488 error = got_error_from_errno("asprintf");
5489 free(p);
5490 goto done;
5492 free(p);
5493 } else {
5494 char *mapped_path, *s;
5495 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5496 if (error)
5497 goto done;
5498 s = mapped_path;
5499 while (s[0] == '/')
5500 s++;
5501 in_repo_path = strdup(s);
5502 if (in_repo_path == NULL) {
5503 error = got_error_from_errno("asprintf");
5504 free(mapped_path);
5505 goto done;
5507 free(mapped_path);
5510 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5511 if (error || new == NULL /* duplicate */)
5512 free(in_repo_path);
5513 if (error)
5514 goto done;
5517 if (worktree) {
5518 /* Release work tree lock. */
5519 got_worktree_close(worktree);
5520 worktree = NULL;
5523 fd1 = got_opentempfd();
5524 if (fd1 == -1) {
5525 error = got_error_from_errno("got_opentempfd");
5526 goto done;
5529 fd2 = got_opentempfd();
5530 if (fd2 == -1) {
5531 error = got_error_from_errno("got_opentempfd");
5532 goto done;
5535 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5536 case GOT_OBJ_TYPE_BLOB:
5537 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5538 fd1, fd2, ids[0], ids[1], NULL, NULL,
5539 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5540 ignore_whitespace, force_text_diff,
5541 show_diffstat ? &dsa : NULL, repo, outfile);
5542 break;
5543 case GOT_OBJ_TYPE_TREE:
5544 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5545 ids[0], ids[1], &paths, "", "",
5546 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5547 ignore_whitespace, force_text_diff,
5548 show_diffstat ? &dsa : NULL, repo, outfile);
5549 break;
5550 case GOT_OBJ_TYPE_COMMIT:
5551 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5552 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5553 fd1, fd2, ids[0], ids[1], &paths,
5554 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5555 ignore_whitespace, force_text_diff,
5556 show_diffstat ? &dsa : NULL, repo, outfile);
5557 break;
5558 default:
5559 error = got_error(GOT_ERR_OBJ_TYPE);
5561 if (error)
5562 goto done;
5564 if (show_diffstat && dsa.nfiles > 0) {
5565 char *header = NULL;
5567 if (asprintf(&header, "diffstat %s %s",
5568 labels[0], labels[1]) == -1) {
5569 error = got_error_from_errno("asprintf");
5570 goto done;
5573 error = print_diffstat(&dsa, header);
5574 free(header);
5575 if (error)
5576 goto done;
5579 error = printfile(outfile);
5581 done:
5582 free(labels[0]);
5583 free(labels[1]);
5584 free(ids[0]);
5585 free(ids[1]);
5586 if (worktree)
5587 got_worktree_close(worktree);
5588 if (repo) {
5589 const struct got_error *close_err = got_repo_close(repo);
5590 if (error == NULL)
5591 error = close_err;
5593 if (pack_fds) {
5594 const struct got_error *pack_err =
5595 got_repo_pack_fds_close(pack_fds);
5596 if (error == NULL)
5597 error = pack_err;
5599 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5600 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5601 got_ref_list_free(&refs);
5602 if (outfile && fclose(outfile) == EOF && error == NULL)
5603 error = got_error_from_errno("fclose");
5604 if (f1 && fclose(f1) == EOF && error == NULL)
5605 error = got_error_from_errno("fclose");
5606 if (f2 && fclose(f2) == EOF && error == NULL)
5607 error = got_error_from_errno("fclose");
5608 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5609 error = got_error_from_errno("close");
5610 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5611 error = got_error_from_errno("close");
5612 return error;
5615 __dead static void
5616 usage_blame(void)
5618 fprintf(stderr,
5619 "usage: %s blame [-c commit] [-r repository-path] path\n",
5620 getprogname());
5621 exit(1);
5624 struct blame_line {
5625 int annotated;
5626 char *id_str;
5627 char *committer;
5628 char datebuf[11]; /* YYYY-MM-DD + NUL */
5631 struct blame_cb_args {
5632 struct blame_line *lines;
5633 int nlines;
5634 int nlines_prec;
5635 int lineno_cur;
5636 off_t *line_offsets;
5637 FILE *f;
5638 struct got_repository *repo;
5641 static const struct got_error *
5642 blame_cb(void *arg, int nlines, int lineno,
5643 struct got_commit_object *commit, struct got_object_id *id)
5645 const struct got_error *err = NULL;
5646 struct blame_cb_args *a = arg;
5647 struct blame_line *bline;
5648 char *line = NULL;
5649 size_t linesize = 0;
5650 off_t offset;
5651 struct tm tm;
5652 time_t committer_time;
5654 if (nlines != a->nlines ||
5655 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5656 return got_error(GOT_ERR_RANGE);
5658 if (sigint_received)
5659 return got_error(GOT_ERR_ITER_COMPLETED);
5661 if (lineno == -1)
5662 return NULL; /* no change in this commit */
5664 /* Annotate this line. */
5665 bline = &a->lines[lineno - 1];
5666 if (bline->annotated)
5667 return NULL;
5668 err = got_object_id_str(&bline->id_str, id);
5669 if (err)
5670 return err;
5672 bline->committer = strdup(got_object_commit_get_committer(commit));
5673 if (bline->committer == NULL) {
5674 err = got_error_from_errno("strdup");
5675 goto done;
5678 committer_time = got_object_commit_get_committer_time(commit);
5679 if (gmtime_r(&committer_time, &tm) == NULL)
5680 return got_error_from_errno("gmtime_r");
5681 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5682 &tm) == 0) {
5683 err = got_error(GOT_ERR_NO_SPACE);
5684 goto done;
5686 bline->annotated = 1;
5688 /* Print lines annotated so far. */
5689 bline = &a->lines[a->lineno_cur - 1];
5690 if (!bline->annotated)
5691 goto done;
5693 offset = a->line_offsets[a->lineno_cur - 1];
5694 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5695 err = got_error_from_errno("fseeko");
5696 goto done;
5699 while (a->lineno_cur <= a->nlines && bline->annotated) {
5700 char *smallerthan, *at, *nl, *committer;
5701 size_t len;
5703 if (getline(&line, &linesize, a->f) == -1) {
5704 if (ferror(a->f))
5705 err = got_error_from_errno("getline");
5706 break;
5709 committer = bline->committer;
5710 smallerthan = strchr(committer, '<');
5711 if (smallerthan && smallerthan[1] != '\0')
5712 committer = smallerthan + 1;
5713 at = strchr(committer, '@');
5714 if (at)
5715 *at = '\0';
5716 len = strlen(committer);
5717 if (len >= 9)
5718 committer[8] = '\0';
5720 nl = strchr(line, '\n');
5721 if (nl)
5722 *nl = '\0';
5723 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5724 bline->id_str, bline->datebuf, committer, line);
5726 a->lineno_cur++;
5727 bline = &a->lines[a->lineno_cur - 1];
5729 done:
5730 free(line);
5731 return err;
5734 static const struct got_error *
5735 cmd_blame(int argc, char *argv[])
5737 const struct got_error *error;
5738 struct got_repository *repo = NULL;
5739 struct got_worktree *worktree = NULL;
5740 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5741 char *link_target = NULL;
5742 struct got_object_id *obj_id = NULL;
5743 struct got_object_id *commit_id = NULL;
5744 struct got_commit_object *commit = NULL;
5745 struct got_blob_object *blob = NULL;
5746 char *commit_id_str = NULL, *keyword_idstr = NULL;
5747 struct blame_cb_args bca;
5748 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5749 off_t filesize;
5750 int *pack_fds = NULL;
5751 FILE *f1 = NULL, *f2 = NULL;
5753 fd1 = got_opentempfd();
5754 if (fd1 == -1)
5755 return got_error_from_errno("got_opentempfd");
5757 memset(&bca, 0, sizeof(bca));
5759 #ifndef PROFILE
5760 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5761 NULL) == -1)
5762 err(1, "pledge");
5763 #endif
5765 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5766 switch (ch) {
5767 case 'c':
5768 commit_id_str = optarg;
5769 break;
5770 case 'r':
5771 repo_path = realpath(optarg, NULL);
5772 if (repo_path == NULL)
5773 return got_error_from_errno2("realpath",
5774 optarg);
5775 got_path_strip_trailing_slashes(repo_path);
5776 break;
5777 default:
5778 usage_blame();
5779 /* NOTREACHED */
5783 argc -= optind;
5784 argv += optind;
5786 if (argc == 1)
5787 path = argv[0];
5788 else
5789 usage_blame();
5791 cwd = getcwd(NULL, 0);
5792 if (cwd == NULL) {
5793 error = got_error_from_errno("getcwd");
5794 goto done;
5797 error = got_repo_pack_fds_open(&pack_fds);
5798 if (error != NULL)
5799 goto done;
5801 if (repo_path == NULL) {
5802 error = got_worktree_open(&worktree, cwd,
5803 GOT_WORKTREE_GOT_DIR);
5804 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5805 goto done;
5806 else
5807 error = NULL;
5808 if (worktree) {
5809 repo_path =
5810 strdup(got_worktree_get_repo_path(worktree));
5811 if (repo_path == NULL) {
5812 error = got_error_from_errno("strdup");
5813 if (error)
5814 goto done;
5816 } else {
5817 repo_path = strdup(cwd);
5818 if (repo_path == NULL) {
5819 error = got_error_from_errno("strdup");
5820 goto done;
5825 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5826 if (error != NULL)
5827 goto done;
5829 if (worktree) {
5830 const char *prefix = got_worktree_get_path_prefix(worktree);
5831 char *p;
5833 error = got_worktree_resolve_path(&p, worktree, path);
5834 if (error)
5835 goto done;
5836 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5837 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5838 p) == -1) {
5839 error = got_error_from_errno("asprintf");
5840 free(p);
5841 goto done;
5843 free(p);
5844 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5845 } else {
5846 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5847 if (error)
5848 goto done;
5849 error = got_repo_map_path(&in_repo_path, repo, path);
5851 if (error)
5852 goto done;
5854 if (commit_id_str == NULL) {
5855 struct got_reference *head_ref;
5856 error = got_ref_open(&head_ref, repo, worktree ?
5857 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5858 if (error != NULL)
5859 goto done;
5860 error = got_ref_resolve(&commit_id, repo, head_ref);
5861 got_ref_close(head_ref);
5862 if (error != NULL)
5863 goto done;
5864 } else {
5865 struct got_reflist_head refs;
5867 TAILQ_INIT(&refs);
5868 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5869 NULL);
5870 if (error)
5871 goto done;
5873 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5874 repo, worktree);
5875 if (error != NULL)
5876 goto done;
5877 if (keyword_idstr != NULL)
5878 commit_id_str = keyword_idstr;
5880 error = got_repo_match_object_id(&commit_id, NULL,
5881 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5882 got_ref_list_free(&refs);
5883 if (error)
5884 goto done;
5887 if (worktree) {
5888 /* Release work tree lock. */
5889 got_worktree_close(worktree);
5890 worktree = NULL;
5893 error = got_object_open_as_commit(&commit, repo, commit_id);
5894 if (error)
5895 goto done;
5897 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5898 commit, repo);
5899 if (error)
5900 goto done;
5902 error = got_object_id_by_path(&obj_id, repo, commit,
5903 link_target ? link_target : in_repo_path);
5904 if (error)
5905 goto done;
5907 error = got_object_get_type(&obj_type, repo, obj_id);
5908 if (error)
5909 goto done;
5911 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5912 error = got_error_path(link_target ? link_target : in_repo_path,
5913 GOT_ERR_OBJ_TYPE);
5914 goto done;
5917 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5918 if (error)
5919 goto done;
5920 bca.f = got_opentemp();
5921 if (bca.f == NULL) {
5922 error = got_error_from_errno("got_opentemp");
5923 goto done;
5925 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5926 &bca.line_offsets, bca.f, blob);
5927 if (error || bca.nlines == 0)
5928 goto done;
5930 /* Don't include \n at EOF in the blame line count. */
5931 if (bca.line_offsets[bca.nlines - 1] == filesize)
5932 bca.nlines--;
5934 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5935 if (bca.lines == NULL) {
5936 error = got_error_from_errno("calloc");
5937 goto done;
5939 bca.lineno_cur = 1;
5940 bca.nlines_prec = 0;
5941 i = bca.nlines;
5942 while (i > 0) {
5943 i /= 10;
5944 bca.nlines_prec++;
5946 bca.repo = repo;
5948 fd2 = got_opentempfd();
5949 if (fd2 == -1) {
5950 error = got_error_from_errno("got_opentempfd");
5951 goto done;
5953 fd3 = got_opentempfd();
5954 if (fd3 == -1) {
5955 error = got_error_from_errno("got_opentempfd");
5956 goto done;
5958 f1 = got_opentemp();
5959 if (f1 == NULL) {
5960 error = got_error_from_errno("got_opentemp");
5961 goto done;
5963 f2 = got_opentemp();
5964 if (f2 == NULL) {
5965 error = got_error_from_errno("got_opentemp");
5966 goto done;
5968 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5969 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5970 check_cancelled, NULL, fd2, fd3, f1, f2);
5971 done:
5972 free(keyword_idstr);
5973 free(in_repo_path);
5974 free(link_target);
5975 free(repo_path);
5976 free(cwd);
5977 free(commit_id);
5978 free(obj_id);
5979 if (commit)
5980 got_object_commit_close(commit);
5982 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5983 error = got_error_from_errno("close");
5984 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5985 error = got_error_from_errno("close");
5986 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5987 error = got_error_from_errno("close");
5988 if (f1 && fclose(f1) == EOF && error == NULL)
5989 error = got_error_from_errno("fclose");
5990 if (f2 && fclose(f2) == EOF && error == NULL)
5991 error = got_error_from_errno("fclose");
5993 if (blob)
5994 got_object_blob_close(blob);
5995 if (worktree)
5996 got_worktree_close(worktree);
5997 if (repo) {
5998 const struct got_error *close_err = got_repo_close(repo);
5999 if (error == NULL)
6000 error = close_err;
6002 if (pack_fds) {
6003 const struct got_error *pack_err =
6004 got_repo_pack_fds_close(pack_fds);
6005 if (error == NULL)
6006 error = pack_err;
6008 if (bca.lines) {
6009 for (i = 0; i < bca.nlines; i++) {
6010 struct blame_line *bline = &bca.lines[i];
6011 free(bline->id_str);
6012 free(bline->committer);
6014 free(bca.lines);
6016 free(bca.line_offsets);
6017 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6018 error = got_error_from_errno("fclose");
6019 return error;
6022 __dead static void
6023 usage_tree(void)
6025 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6026 "[path]\n", getprogname());
6027 exit(1);
6030 static const struct got_error *
6031 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6032 const char *root_path, struct got_repository *repo)
6034 const struct got_error *err = NULL;
6035 int is_root_path = (strcmp(path, root_path) == 0);
6036 const char *modestr = "";
6037 mode_t mode = got_tree_entry_get_mode(te);
6038 char *link_target = NULL;
6040 path += strlen(root_path);
6041 while (path[0] == '/')
6042 path++;
6044 if (got_object_tree_entry_is_submodule(te))
6045 modestr = "$";
6046 else if (S_ISLNK(mode)) {
6047 int i;
6049 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6050 if (err)
6051 return err;
6052 for (i = 0; link_target[i] != '\0'; i++) {
6053 if (!isprint((unsigned char)link_target[i]))
6054 link_target[i] = '?';
6057 modestr = "@";
6059 else if (S_ISDIR(mode))
6060 modestr = "/";
6061 else if (mode & S_IXUSR)
6062 modestr = "*";
6064 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6065 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6066 link_target ? " -> ": "", link_target ? link_target : "");
6068 free(link_target);
6069 return NULL;
6072 static const struct got_error *
6073 print_tree(const char *path, struct got_commit_object *commit,
6074 int show_ids, int recurse, const char *root_path,
6075 struct got_repository *repo)
6077 const struct got_error *err = NULL;
6078 struct got_object_id *tree_id = NULL;
6079 struct got_tree_object *tree = NULL;
6080 int nentries, i;
6082 err = got_object_id_by_path(&tree_id, repo, commit, path);
6083 if (err)
6084 goto done;
6086 err = got_object_open_as_tree(&tree, repo, tree_id);
6087 if (err)
6088 goto done;
6089 nentries = got_object_tree_get_nentries(tree);
6090 for (i = 0; i < nentries; i++) {
6091 struct got_tree_entry *te;
6092 char *id = NULL;
6094 if (sigint_received || sigpipe_received)
6095 break;
6097 te = got_object_tree_get_entry(tree, i);
6098 if (show_ids) {
6099 char *id_str;
6100 err = got_object_id_str(&id_str,
6101 got_tree_entry_get_id(te));
6102 if (err)
6103 goto done;
6104 if (asprintf(&id, "%s ", id_str) == -1) {
6105 err = got_error_from_errno("asprintf");
6106 free(id_str);
6107 goto done;
6109 free(id_str);
6111 err = print_entry(te, id, path, root_path, repo);
6112 free(id);
6113 if (err)
6114 goto done;
6116 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6117 char *child_path;
6118 if (asprintf(&child_path, "%s%s%s", path,
6119 path[0] == '/' && path[1] == '\0' ? "" : "/",
6120 got_tree_entry_get_name(te)) == -1) {
6121 err = got_error_from_errno("asprintf");
6122 goto done;
6124 err = print_tree(child_path, commit, show_ids, 1,
6125 root_path, repo);
6126 free(child_path);
6127 if (err)
6128 goto done;
6131 done:
6132 if (tree)
6133 got_object_tree_close(tree);
6134 free(tree_id);
6135 return err;
6138 static const struct got_error *
6139 cmd_tree(int argc, char *argv[])
6141 const struct got_error *error;
6142 struct got_repository *repo = NULL;
6143 struct got_worktree *worktree = NULL;
6144 const char *path, *refname = NULL;
6145 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6146 struct got_object_id *commit_id = NULL;
6147 struct got_commit_object *commit = NULL;
6148 char *commit_id_str = NULL, *keyword_idstr = NULL;
6149 int show_ids = 0, recurse = 0;
6150 int ch;
6151 int *pack_fds = NULL;
6153 #ifndef PROFILE
6154 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6155 NULL) == -1)
6156 err(1, "pledge");
6157 #endif
6159 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6160 switch (ch) {
6161 case 'c':
6162 commit_id_str = optarg;
6163 break;
6164 case 'i':
6165 show_ids = 1;
6166 break;
6167 case 'R':
6168 recurse = 1;
6169 break;
6170 case 'r':
6171 repo_path = realpath(optarg, NULL);
6172 if (repo_path == NULL)
6173 return got_error_from_errno2("realpath",
6174 optarg);
6175 got_path_strip_trailing_slashes(repo_path);
6176 break;
6177 default:
6178 usage_tree();
6179 /* NOTREACHED */
6183 argc -= optind;
6184 argv += optind;
6186 if (argc == 1)
6187 path = argv[0];
6188 else if (argc > 1)
6189 usage_tree();
6190 else
6191 path = NULL;
6193 cwd = getcwd(NULL, 0);
6194 if (cwd == NULL) {
6195 error = got_error_from_errno("getcwd");
6196 goto done;
6199 error = got_repo_pack_fds_open(&pack_fds);
6200 if (error != NULL)
6201 goto done;
6203 if (repo_path == NULL) {
6204 error = got_worktree_open(&worktree, cwd,
6205 GOT_WORKTREE_GOT_DIR);
6206 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6207 goto done;
6208 else
6209 error = NULL;
6210 if (worktree) {
6211 repo_path =
6212 strdup(got_worktree_get_repo_path(worktree));
6213 if (repo_path == NULL)
6214 error = got_error_from_errno("strdup");
6215 if (error)
6216 goto done;
6217 } else {
6218 repo_path = strdup(cwd);
6219 if (repo_path == NULL) {
6220 error = got_error_from_errno("strdup");
6221 goto done;
6226 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6227 if (error != NULL)
6228 goto done;
6230 if (worktree) {
6231 const char *prefix = got_worktree_get_path_prefix(worktree);
6232 char *p;
6234 if (path == NULL || got_path_is_root_dir(path))
6235 path = "";
6236 error = got_worktree_resolve_path(&p, worktree, path);
6237 if (error)
6238 goto done;
6239 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6240 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6241 p) == -1) {
6242 error = got_error_from_errno("asprintf");
6243 free(p);
6244 goto done;
6246 free(p);
6247 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6248 if (error)
6249 goto done;
6250 } else {
6251 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6252 if (error)
6253 goto done;
6254 if (path == NULL)
6255 path = "/";
6256 error = got_repo_map_path(&in_repo_path, repo, path);
6257 if (error != NULL)
6258 goto done;
6261 if (commit_id_str == NULL) {
6262 struct got_reference *head_ref;
6263 if (worktree)
6264 refname = got_worktree_get_head_ref_name(worktree);
6265 else
6266 refname = GOT_REF_HEAD;
6267 error = got_ref_open(&head_ref, repo, refname, 0);
6268 if (error != NULL)
6269 goto done;
6270 error = got_ref_resolve(&commit_id, repo, head_ref);
6271 got_ref_close(head_ref);
6272 if (error != NULL)
6273 goto done;
6274 } else {
6275 struct got_reflist_head refs;
6277 TAILQ_INIT(&refs);
6278 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6279 NULL);
6280 if (error)
6281 goto done;
6283 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6284 repo, worktree);
6285 if (error != NULL)
6286 goto done;
6287 if (keyword_idstr != NULL)
6288 commit_id_str = keyword_idstr;
6290 error = got_repo_match_object_id(&commit_id, NULL,
6291 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6292 got_ref_list_free(&refs);
6293 if (error)
6294 goto done;
6297 if (worktree) {
6298 /* Release work tree lock. */
6299 got_worktree_close(worktree);
6300 worktree = NULL;
6303 error = got_object_open_as_commit(&commit, repo, commit_id);
6304 if (error)
6305 goto done;
6307 error = print_tree(in_repo_path, commit, show_ids, recurse,
6308 in_repo_path, repo);
6309 done:
6310 free(keyword_idstr);
6311 free(in_repo_path);
6312 free(repo_path);
6313 free(cwd);
6314 free(commit_id);
6315 if (commit)
6316 got_object_commit_close(commit);
6317 if (worktree)
6318 got_worktree_close(worktree);
6319 if (repo) {
6320 const struct got_error *close_err = got_repo_close(repo);
6321 if (error == NULL)
6322 error = close_err;
6324 if (pack_fds) {
6325 const struct got_error *pack_err =
6326 got_repo_pack_fds_close(pack_fds);
6327 if (error == NULL)
6328 error = pack_err;
6330 return error;
6333 __dead static void
6334 usage_status(void)
6336 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6337 "[-s status-codes] [path ...]\n", getprogname());
6338 exit(1);
6341 struct got_status_arg {
6342 char *status_codes;
6343 int suppress;
6346 static const struct got_error *
6347 print_status(void *arg, unsigned char status, unsigned char staged_status,
6348 const char *path, struct got_object_id *blob_id,
6349 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6350 int dirfd, const char *de_name)
6352 struct got_status_arg *st = arg;
6354 if (status == staged_status && (status == GOT_STATUS_DELETE))
6355 status = GOT_STATUS_NO_CHANGE;
6356 if (st != NULL && st->status_codes) {
6357 size_t ncodes = strlen(st->status_codes);
6358 int i, j = 0;
6360 for (i = 0; i < ncodes ; i++) {
6361 if (st->suppress) {
6362 if (status == st->status_codes[i] ||
6363 staged_status == st->status_codes[i]) {
6364 j++;
6365 continue;
6367 } else {
6368 if (status == st->status_codes[i] ||
6369 staged_status == st->status_codes[i])
6370 break;
6374 if (st->suppress && j == 0)
6375 goto print;
6377 if (i == ncodes)
6378 return NULL;
6380 print:
6381 printf("%c%c %s\n", status, staged_status, path);
6382 return NULL;
6385 static const struct got_error *
6386 cmd_status(int argc, char *argv[])
6388 const struct got_error *error = NULL;
6389 struct got_repository *repo = NULL;
6390 struct got_worktree *worktree = NULL;
6391 struct got_status_arg st;
6392 char *cwd = NULL;
6393 struct got_pathlist_head paths;
6394 int ch, i, no_ignores = 0;
6395 int *pack_fds = NULL;
6397 TAILQ_INIT(&paths);
6399 memset(&st, 0, sizeof(st));
6400 st.status_codes = NULL;
6401 st.suppress = 0;
6403 #ifndef PROFILE
6404 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6405 NULL) == -1)
6406 err(1, "pledge");
6407 #endif
6409 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6410 switch (ch) {
6411 case 'I':
6412 no_ignores = 1;
6413 break;
6414 case 'S':
6415 if (st.status_codes != NULL && st.suppress == 0)
6416 option_conflict('S', 's');
6417 st.suppress = 1;
6418 /* fallthrough */
6419 case 's':
6420 for (i = 0; optarg[i] != '\0'; i++) {
6421 switch (optarg[i]) {
6422 case GOT_STATUS_MODIFY:
6423 case GOT_STATUS_ADD:
6424 case GOT_STATUS_DELETE:
6425 case GOT_STATUS_CONFLICT:
6426 case GOT_STATUS_MISSING:
6427 case GOT_STATUS_OBSTRUCTED:
6428 case GOT_STATUS_UNVERSIONED:
6429 case GOT_STATUS_MODE_CHANGE:
6430 case GOT_STATUS_NONEXISTENT:
6431 break;
6432 default:
6433 errx(1, "invalid status code '%c'",
6434 optarg[i]);
6437 if (ch == 's' && st.suppress)
6438 option_conflict('s', 'S');
6439 st.status_codes = optarg;
6440 break;
6441 default:
6442 usage_status();
6443 /* NOTREACHED */
6447 argc -= optind;
6448 argv += optind;
6450 cwd = getcwd(NULL, 0);
6451 if (cwd == NULL) {
6452 error = got_error_from_errno("getcwd");
6453 goto done;
6456 error = got_repo_pack_fds_open(&pack_fds);
6457 if (error != NULL)
6458 goto done;
6460 error = got_worktree_open(&worktree, cwd,
6461 GOT_WORKTREE_GOT_DIR);
6462 if (error) {
6463 if (error->code == GOT_ERR_NOT_WORKTREE)
6464 error = wrap_not_worktree_error(error, "status", cwd);
6465 goto done;
6468 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6469 NULL, pack_fds);
6470 if (error != NULL)
6471 goto done;
6473 error = apply_unveil(got_repo_get_path(repo), 1,
6474 got_worktree_get_root_path(worktree));
6475 if (error)
6476 goto done;
6478 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6479 if (error)
6480 goto done;
6482 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6483 print_status, &st, check_cancelled, NULL);
6484 done:
6485 if (pack_fds) {
6486 const struct got_error *pack_err =
6487 got_repo_pack_fds_close(pack_fds);
6488 if (error == NULL)
6489 error = pack_err;
6491 if (repo) {
6492 const struct got_error *close_err = got_repo_close(repo);
6493 if (error == NULL)
6494 error = close_err;
6497 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6498 free(cwd);
6499 return error;
6502 __dead static void
6503 usage_ref(void)
6505 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6506 "[-s reference] [name]\n", getprogname());
6507 exit(1);
6510 static const struct got_error *
6511 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6513 static const struct got_error *err = NULL;
6514 struct got_reflist_head refs;
6515 struct got_reflist_entry *re;
6517 TAILQ_INIT(&refs);
6518 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6519 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6520 repo);
6521 if (err)
6522 return err;
6524 TAILQ_FOREACH(re, &refs, entry) {
6525 char *refstr;
6526 refstr = got_ref_to_str(re->ref);
6527 if (refstr == NULL) {
6528 err = got_error_from_errno("got_ref_to_str");
6529 break;
6531 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6532 free(refstr);
6535 got_ref_list_free(&refs);
6536 return err;
6539 static const struct got_error *
6540 delete_ref_by_name(struct got_repository *repo, const char *refname)
6542 const struct got_error *err;
6543 struct got_reference *ref;
6545 err = got_ref_open(&ref, repo, refname, 0);
6546 if (err)
6547 return err;
6549 err = delete_ref(repo, ref);
6550 got_ref_close(ref);
6551 return err;
6554 static const struct got_error *
6555 add_ref(struct got_repository *repo, const char *refname, const char *target)
6557 const struct got_error *err = NULL;
6558 struct got_object_id *id = NULL;
6559 struct got_reference *ref = NULL;
6560 struct got_reflist_head refs;
6563 * Don't let the user create a reference name with a leading '-'.
6564 * While technically a valid reference name, this case is usually
6565 * an unintended typo.
6567 if (refname[0] == '-')
6568 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6570 TAILQ_INIT(&refs);
6571 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6572 if (err)
6573 goto done;
6574 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6575 &refs, repo);
6576 got_ref_list_free(&refs);
6577 if (err)
6578 goto done;
6580 err = got_ref_alloc(&ref, refname, id);
6581 if (err)
6582 goto done;
6584 err = got_ref_write(ref, repo);
6585 done:
6586 if (ref)
6587 got_ref_close(ref);
6588 free(id);
6589 return err;
6592 static const struct got_error *
6593 add_symref(struct got_repository *repo, const char *refname, const char *target)
6595 const struct got_error *err = NULL;
6596 struct got_reference *ref = NULL;
6597 struct got_reference *target_ref = NULL;
6600 * Don't let the user create a reference name with a leading '-'.
6601 * While technically a valid reference name, this case is usually
6602 * an unintended typo.
6604 if (refname[0] == '-')
6605 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6607 err = got_ref_open(&target_ref, repo, target, 0);
6608 if (err)
6609 return err;
6611 err = got_ref_alloc_symref(&ref, refname, target_ref);
6612 if (err)
6613 goto done;
6615 err = got_ref_write(ref, repo);
6616 done:
6617 if (target_ref)
6618 got_ref_close(target_ref);
6619 if (ref)
6620 got_ref_close(ref);
6621 return err;
6624 static const struct got_error *
6625 cmd_ref(int argc, char *argv[])
6627 const struct got_error *error = NULL;
6628 struct got_repository *repo = NULL;
6629 struct got_worktree *worktree = NULL;
6630 char *cwd = NULL, *repo_path = NULL;
6631 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6632 const char *obj_arg = NULL, *symref_target= NULL;
6633 char *refname = NULL, *keyword_idstr = NULL;
6634 int *pack_fds = NULL;
6636 #ifndef PROFILE
6637 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6638 "sendfd unveil", NULL) == -1)
6639 err(1, "pledge");
6640 #endif
6642 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6643 switch (ch) {
6644 case 'c':
6645 obj_arg = optarg;
6646 break;
6647 case 'd':
6648 do_delete = 1;
6649 break;
6650 case 'l':
6651 do_list = 1;
6652 break;
6653 case 'r':
6654 repo_path = realpath(optarg, NULL);
6655 if (repo_path == NULL)
6656 return got_error_from_errno2("realpath",
6657 optarg);
6658 got_path_strip_trailing_slashes(repo_path);
6659 break;
6660 case 's':
6661 symref_target = optarg;
6662 break;
6663 case 't':
6664 sort_by_time = 1;
6665 break;
6666 default:
6667 usage_ref();
6668 /* NOTREACHED */
6672 if (obj_arg && do_list)
6673 option_conflict('c', 'l');
6674 if (obj_arg && do_delete)
6675 option_conflict('c', 'd');
6676 if (obj_arg && symref_target)
6677 option_conflict('c', 's');
6678 if (symref_target && do_delete)
6679 option_conflict('s', 'd');
6680 if (symref_target && do_list)
6681 option_conflict('s', 'l');
6682 if (do_delete && do_list)
6683 option_conflict('d', 'l');
6684 if (sort_by_time && !do_list)
6685 errx(1, "-t option requires -l option");
6687 argc -= optind;
6688 argv += optind;
6690 if (do_list) {
6691 if (argc != 0 && argc != 1)
6692 usage_ref();
6693 if (argc == 1) {
6694 refname = strdup(argv[0]);
6695 if (refname == NULL) {
6696 error = got_error_from_errno("strdup");
6697 goto done;
6700 } else {
6701 if (argc != 1)
6702 usage_ref();
6703 refname = strdup(argv[0]);
6704 if (refname == NULL) {
6705 error = got_error_from_errno("strdup");
6706 goto done;
6710 if (refname)
6711 got_path_strip_trailing_slashes(refname);
6713 cwd = getcwd(NULL, 0);
6714 if (cwd == NULL) {
6715 error = got_error_from_errno("getcwd");
6716 goto done;
6719 error = got_repo_pack_fds_open(&pack_fds);
6720 if (error != NULL)
6721 goto done;
6723 if (repo_path == NULL) {
6724 error = got_worktree_open(&worktree, cwd,
6725 GOT_WORKTREE_GOT_DIR);
6726 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6727 goto done;
6728 else
6729 error = NULL;
6730 if (worktree) {
6731 repo_path =
6732 strdup(got_worktree_get_repo_path(worktree));
6733 if (repo_path == NULL)
6734 error = got_error_from_errno("strdup");
6735 if (error)
6736 goto done;
6737 } else {
6738 repo_path = strdup(cwd);
6739 if (repo_path == NULL) {
6740 error = got_error_from_errno("strdup");
6741 goto done;
6746 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6747 if (error != NULL)
6748 goto done;
6750 #ifndef PROFILE
6751 if (do_list) {
6752 /* Remove "cpath" promise. */
6753 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6754 NULL) == -1)
6755 err(1, "pledge");
6757 #endif
6759 error = apply_unveil(got_repo_get_path(repo), do_list,
6760 worktree ? got_worktree_get_root_path(worktree) : NULL);
6761 if (error)
6762 goto done;
6764 if (do_list)
6765 error = list_refs(repo, refname, sort_by_time);
6766 else if (do_delete)
6767 error = delete_ref_by_name(repo, refname);
6768 else if (symref_target)
6769 error = add_symref(repo, refname, symref_target);
6770 else {
6771 if (obj_arg == NULL)
6772 usage_ref();
6774 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6775 repo, worktree);
6776 if (error != NULL)
6777 goto done;
6778 if (keyword_idstr != NULL)
6779 obj_arg = keyword_idstr;
6781 error = add_ref(repo, refname, obj_arg);
6783 done:
6784 free(refname);
6785 if (repo) {
6786 const struct got_error *close_err = got_repo_close(repo);
6787 if (error == NULL)
6788 error = close_err;
6790 if (worktree)
6791 got_worktree_close(worktree);
6792 if (pack_fds) {
6793 const struct got_error *pack_err =
6794 got_repo_pack_fds_close(pack_fds);
6795 if (error == NULL)
6796 error = pack_err;
6798 free(cwd);
6799 free(repo_path);
6800 free(keyword_idstr);
6801 return error;
6804 __dead static void
6805 usage_branch(void)
6807 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6808 "[-r repository-path] [name]\n", getprogname());
6809 exit(1);
6812 static const struct got_error *
6813 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6814 struct got_reference *ref)
6816 const struct got_error *err = NULL;
6817 const char *refname;
6818 char *refstr;
6819 char marker = ' ';
6821 refname = got_ref_get_name(ref);
6822 if (worktree && strcmp(refname,
6823 got_worktree_get_head_ref_name(worktree)) == 0) {
6824 err = got_worktree_get_state(&marker, repo, worktree,
6825 check_cancelled, NULL);
6826 if (err != NULL)
6827 return err;
6830 if (strncmp(refname, "refs/heads/", 11) == 0)
6831 refname += 11;
6832 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6833 refname += 18;
6834 if (strncmp(refname, "refs/remotes/", 13) == 0)
6835 refname += 13;
6837 refstr = got_ref_to_str(ref);
6838 if (refstr == NULL)
6839 return got_error_from_errno("got_ref_to_str");
6841 printf("%c %s: %s\n", marker, refname, refstr);
6842 free(refstr);
6843 return NULL;
6846 static const struct got_error *
6847 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6849 const char *refname;
6851 if (worktree == NULL)
6852 return got_error(GOT_ERR_NOT_WORKTREE);
6854 refname = got_worktree_get_head_ref_name(worktree);
6856 if (strncmp(refname, "refs/heads/", 11) == 0)
6857 refname += 11;
6858 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6859 refname += 18;
6861 printf("%s\n", refname);
6863 return NULL;
6866 static const struct got_error *
6867 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6868 int sort_by_time)
6870 static const struct got_error *err = NULL;
6871 struct got_reflist_head refs;
6872 struct got_reflist_entry *re;
6873 struct got_reference *temp_ref = NULL;
6874 int rebase_in_progress, histedit_in_progress;
6876 TAILQ_INIT(&refs);
6878 if (worktree) {
6879 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6880 worktree);
6881 if (err)
6882 return err;
6884 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6885 worktree);
6886 if (err)
6887 return err;
6889 if (rebase_in_progress || histedit_in_progress) {
6890 err = got_ref_open(&temp_ref, repo,
6891 got_worktree_get_head_ref_name(worktree), 0);
6892 if (err)
6893 return err;
6894 list_branch(repo, worktree, temp_ref);
6895 got_ref_close(temp_ref);
6899 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6900 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6901 repo);
6902 if (err)
6903 return err;
6905 TAILQ_FOREACH(re, &refs, entry)
6906 list_branch(repo, worktree, re->ref);
6908 got_ref_list_free(&refs);
6910 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6911 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6912 repo);
6913 if (err)
6914 return err;
6916 TAILQ_FOREACH(re, &refs, entry)
6917 list_branch(repo, worktree, re->ref);
6919 got_ref_list_free(&refs);
6921 return NULL;
6924 static const struct got_error *
6925 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6926 const char *branch_name)
6928 const struct got_error *err = NULL;
6929 struct got_reference *ref = NULL;
6930 char *refname, *remote_refname = NULL;
6932 if (strncmp(branch_name, "refs/", 5) == 0)
6933 branch_name += 5;
6934 if (strncmp(branch_name, "heads/", 6) == 0)
6935 branch_name += 6;
6936 else if (strncmp(branch_name, "remotes/", 8) == 0)
6937 branch_name += 8;
6939 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6940 return got_error_from_errno("asprintf");
6942 if (asprintf(&remote_refname, "refs/remotes/%s",
6943 branch_name) == -1) {
6944 err = got_error_from_errno("asprintf");
6945 goto done;
6948 err = got_ref_open(&ref, repo, refname, 0);
6949 if (err) {
6950 const struct got_error *err2;
6951 if (err->code != GOT_ERR_NOT_REF)
6952 goto done;
6954 * Keep 'err' intact such that if neither branch exists
6955 * we report "refs/heads" rather than "refs/remotes" in
6956 * our error message.
6958 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6959 if (err2)
6960 goto done;
6961 err = NULL;
6964 if (worktree &&
6965 strcmp(got_worktree_get_head_ref_name(worktree),
6966 got_ref_get_name(ref)) == 0) {
6967 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6968 "will not delete this work tree's current branch");
6969 goto done;
6972 err = delete_ref(repo, ref);
6973 done:
6974 if (ref)
6975 got_ref_close(ref);
6976 free(refname);
6977 free(remote_refname);
6978 return err;
6981 static const struct got_error *
6982 add_branch(struct got_repository *repo, const char *branch_name,
6983 struct got_object_id *base_commit_id)
6985 const struct got_error *err = NULL;
6986 struct got_reference *ref = NULL;
6987 char *refname = NULL;
6990 * Don't let the user create a branch name with a leading '-'.
6991 * While technically a valid reference name, this case is usually
6992 * an unintended typo.
6994 if (branch_name[0] == '-')
6995 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6997 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6998 branch_name += 11;
7000 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7001 err = got_error_from_errno("asprintf");
7002 goto done;
7005 err = got_ref_open(&ref, repo, refname, 0);
7006 if (err == NULL) {
7007 err = got_error(GOT_ERR_BRANCH_EXISTS);
7008 goto done;
7009 } else if (err->code != GOT_ERR_NOT_REF)
7010 goto done;
7012 err = got_ref_alloc(&ref, refname, base_commit_id);
7013 if (err)
7014 goto done;
7016 err = got_ref_write(ref, repo);
7017 done:
7018 if (ref)
7019 got_ref_close(ref);
7020 free(refname);
7021 return err;
7024 static const struct got_error *
7025 cmd_branch(int argc, char *argv[])
7027 const struct got_error *error = NULL;
7028 struct got_repository *repo = NULL;
7029 struct got_worktree *worktree = NULL;
7030 char *cwd = NULL, *repo_path = NULL;
7031 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7032 const char *delref = NULL, *commit_id_arg = NULL;
7033 struct got_reference *ref = NULL;
7034 struct got_pathlist_head paths;
7035 struct got_object_id *commit_id = NULL;
7036 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7037 int *pack_fds = NULL;
7039 TAILQ_INIT(&paths);
7041 #ifndef PROFILE
7042 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7043 "sendfd unveil", NULL) == -1)
7044 err(1, "pledge");
7045 #endif
7047 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7048 switch (ch) {
7049 case 'c':
7050 commit_id_arg = optarg;
7051 break;
7052 case 'd':
7053 delref = optarg;
7054 break;
7055 case 'l':
7056 do_list = 1;
7057 break;
7058 case 'n':
7059 do_update = 0;
7060 break;
7061 case 'r':
7062 repo_path = realpath(optarg, NULL);
7063 if (repo_path == NULL)
7064 return got_error_from_errno2("realpath",
7065 optarg);
7066 got_path_strip_trailing_slashes(repo_path);
7067 break;
7068 case 't':
7069 sort_by_time = 1;
7070 break;
7071 default:
7072 usage_branch();
7073 /* NOTREACHED */
7077 if (do_list && delref)
7078 option_conflict('l', 'd');
7079 if (sort_by_time && !do_list)
7080 errx(1, "-t option requires -l option");
7082 argc -= optind;
7083 argv += optind;
7085 if (!do_list && !delref && argc == 0)
7086 do_show = 1;
7088 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7089 errx(1, "-c option can only be used when creating a branch");
7091 if (do_list || delref) {
7092 if (argc > 0)
7093 usage_branch();
7094 } else if (!do_show && argc != 1)
7095 usage_branch();
7097 cwd = getcwd(NULL, 0);
7098 if (cwd == NULL) {
7099 error = got_error_from_errno("getcwd");
7100 goto done;
7103 error = got_repo_pack_fds_open(&pack_fds);
7104 if (error != NULL)
7105 goto done;
7107 if (repo_path == NULL) {
7108 error = got_worktree_open(&worktree, cwd,
7109 GOT_WORKTREE_GOT_DIR);
7110 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7111 goto done;
7112 else
7113 error = NULL;
7114 if (worktree) {
7115 repo_path =
7116 strdup(got_worktree_get_repo_path(worktree));
7117 if (repo_path == NULL)
7118 error = got_error_from_errno("strdup");
7119 if (error)
7120 goto done;
7121 } else {
7122 repo_path = strdup(cwd);
7123 if (repo_path == NULL) {
7124 error = got_error_from_errno("strdup");
7125 goto done;
7130 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7131 if (error != NULL)
7132 goto done;
7134 #ifndef PROFILE
7135 if (do_list || do_show) {
7136 /* Remove "cpath" promise. */
7137 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7138 NULL) == -1)
7139 err(1, "pledge");
7141 #endif
7143 error = apply_unveil(got_repo_get_path(repo), do_list,
7144 worktree ? got_worktree_get_root_path(worktree) : NULL);
7145 if (error)
7146 goto done;
7148 if (do_show)
7149 error = show_current_branch(repo, worktree);
7150 else if (do_list)
7151 error = list_branches(repo, worktree, sort_by_time);
7152 else if (delref)
7153 error = delete_branch(repo, worktree, delref);
7154 else {
7155 struct got_reflist_head refs;
7156 TAILQ_INIT(&refs);
7157 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7158 NULL);
7159 if (error)
7160 goto done;
7161 if (commit_id_arg == NULL)
7162 commit_id_arg = worktree ?
7163 got_worktree_get_head_ref_name(worktree) :
7164 GOT_REF_HEAD;
7165 else {
7166 error = got_keyword_to_idstr(&keyword_idstr,
7167 commit_id_arg, repo, worktree);
7168 if (error != NULL)
7169 goto done;
7170 if (keyword_idstr != NULL)
7171 commit_id_arg = keyword_idstr;
7173 error = got_repo_match_object_id(&commit_id, NULL,
7174 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7175 got_ref_list_free(&refs);
7176 if (error)
7177 goto done;
7178 error = add_branch(repo, argv[0], commit_id);
7179 if (error)
7180 goto done;
7181 if (worktree && do_update) {
7182 struct got_update_progress_arg upa;
7183 char *branch_refname = NULL;
7185 error = got_object_id_str(&commit_id_str, commit_id);
7186 if (error)
7187 goto done;
7188 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7189 worktree);
7190 if (error)
7191 goto done;
7192 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7193 == -1) {
7194 error = got_error_from_errno("asprintf");
7195 goto done;
7197 error = got_ref_open(&ref, repo, branch_refname, 0);
7198 free(branch_refname);
7199 if (error)
7200 goto done;
7201 error = switch_head_ref(ref, commit_id, worktree,
7202 repo);
7203 if (error)
7204 goto done;
7205 error = got_worktree_set_base_commit_id(worktree, repo,
7206 commit_id);
7207 if (error)
7208 goto done;
7209 memset(&upa, 0, sizeof(upa));
7210 error = got_worktree_checkout_files(worktree, &paths,
7211 repo, update_progress, &upa, check_cancelled,
7212 NULL);
7213 if (error)
7214 goto done;
7215 if (upa.did_something) {
7216 printf("Updated to %s: %s\n",
7217 got_worktree_get_head_ref_name(worktree),
7218 commit_id_str);
7220 print_update_progress_stats(&upa);
7223 done:
7224 free(keyword_idstr);
7225 if (ref)
7226 got_ref_close(ref);
7227 if (repo) {
7228 const struct got_error *close_err = got_repo_close(repo);
7229 if (error == NULL)
7230 error = close_err;
7232 if (worktree)
7233 got_worktree_close(worktree);
7234 if (pack_fds) {
7235 const struct got_error *pack_err =
7236 got_repo_pack_fds_close(pack_fds);
7237 if (error == NULL)
7238 error = pack_err;
7240 free(cwd);
7241 free(repo_path);
7242 free(commit_id);
7243 free(commit_id_str);
7244 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7245 return error;
7249 __dead static void
7250 usage_tag(void)
7252 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7253 "[-r repository-path] [-s signer-id] name\n", getprogname());
7254 exit(1);
7257 #if 0
7258 static const struct got_error *
7259 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7261 const struct got_error *err = NULL;
7262 struct got_reflist_entry *re, *se, *new;
7263 struct got_object_id *re_id, *se_id;
7264 struct got_tag_object *re_tag, *se_tag;
7265 time_t re_time, se_time;
7267 STAILQ_FOREACH(re, tags, entry) {
7268 se = STAILQ_FIRST(sorted);
7269 if (se == NULL) {
7270 err = got_reflist_entry_dup(&new, re);
7271 if (err)
7272 return err;
7273 STAILQ_INSERT_HEAD(sorted, new, entry);
7274 continue;
7275 } else {
7276 err = got_ref_resolve(&re_id, repo, re->ref);
7277 if (err)
7278 break;
7279 err = got_object_open_as_tag(&re_tag, repo, re_id);
7280 free(re_id);
7281 if (err)
7282 break;
7283 re_time = got_object_tag_get_tagger_time(re_tag);
7284 got_object_tag_close(re_tag);
7287 while (se) {
7288 err = got_ref_resolve(&se_id, repo, re->ref);
7289 if (err)
7290 break;
7291 err = got_object_open_as_tag(&se_tag, repo, se_id);
7292 free(se_id);
7293 if (err)
7294 break;
7295 se_time = got_object_tag_get_tagger_time(se_tag);
7296 got_object_tag_close(se_tag);
7298 if (se_time > re_time) {
7299 err = got_reflist_entry_dup(&new, re);
7300 if (err)
7301 return err;
7302 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7303 break;
7305 se = STAILQ_NEXT(se, entry);
7306 continue;
7309 done:
7310 return err;
7312 #endif
7314 static const struct got_error *
7315 get_tag_refname(char **refname, const char *tag_name)
7317 const struct got_error *err;
7319 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7320 *refname = strdup(tag_name);
7321 if (*refname == NULL)
7322 return got_error_from_errno("strdup");
7323 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7324 err = got_error_from_errno("asprintf");
7325 *refname = NULL;
7326 return err;
7329 return NULL;
7332 static const struct got_error *
7333 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7334 const char *allowed_signers, const char *revoked_signers, int verbosity)
7336 static const struct got_error *err = NULL;
7337 struct got_reflist_head refs;
7338 struct got_reflist_entry *re;
7339 char *wanted_refname = NULL;
7340 int bad_sigs = 0;
7342 TAILQ_INIT(&refs);
7344 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7345 if (err)
7346 return err;
7348 if (tag_name) {
7349 struct got_reference *ref;
7350 err = get_tag_refname(&wanted_refname, tag_name);
7351 if (err)
7352 goto done;
7353 /* Wanted tag reference should exist. */
7354 err = got_ref_open(&ref, repo, wanted_refname, 0);
7355 if (err)
7356 goto done;
7357 got_ref_close(ref);
7360 TAILQ_FOREACH(re, &refs, entry) {
7361 const char *refname;
7362 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7363 char datebuf[26];
7364 const char *tagger, *ssh_sig = NULL;
7365 char *sig_msg = NULL;
7366 time_t tagger_time;
7367 struct got_object_id *id;
7368 struct got_tag_object *tag;
7369 struct got_commit_object *commit = NULL;
7371 refname = got_ref_get_name(re->ref);
7372 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7373 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7374 continue;
7375 refname += 10;
7376 refstr = got_ref_to_str(re->ref);
7377 if (refstr == NULL) {
7378 err = got_error_from_errno("got_ref_to_str");
7379 break;
7382 err = got_ref_resolve(&id, repo, re->ref);
7383 if (err)
7384 break;
7385 err = got_object_open_as_tag(&tag, repo, id);
7386 if (err) {
7387 if (err->code != GOT_ERR_OBJ_TYPE) {
7388 free(id);
7389 break;
7391 /* "lightweight" tag */
7392 err = got_object_open_as_commit(&commit, repo, id);
7393 if (err) {
7394 free(id);
7395 break;
7397 tagger = got_object_commit_get_committer(commit);
7398 tagger_time =
7399 got_object_commit_get_committer_time(commit);
7400 err = got_object_id_str(&id_str, id);
7401 free(id);
7402 if (err)
7403 break;
7404 } else {
7405 free(id);
7406 tagger = got_object_tag_get_tagger(tag);
7407 tagger_time = got_object_tag_get_tagger_time(tag);
7408 err = got_object_id_str(&id_str,
7409 got_object_tag_get_object_id(tag));
7410 if (err)
7411 break;
7414 if (tag && verify_tags) {
7415 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7416 got_object_tag_get_message(tag));
7417 if (ssh_sig && allowed_signers == NULL) {
7418 err = got_error_msg(
7419 GOT_ERR_VERIFY_TAG_SIGNATURE,
7420 "SSH signature verification requires "
7421 "setting allowed_signers in "
7422 "got.conf(5)");
7423 break;
7427 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7428 free(refstr);
7429 printf("from: %s\n", tagger);
7430 datestr = get_datestr(&tagger_time, datebuf);
7431 if (datestr)
7432 printf("date: %s UTC\n", datestr);
7433 if (commit)
7434 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7435 else {
7436 switch (got_object_tag_get_object_type(tag)) {
7437 case GOT_OBJ_TYPE_BLOB:
7438 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7439 id_str);
7440 break;
7441 case GOT_OBJ_TYPE_TREE:
7442 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7443 id_str);
7444 break;
7445 case GOT_OBJ_TYPE_COMMIT:
7446 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7447 id_str);
7448 break;
7449 case GOT_OBJ_TYPE_TAG:
7450 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7451 id_str);
7452 break;
7453 default:
7454 break;
7457 free(id_str);
7459 if (ssh_sig) {
7460 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7461 allowed_signers, revoked_signers, verbosity);
7462 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7463 bad_sigs = 1;
7464 else if (err)
7465 break;
7466 printf("signature: %s", sig_msg);
7467 free(sig_msg);
7468 sig_msg = NULL;
7471 if (commit) {
7472 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7473 if (err)
7474 break;
7475 got_object_commit_close(commit);
7476 } else {
7477 tagmsg0 = strdup(got_object_tag_get_message(tag));
7478 got_object_tag_close(tag);
7479 if (tagmsg0 == NULL) {
7480 err = got_error_from_errno("strdup");
7481 break;
7485 tagmsg = tagmsg0;
7486 do {
7487 line = strsep(&tagmsg, "\n");
7488 if (line)
7489 printf(" %s\n", line);
7490 } while (line);
7491 free(tagmsg0);
7493 done:
7494 got_ref_list_free(&refs);
7495 free(wanted_refname);
7497 if (err == NULL && bad_sigs)
7498 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7499 return err;
7502 static const struct got_error *
7503 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7504 const char *tag_name, const char *repo_path)
7506 const struct got_error *err = NULL;
7507 char *template = NULL, *initial_content = NULL;
7508 char *editor = NULL;
7509 int initial_content_len;
7510 int fd = -1;
7512 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7513 err = got_error_from_errno("asprintf");
7514 goto done;
7517 initial_content_len = asprintf(&initial_content,
7518 "\n# tagging commit %s as %s\n",
7519 commit_id_str, tag_name);
7520 if (initial_content_len == -1) {
7521 err = got_error_from_errno("asprintf");
7522 goto done;
7525 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7526 if (err)
7527 goto done;
7529 if (write(fd, initial_content, initial_content_len) == -1) {
7530 err = got_error_from_errno2("write", *tagmsg_path);
7531 goto done;
7533 if (close(fd) == -1) {
7534 err = got_error_from_errno2("close", *tagmsg_path);
7535 goto done;
7537 fd = -1;
7539 err = get_editor(&editor);
7540 if (err)
7541 goto done;
7542 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7543 initial_content_len, 1);
7544 done:
7545 free(initial_content);
7546 free(template);
7547 free(editor);
7549 if (fd != -1 && close(fd) == -1 && err == NULL)
7550 err = got_error_from_errno2("close", *tagmsg_path);
7552 if (err) {
7553 free(*tagmsg);
7554 *tagmsg = NULL;
7556 return err;
7559 static const struct got_error *
7560 add_tag(struct got_repository *repo, const char *tagger,
7561 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7562 const char *signer_id, int verbosity)
7564 const struct got_error *err = NULL;
7565 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7566 char *label = NULL, *commit_id_str = NULL;
7567 struct got_reference *ref = NULL;
7568 char *refname = NULL, *tagmsg = NULL;
7569 char *tagmsg_path = NULL, *tag_id_str = NULL;
7570 int preserve_tagmsg = 0;
7571 struct got_reflist_head refs;
7573 TAILQ_INIT(&refs);
7576 * Don't let the user create a tag name with a leading '-'.
7577 * While technically a valid reference name, this case is usually
7578 * an unintended typo.
7580 if (tag_name[0] == '-')
7581 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7583 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7584 if (err)
7585 goto done;
7587 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7588 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7589 if (err)
7590 goto done;
7592 err = got_object_id_str(&commit_id_str, commit_id);
7593 if (err)
7594 goto done;
7596 err = get_tag_refname(&refname, tag_name);
7597 if (err)
7598 goto done;
7599 if (strncmp("refs/tags/", tag_name, 10) == 0)
7600 tag_name += 10;
7602 err = got_ref_open(&ref, repo, refname, 0);
7603 if (err == NULL) {
7604 err = got_error(GOT_ERR_TAG_EXISTS);
7605 goto done;
7606 } else if (err->code != GOT_ERR_NOT_REF)
7607 goto done;
7609 if (tagmsg_arg == NULL) {
7610 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7611 tag_name, got_repo_get_path(repo));
7612 if (err) {
7613 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7614 tagmsg_path != NULL)
7615 preserve_tagmsg = 1;
7616 goto done;
7618 /* Editor is done; we can now apply unveil(2) */
7619 err = got_sigs_apply_unveil();
7620 if (err)
7621 goto done;
7622 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7623 if (err)
7624 goto done;
7627 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7628 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7629 verbosity);
7630 if (err) {
7631 if (tagmsg_path)
7632 preserve_tagmsg = 1;
7633 goto done;
7636 err = got_ref_alloc(&ref, refname, tag_id);
7637 if (err) {
7638 if (tagmsg_path)
7639 preserve_tagmsg = 1;
7640 goto done;
7643 err = got_ref_write(ref, repo);
7644 if (err) {
7645 if (tagmsg_path)
7646 preserve_tagmsg = 1;
7647 goto done;
7650 err = got_object_id_str(&tag_id_str, tag_id);
7651 if (err) {
7652 if (tagmsg_path)
7653 preserve_tagmsg = 1;
7654 goto done;
7656 printf("Created tag %s\n", tag_id_str);
7657 done:
7658 if (preserve_tagmsg) {
7659 fprintf(stderr, "%s: tag message preserved in %s\n",
7660 getprogname(), tagmsg_path);
7661 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7662 err = got_error_from_errno2("unlink", tagmsg_path);
7663 free(tag_id_str);
7664 if (ref)
7665 got_ref_close(ref);
7666 free(commit_id);
7667 free(commit_id_str);
7668 free(refname);
7669 free(tagmsg);
7670 free(tagmsg_path);
7671 got_ref_list_free(&refs);
7672 return err;
7675 static const struct got_error *
7676 cmd_tag(int argc, char *argv[])
7678 const struct got_error *error = NULL;
7679 struct got_repository *repo = NULL;
7680 struct got_worktree *worktree = NULL;
7681 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7682 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7683 char *allowed_signers = NULL, *revoked_signers = NULL;
7684 const char *signer_id = NULL;
7685 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7686 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7687 int *pack_fds = NULL;
7689 #ifndef PROFILE
7690 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7691 "sendfd unveil", NULL) == -1)
7692 err(1, "pledge");
7693 #endif
7695 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7696 switch (ch) {
7697 case 'c':
7698 commit_id_arg = optarg;
7699 break;
7700 case 'l':
7701 do_list = 1;
7702 break;
7703 case 'm':
7704 tagmsg = optarg;
7705 break;
7706 case 'r':
7707 repo_path = realpath(optarg, NULL);
7708 if (repo_path == NULL) {
7709 error = got_error_from_errno2("realpath",
7710 optarg);
7711 goto done;
7713 got_path_strip_trailing_slashes(repo_path);
7714 break;
7715 case 's':
7716 signer_id = optarg;
7717 break;
7718 case 'V':
7719 verify_tags = 1;
7720 break;
7721 case 'v':
7722 if (verbosity < 0)
7723 verbosity = 0;
7724 else if (verbosity < 3)
7725 verbosity++;
7726 break;
7727 default:
7728 usage_tag();
7729 /* NOTREACHED */
7733 argc -= optind;
7734 argv += optind;
7736 if (do_list || verify_tags) {
7737 if (commit_id_arg != NULL)
7738 errx(1,
7739 "-c option can only be used when creating a tag");
7740 if (tagmsg) {
7741 if (do_list)
7742 option_conflict('l', 'm');
7743 else
7744 option_conflict('V', 'm');
7746 if (signer_id) {
7747 if (do_list)
7748 option_conflict('l', 's');
7749 else
7750 option_conflict('V', 's');
7752 if (argc > 1)
7753 usage_tag();
7754 } else if (argc != 1)
7755 usage_tag();
7757 if (argc == 1)
7758 tag_name = argv[0];
7760 cwd = getcwd(NULL, 0);
7761 if (cwd == NULL) {
7762 error = got_error_from_errno("getcwd");
7763 goto done;
7766 error = got_repo_pack_fds_open(&pack_fds);
7767 if (error != NULL)
7768 goto done;
7770 if (repo_path == NULL) {
7771 error = got_worktree_open(&worktree, cwd,
7772 GOT_WORKTREE_GOT_DIR);
7773 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7774 goto done;
7775 else
7776 error = NULL;
7777 if (worktree) {
7778 repo_path =
7779 strdup(got_worktree_get_repo_path(worktree));
7780 if (repo_path == NULL)
7781 error = got_error_from_errno("strdup");
7782 if (error)
7783 goto done;
7784 } else {
7785 repo_path = strdup(cwd);
7786 if (repo_path == NULL) {
7787 error = got_error_from_errno("strdup");
7788 goto done;
7793 if (do_list || verify_tags) {
7794 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7795 if (error != NULL)
7796 goto done;
7797 error = get_allowed_signers(&allowed_signers, repo, worktree);
7798 if (error)
7799 goto done;
7800 error = get_revoked_signers(&revoked_signers, repo, worktree);
7801 if (error)
7802 goto done;
7803 if (worktree) {
7804 /* Release work tree lock. */
7805 got_worktree_close(worktree);
7806 worktree = NULL;
7810 * Remove "cpath" promise unless needed for signature tmpfile
7811 * creation.
7813 if (verify_tags)
7814 got_sigs_apply_unveil();
7815 else {
7816 #ifndef PROFILE
7817 if (pledge("stdio rpath wpath flock proc exec sendfd "
7818 "unveil", NULL) == -1)
7819 err(1, "pledge");
7820 #endif
7822 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7823 if (error)
7824 goto done;
7825 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7826 revoked_signers, verbosity);
7827 } else {
7828 error = get_gitconfig_path(&gitconfig_path);
7829 if (error)
7830 goto done;
7831 error = got_repo_open(&repo, repo_path, gitconfig_path,
7832 pack_fds);
7833 if (error != NULL)
7834 goto done;
7836 error = get_author(&tagger, repo, worktree);
7837 if (error)
7838 goto done;
7839 if (signer_id == NULL)
7840 signer_id = get_signer_id(repo, worktree);
7842 if (tagmsg) {
7843 if (signer_id) {
7844 error = got_sigs_apply_unveil();
7845 if (error)
7846 goto done;
7848 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7849 if (error)
7850 goto done;
7853 if (commit_id_arg == NULL) {
7854 struct got_reference *head_ref;
7855 struct got_object_id *commit_id;
7856 error = got_ref_open(&head_ref, repo,
7857 worktree ? got_worktree_get_head_ref_name(worktree)
7858 : GOT_REF_HEAD, 0);
7859 if (error)
7860 goto done;
7861 error = got_ref_resolve(&commit_id, repo, head_ref);
7862 got_ref_close(head_ref);
7863 if (error)
7864 goto done;
7865 error = got_object_id_str(&commit_id_str, commit_id);
7866 free(commit_id);
7867 if (error)
7868 goto done;
7869 } else {
7870 error = got_keyword_to_idstr(&keyword_idstr,
7871 commit_id_arg, repo, worktree);
7872 if (error != NULL)
7873 goto done;
7874 commit_id_str = keyword_idstr;
7877 if (worktree) {
7878 /* Release work tree lock. */
7879 got_worktree_close(worktree);
7880 worktree = NULL;
7883 error = add_tag(repo, tagger, tag_name,
7884 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7885 signer_id, verbosity);
7887 done:
7888 if (repo) {
7889 const struct got_error *close_err = got_repo_close(repo);
7890 if (error == NULL)
7891 error = close_err;
7893 if (worktree)
7894 got_worktree_close(worktree);
7895 if (pack_fds) {
7896 const struct got_error *pack_err =
7897 got_repo_pack_fds_close(pack_fds);
7898 if (error == NULL)
7899 error = pack_err;
7901 free(cwd);
7902 free(repo_path);
7903 free(gitconfig_path);
7904 free(commit_id_str);
7905 free(tagger);
7906 free(allowed_signers);
7907 free(revoked_signers);
7908 return error;
7911 __dead static void
7912 usage_add(void)
7914 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7915 exit(1);
7918 static const struct got_error *
7919 add_progress(void *arg, unsigned char status, const char *path)
7921 while (path[0] == '/')
7922 path++;
7923 printf("%c %s\n", status, path);
7924 return NULL;
7927 static const struct got_error *
7928 cmd_add(int argc, char *argv[])
7930 const struct got_error *error = NULL;
7931 struct got_repository *repo = NULL;
7932 struct got_worktree *worktree = NULL;
7933 char *cwd = NULL;
7934 struct got_pathlist_head paths;
7935 struct got_pathlist_entry *pe;
7936 int ch, can_recurse = 0, no_ignores = 0;
7937 int *pack_fds = NULL;
7939 TAILQ_INIT(&paths);
7941 #ifndef PROFILE
7942 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7943 NULL) == -1)
7944 err(1, "pledge");
7945 #endif
7947 while ((ch = getopt(argc, argv, "IR")) != -1) {
7948 switch (ch) {
7949 case 'I':
7950 no_ignores = 1;
7951 break;
7952 case 'R':
7953 can_recurse = 1;
7954 break;
7955 default:
7956 usage_add();
7957 /* NOTREACHED */
7961 argc -= optind;
7962 argv += optind;
7964 if (argc < 1)
7965 usage_add();
7967 cwd = getcwd(NULL, 0);
7968 if (cwd == NULL) {
7969 error = got_error_from_errno("getcwd");
7970 goto done;
7973 error = got_repo_pack_fds_open(&pack_fds);
7974 if (error != NULL)
7975 goto done;
7977 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7978 if (error) {
7979 if (error->code == GOT_ERR_NOT_WORKTREE)
7980 error = wrap_not_worktree_error(error, "add", cwd);
7981 goto done;
7984 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7985 NULL, pack_fds);
7986 if (error != NULL)
7987 goto done;
7989 error = apply_unveil(got_repo_get_path(repo), 1,
7990 got_worktree_get_root_path(worktree));
7991 if (error)
7992 goto done;
7994 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7995 if (error)
7996 goto done;
7998 if (!can_recurse) {
7999 char *ondisk_path;
8000 struct stat sb;
8001 TAILQ_FOREACH(pe, &paths, entry) {
8002 if (asprintf(&ondisk_path, "%s/%s",
8003 got_worktree_get_root_path(worktree),
8004 pe->path) == -1) {
8005 error = got_error_from_errno("asprintf");
8006 goto done;
8008 if (lstat(ondisk_path, &sb) == -1) {
8009 if (errno == ENOENT) {
8010 free(ondisk_path);
8011 continue;
8013 error = got_error_from_errno2("lstat",
8014 ondisk_path);
8015 free(ondisk_path);
8016 goto done;
8018 free(ondisk_path);
8019 if (S_ISDIR(sb.st_mode)) {
8020 error = got_error_msg(GOT_ERR_BAD_PATH,
8021 "adding directories requires -R option");
8022 goto done;
8027 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8028 NULL, repo, no_ignores);
8029 done:
8030 if (repo) {
8031 const struct got_error *close_err = got_repo_close(repo);
8032 if (error == NULL)
8033 error = close_err;
8035 if (worktree)
8036 got_worktree_close(worktree);
8037 if (pack_fds) {
8038 const struct got_error *pack_err =
8039 got_repo_pack_fds_close(pack_fds);
8040 if (error == NULL)
8041 error = pack_err;
8043 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8044 free(cwd);
8045 return error;
8048 __dead static void
8049 usage_remove(void)
8051 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8052 getprogname());
8053 exit(1);
8056 static const struct got_error *
8057 print_remove_status(void *arg, unsigned char status,
8058 unsigned char staged_status, const char *path)
8060 while (path[0] == '/')
8061 path++;
8062 if (status == GOT_STATUS_NONEXISTENT)
8063 return NULL;
8064 if (status == staged_status && (status == GOT_STATUS_DELETE))
8065 status = GOT_STATUS_NO_CHANGE;
8066 printf("%c%c %s\n", status, staged_status, path);
8067 return NULL;
8070 static const struct got_error *
8071 cmd_remove(int argc, char *argv[])
8073 const struct got_error *error = NULL;
8074 struct got_worktree *worktree = NULL;
8075 struct got_repository *repo = NULL;
8076 const char *status_codes = NULL;
8077 char *cwd = NULL;
8078 struct got_pathlist_head paths;
8079 struct got_pathlist_entry *pe;
8080 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8081 int ignore_missing_paths = 0;
8082 int *pack_fds = NULL;
8084 TAILQ_INIT(&paths);
8086 #ifndef PROFILE
8087 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8088 NULL) == -1)
8089 err(1, "pledge");
8090 #endif
8092 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8093 switch (ch) {
8094 case 'f':
8095 delete_local_mods = 1;
8096 ignore_missing_paths = 1;
8097 break;
8098 case 'k':
8099 keep_on_disk = 1;
8100 break;
8101 case 'R':
8102 can_recurse = 1;
8103 break;
8104 case 's':
8105 for (i = 0; optarg[i] != '\0'; i++) {
8106 switch (optarg[i]) {
8107 case GOT_STATUS_MODIFY:
8108 delete_local_mods = 1;
8109 break;
8110 case GOT_STATUS_MISSING:
8111 ignore_missing_paths = 1;
8112 break;
8113 default:
8114 errx(1, "invalid status code '%c'",
8115 optarg[i]);
8118 status_codes = optarg;
8119 break;
8120 default:
8121 usage_remove();
8122 /* NOTREACHED */
8126 argc -= optind;
8127 argv += optind;
8129 if (argc < 1)
8130 usage_remove();
8132 cwd = getcwd(NULL, 0);
8133 if (cwd == NULL) {
8134 error = got_error_from_errno("getcwd");
8135 goto done;
8138 error = got_repo_pack_fds_open(&pack_fds);
8139 if (error != NULL)
8140 goto done;
8142 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8143 if (error) {
8144 if (error->code == GOT_ERR_NOT_WORKTREE)
8145 error = wrap_not_worktree_error(error, "remove", cwd);
8146 goto done;
8149 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8150 NULL, pack_fds);
8151 if (error)
8152 goto done;
8154 error = apply_unveil(got_repo_get_path(repo), 1,
8155 got_worktree_get_root_path(worktree));
8156 if (error)
8157 goto done;
8159 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8160 if (error)
8161 goto done;
8163 if (!can_recurse) {
8164 char *ondisk_path;
8165 struct stat sb;
8166 TAILQ_FOREACH(pe, &paths, entry) {
8167 if (asprintf(&ondisk_path, "%s/%s",
8168 got_worktree_get_root_path(worktree),
8169 pe->path) == -1) {
8170 error = got_error_from_errno("asprintf");
8171 goto done;
8173 if (lstat(ondisk_path, &sb) == -1) {
8174 if (errno == ENOENT) {
8175 free(ondisk_path);
8176 continue;
8178 error = got_error_from_errno2("lstat",
8179 ondisk_path);
8180 free(ondisk_path);
8181 goto done;
8183 free(ondisk_path);
8184 if (S_ISDIR(sb.st_mode)) {
8185 error = got_error_msg(GOT_ERR_BAD_PATH,
8186 "removing directories requires -R option");
8187 goto done;
8192 error = got_worktree_schedule_delete(worktree, &paths,
8193 delete_local_mods, status_codes, print_remove_status, NULL,
8194 repo, keep_on_disk, ignore_missing_paths);
8195 done:
8196 if (repo) {
8197 const struct got_error *close_err = got_repo_close(repo);
8198 if (error == NULL)
8199 error = close_err;
8201 if (worktree)
8202 got_worktree_close(worktree);
8203 if (pack_fds) {
8204 const struct got_error *pack_err =
8205 got_repo_pack_fds_close(pack_fds);
8206 if (error == NULL)
8207 error = pack_err;
8209 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8210 free(cwd);
8211 return error;
8214 __dead static void
8215 usage_patch(void)
8217 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8218 "[patchfile]\n", getprogname());
8219 exit(1);
8222 static const struct got_error *
8223 patch_from_stdin(int *patchfd)
8225 const struct got_error *err = NULL;
8226 ssize_t r;
8227 char buf[BUFSIZ];
8228 sig_t sighup, sigint, sigquit;
8230 *patchfd = got_opentempfd();
8231 if (*patchfd == -1)
8232 return got_error_from_errno("got_opentempfd");
8234 sighup = signal(SIGHUP, SIG_DFL);
8235 sigint = signal(SIGINT, SIG_DFL);
8236 sigquit = signal(SIGQUIT, SIG_DFL);
8238 for (;;) {
8239 r = read(0, buf, sizeof(buf));
8240 if (r == -1) {
8241 err = got_error_from_errno("read");
8242 break;
8244 if (r == 0)
8245 break;
8246 if (write(*patchfd, buf, r) == -1) {
8247 err = got_error_from_errno("write");
8248 break;
8252 signal(SIGHUP, sighup);
8253 signal(SIGINT, sigint);
8254 signal(SIGQUIT, sigquit);
8256 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8257 err = got_error_from_errno("lseek");
8259 if (err != NULL) {
8260 close(*patchfd);
8261 *patchfd = -1;
8264 return err;
8267 struct got_patch_progress_arg {
8268 int did_something;
8269 int conflicts;
8270 int rejects;
8273 static const struct got_error *
8274 patch_progress(void *arg, const char *old, const char *new,
8275 unsigned char status, const struct got_error *error, int old_from,
8276 int old_lines, int new_from, int new_lines, int offset,
8277 int ws_mangled, const struct got_error *hunk_err)
8279 const char *path = new == NULL ? old : new;
8280 struct got_patch_progress_arg *a = arg;
8282 while (*path == '/')
8283 path++;
8285 if (status != GOT_STATUS_NO_CHANGE &&
8286 status != 0 /* per-hunk progress */) {
8287 printf("%c %s\n", status, path);
8288 a->did_something = 1;
8291 if (hunk_err == NULL) {
8292 if (status == GOT_STATUS_CANNOT_UPDATE)
8293 a->rejects++;
8294 else if (status == GOT_STATUS_CONFLICT)
8295 a->conflicts++;
8298 if (error != NULL)
8299 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8301 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8302 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8303 old_lines, new_from, new_lines);
8304 if (hunk_err != NULL)
8305 printf("%s\n", hunk_err->msg);
8306 else if (offset != 0)
8307 printf("applied with offset %d\n", offset);
8308 else
8309 printf("hunk contains mangled whitespace\n");
8312 return NULL;
8315 static void
8316 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8318 if (!ppa->did_something)
8319 return;
8321 if (ppa->conflicts > 0)
8322 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8324 if (ppa->rejects > 0) {
8325 printf("Files where patch failed to apply: %d\n",
8326 ppa->rejects);
8330 static const struct got_error *
8331 cmd_patch(int argc, char *argv[])
8333 const struct got_error *error = NULL, *close_error = NULL;
8334 struct got_worktree *worktree = NULL;
8335 struct got_repository *repo = NULL;
8336 struct got_reflist_head refs;
8337 struct got_object_id *commit_id = NULL;
8338 const char *commit_id_str = NULL;
8339 struct stat sb;
8340 const char *errstr;
8341 char *cwd = NULL, *keyword_idstr = NULL;
8342 int ch, nop = 0, strip = -1, reverse = 0;
8343 int patchfd;
8344 int *pack_fds = NULL;
8345 struct got_patch_progress_arg ppa;
8347 TAILQ_INIT(&refs);
8349 #ifndef PROFILE
8350 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8351 "unveil", NULL) == -1)
8352 err(1, "pledge");
8353 #endif
8355 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8356 switch (ch) {
8357 case 'c':
8358 commit_id_str = optarg;
8359 break;
8360 case 'n':
8361 nop = 1;
8362 break;
8363 case 'p':
8364 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8365 if (errstr != NULL)
8366 errx(1, "pathname strip count is %s: %s",
8367 errstr, optarg);
8368 break;
8369 case 'R':
8370 reverse = 1;
8371 break;
8372 default:
8373 usage_patch();
8374 /* NOTREACHED */
8378 argc -= optind;
8379 argv += optind;
8381 if (argc == 0) {
8382 error = patch_from_stdin(&patchfd);
8383 if (error)
8384 return error;
8385 } else if (argc == 1) {
8386 patchfd = open(argv[0], O_RDONLY);
8387 if (patchfd == -1) {
8388 error = got_error_from_errno2("open", argv[0]);
8389 return error;
8391 if (fstat(patchfd, &sb) == -1) {
8392 error = got_error_from_errno2("fstat", argv[0]);
8393 goto done;
8395 if (!S_ISREG(sb.st_mode)) {
8396 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8397 goto done;
8399 } else
8400 usage_patch();
8402 if ((cwd = getcwd(NULL, 0)) == NULL) {
8403 error = got_error_from_errno("getcwd");
8404 goto done;
8407 error = got_repo_pack_fds_open(&pack_fds);
8408 if (error != NULL)
8409 goto done;
8411 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8412 if (error != NULL)
8413 goto done;
8415 const char *repo_path = got_worktree_get_repo_path(worktree);
8416 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8417 if (error != NULL)
8418 goto done;
8420 error = apply_unveil(got_repo_get_path(repo), 0,
8421 got_worktree_get_root_path(worktree));
8422 if (error != NULL)
8423 goto done;
8425 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8426 if (error)
8427 goto done;
8429 if (commit_id_str != NULL) {
8430 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8431 repo, worktree);
8432 if (error != NULL)
8433 goto done;
8435 error = got_repo_match_object_id(&commit_id, NULL,
8436 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8437 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8438 if (error)
8439 goto done;
8442 memset(&ppa, 0, sizeof(ppa));
8443 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8444 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8445 print_patch_progress_stats(&ppa);
8446 done:
8447 got_ref_list_free(&refs);
8448 free(keyword_idstr);
8449 free(commit_id);
8450 if (repo) {
8451 close_error = got_repo_close(repo);
8452 if (error == NULL)
8453 error = close_error;
8455 if (worktree != NULL) {
8456 close_error = got_worktree_close(worktree);
8457 if (error == NULL)
8458 error = close_error;
8460 if (pack_fds) {
8461 const struct got_error *pack_err =
8462 got_repo_pack_fds_close(pack_fds);
8463 if (error == NULL)
8464 error = pack_err;
8466 free(cwd);
8467 return error;
8470 __dead static void
8471 usage_revert(void)
8473 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8474 getprogname());
8475 exit(1);
8478 static const struct got_error *
8479 revert_progress(void *arg, unsigned char status, const char *path)
8481 if (status == GOT_STATUS_UNVERSIONED)
8482 return NULL;
8484 while (path[0] == '/')
8485 path++;
8486 printf("%c %s\n", status, path);
8487 return NULL;
8490 struct choose_patch_arg {
8491 FILE *patch_script_file;
8492 const char *action;
8495 static const struct got_error *
8496 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8497 int nchanges, const char *action)
8499 const struct got_error *err;
8500 char *line = NULL;
8501 size_t linesize = 0;
8502 ssize_t linelen;
8504 switch (status) {
8505 case GOT_STATUS_ADD:
8506 printf("A %s\n%s this addition? [y/n] ", path, action);
8507 break;
8508 case GOT_STATUS_DELETE:
8509 printf("D %s\n%s this deletion? [y/n] ", path, action);
8510 break;
8511 case GOT_STATUS_MODIFY:
8512 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8513 return got_error_from_errno("fseek");
8514 printf(GOT_COMMIT_SEP_STR);
8515 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8516 printf("%s", line);
8517 if (linelen == -1 && ferror(patch_file)) {
8518 err = got_error_from_errno("getline");
8519 free(line);
8520 return err;
8522 free(line);
8523 printf(GOT_COMMIT_SEP_STR);
8524 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8525 path, n, nchanges, action);
8526 break;
8527 default:
8528 return got_error_path(path, GOT_ERR_FILE_STATUS);
8531 fflush(stdout);
8532 return NULL;
8535 static const struct got_error *
8536 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8537 FILE *patch_file, int n, int nchanges)
8539 const struct got_error *err = NULL;
8540 char *line = NULL;
8541 size_t linesize = 0;
8542 ssize_t linelen;
8543 int resp = ' ';
8544 struct choose_patch_arg *a = arg;
8546 *choice = GOT_PATCH_CHOICE_NONE;
8548 if (a->patch_script_file) {
8549 char *nl;
8550 err = show_change(status, path, patch_file, n, nchanges,
8551 a->action);
8552 if (err)
8553 return err;
8554 linelen = getline(&line, &linesize, a->patch_script_file);
8555 if (linelen == -1) {
8556 if (ferror(a->patch_script_file))
8557 return got_error_from_errno("getline");
8558 return NULL;
8560 nl = strchr(line, '\n');
8561 if (nl)
8562 *nl = '\0';
8563 if (strcmp(line, "y") == 0) {
8564 *choice = GOT_PATCH_CHOICE_YES;
8565 printf("y\n");
8566 } else if (strcmp(line, "n") == 0) {
8567 *choice = GOT_PATCH_CHOICE_NO;
8568 printf("n\n");
8569 } else if (strcmp(line, "q") == 0 &&
8570 status == GOT_STATUS_MODIFY) {
8571 *choice = GOT_PATCH_CHOICE_QUIT;
8572 printf("q\n");
8573 } else
8574 printf("invalid response '%s'\n", line);
8575 free(line);
8576 return NULL;
8579 while (resp != 'y' && resp != 'n' && resp != 'q') {
8580 err = show_change(status, path, patch_file, n, nchanges,
8581 a->action);
8582 if (err)
8583 return err;
8584 resp = getchar();
8585 if (resp == '\n')
8586 resp = getchar();
8587 if (status == GOT_STATUS_MODIFY) {
8588 if (resp != 'y' && resp != 'n' && resp != 'q') {
8589 printf("invalid response '%c'\n", resp);
8590 resp = ' ';
8592 } else if (resp != 'y' && resp != 'n') {
8593 printf("invalid response '%c'\n", resp);
8594 resp = ' ';
8598 if (resp == 'y')
8599 *choice = GOT_PATCH_CHOICE_YES;
8600 else if (resp == 'n')
8601 *choice = GOT_PATCH_CHOICE_NO;
8602 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8603 *choice = GOT_PATCH_CHOICE_QUIT;
8605 return NULL;
8608 struct wt_commitable_path_arg {
8609 struct got_pathlist_head *commit_paths;
8610 int *has_changes;
8614 * Shortcut work tree status callback to determine if the set of paths scanned
8615 * has at least one versioned path that is being modified and, if not NULL, is
8616 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8617 * soon as a path is passed with a status that satisfies this criteria.
8619 static const struct got_error *
8620 worktree_has_commitable_path(void *arg, unsigned char status,
8621 unsigned char staged_status, const char *path,
8622 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8623 struct got_object_id *commit_id, int dirfd, const char *de_name)
8625 struct wt_commitable_path_arg *a = arg;
8627 if (status == staged_status && (status == GOT_STATUS_DELETE))
8628 status = GOT_STATUS_NO_CHANGE;
8630 if (!(status == GOT_STATUS_NO_CHANGE ||
8631 status == GOT_STATUS_UNVERSIONED) ||
8632 staged_status != GOT_STATUS_NO_CHANGE) {
8633 if (a->commit_paths != NULL) {
8634 struct got_pathlist_entry *pe;
8636 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8637 if (strncmp(path, pe->path,
8638 pe->path_len) == 0) {
8639 *a->has_changes = 1;
8640 break;
8643 } else
8644 *a->has_changes = 1;
8646 if (*a->has_changes)
8647 return got_error(GOT_ERR_FILE_MODIFIED);
8650 return NULL;
8654 * Check that the changeset of the commit identified by id is
8655 * comprised of at least one modified path that is being committed.
8657 static const struct got_error *
8658 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8659 struct got_object_id *id, struct got_worktree *worktree,
8660 struct got_repository *repo)
8662 const struct got_error *err;
8663 struct got_pathlist_head paths;
8664 struct got_commit_object *commit = NULL, *pcommit = NULL;
8665 struct got_tree_object *tree = NULL, *ptree = NULL;
8666 struct got_object_qid *pid;
8668 TAILQ_INIT(&paths);
8670 err = got_object_open_as_commit(&commit, repo, id);
8671 if (err)
8672 goto done;
8674 err = got_object_open_as_tree(&tree, repo,
8675 got_object_commit_get_tree_id(commit));
8676 if (err)
8677 goto done;
8679 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8680 if (pid != NULL) {
8681 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8682 if (err)
8683 goto done;
8685 err = got_object_open_as_tree(&ptree, repo,
8686 got_object_commit_get_tree_id(pcommit));
8687 if (err)
8688 goto done;
8691 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8692 got_diff_tree_collect_changed_paths, &paths, 0);
8693 if (err)
8694 goto done;
8696 err = got_worktree_status(worktree, &paths, repo, 0,
8697 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8698 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8700 * At least one changed path in the referenced commit is
8701 * modified in the work tree, that's all we need to know!
8703 err = NULL;
8706 done:
8707 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8708 if (commit)
8709 got_object_commit_close(commit);
8710 if (pcommit)
8711 got_object_commit_close(pcommit);
8712 if (tree)
8713 got_object_tree_close(tree);
8714 if (ptree)
8715 got_object_tree_close(ptree);
8716 return err;
8720 * Remove any "logmsg" reference comprised entirely of paths that have
8721 * been reverted in this work tree. If any path in the logmsg ref changeset
8722 * remains in a changed state in the worktree, do not remove the reference.
8724 static const struct got_error *
8725 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8727 const struct got_error *err;
8728 struct got_reflist_head refs;
8729 struct got_reflist_entry *re;
8730 struct got_commit_object *commit = NULL;
8731 struct got_object_id *commit_id = NULL;
8732 struct wt_commitable_path_arg wcpa;
8733 char *uuidstr = NULL;
8735 TAILQ_INIT(&refs);
8737 err = got_worktree_get_uuid(&uuidstr, worktree);
8738 if (err)
8739 goto done;
8741 err = got_ref_list(&refs, repo, "refs/got/worktree",
8742 got_ref_cmp_by_name, repo);
8743 if (err)
8744 goto done;
8746 TAILQ_FOREACH(re, &refs, entry) {
8747 const char *refname;
8748 int has_changes = 0;
8750 refname = got_ref_get_name(re->ref);
8752 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8753 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8754 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8755 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8756 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8757 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8758 else
8759 continue;
8761 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8762 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8763 else
8764 continue;
8766 err = got_repo_match_object_id(&commit_id, NULL, refname,
8767 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8768 if (err)
8769 goto done;
8771 err = got_object_open_as_commit(&commit, repo, commit_id);
8772 if (err)
8773 goto done;
8775 wcpa.commit_paths = NULL;
8776 wcpa.has_changes = &has_changes;
8778 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8779 worktree, repo);
8780 if (err)
8781 goto done;
8783 if (!has_changes) {
8784 err = got_ref_delete(re->ref, repo);
8785 if (err)
8786 goto done;
8789 got_object_commit_close(commit);
8790 commit = NULL;
8791 free(commit_id);
8792 commit_id = NULL;
8795 done:
8796 free(uuidstr);
8797 free(commit_id);
8798 got_ref_list_free(&refs);
8799 if (commit)
8800 got_object_commit_close(commit);
8801 return err;
8804 static const struct got_error *
8805 cmd_revert(int argc, char *argv[])
8807 const struct got_error *error = NULL;
8808 struct got_worktree *worktree = NULL;
8809 struct got_repository *repo = NULL;
8810 char *cwd = NULL, *path = NULL;
8811 struct got_pathlist_head paths;
8812 struct got_pathlist_entry *pe;
8813 int ch, can_recurse = 0, pflag = 0;
8814 FILE *patch_script_file = NULL;
8815 const char *patch_script_path = NULL;
8816 struct choose_patch_arg cpa;
8817 int *pack_fds = NULL;
8819 TAILQ_INIT(&paths);
8821 #ifndef PROFILE
8822 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8823 "unveil", NULL) == -1)
8824 err(1, "pledge");
8825 #endif
8827 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8828 switch (ch) {
8829 case 'F':
8830 patch_script_path = optarg;
8831 break;
8832 case 'p':
8833 pflag = 1;
8834 break;
8835 case 'R':
8836 can_recurse = 1;
8837 break;
8838 default:
8839 usage_revert();
8840 /* NOTREACHED */
8844 argc -= optind;
8845 argv += optind;
8847 if (argc < 1)
8848 usage_revert();
8849 if (patch_script_path && !pflag)
8850 errx(1, "-F option can only be used together with -p option");
8852 cwd = getcwd(NULL, 0);
8853 if (cwd == NULL) {
8854 error = got_error_from_errno("getcwd");
8855 goto done;
8858 error = got_repo_pack_fds_open(&pack_fds);
8859 if (error != NULL)
8860 goto done;
8862 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8863 if (error) {
8864 if (error->code == GOT_ERR_NOT_WORKTREE)
8865 error = wrap_not_worktree_error(error, "revert", cwd);
8866 goto done;
8869 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8870 NULL, pack_fds);
8871 if (error != NULL)
8872 goto done;
8874 if (patch_script_path) {
8875 patch_script_file = fopen(patch_script_path, "re");
8876 if (patch_script_file == NULL) {
8877 error = got_error_from_errno2("fopen",
8878 patch_script_path);
8879 goto done;
8884 * XXX "c" perm needed on repo dir to delete merge references.
8886 error = apply_unveil(got_repo_get_path(repo), 0,
8887 got_worktree_get_root_path(worktree));
8888 if (error)
8889 goto done;
8891 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8892 if (error)
8893 goto done;
8895 if (!can_recurse) {
8896 char *ondisk_path;
8897 struct stat sb;
8898 TAILQ_FOREACH(pe, &paths, entry) {
8899 if (asprintf(&ondisk_path, "%s/%s",
8900 got_worktree_get_root_path(worktree),
8901 pe->path) == -1) {
8902 error = got_error_from_errno("asprintf");
8903 goto done;
8905 if (lstat(ondisk_path, &sb) == -1) {
8906 if (errno == ENOENT) {
8907 free(ondisk_path);
8908 continue;
8910 error = got_error_from_errno2("lstat",
8911 ondisk_path);
8912 free(ondisk_path);
8913 goto done;
8915 free(ondisk_path);
8916 if (S_ISDIR(sb.st_mode)) {
8917 error = got_error_msg(GOT_ERR_BAD_PATH,
8918 "reverting directories requires -R option");
8919 goto done;
8924 cpa.patch_script_file = patch_script_file;
8925 cpa.action = "revert";
8926 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8927 pflag ? choose_patch : NULL, &cpa, repo);
8929 error = rm_logmsg_ref(worktree, repo);
8930 done:
8931 if (patch_script_file && fclose(patch_script_file) == EOF &&
8932 error == NULL)
8933 error = got_error_from_errno2("fclose", patch_script_path);
8934 if (repo) {
8935 const struct got_error *close_err = got_repo_close(repo);
8936 if (error == NULL)
8937 error = close_err;
8939 if (worktree)
8940 got_worktree_close(worktree);
8941 if (pack_fds) {
8942 const struct got_error *pack_err =
8943 got_repo_pack_fds_close(pack_fds);
8944 if (error == NULL)
8945 error = pack_err;
8947 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8948 free(path);
8949 free(cwd);
8950 return error;
8953 __dead static void
8954 usage_commit(void)
8956 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8957 "[-m message] [path ...]\n", getprogname());
8958 exit(1);
8961 struct collect_commit_logmsg_arg {
8962 const char *cmdline_log;
8963 const char *prepared_log;
8964 const char *merged_log;
8965 int non_interactive;
8966 const char *editor;
8967 const char *worktree_path;
8968 const char *branch_name;
8969 const char *repo_path;
8970 char *logmsg_path;
8974 static const struct got_error *
8975 read_prepared_logmsg(char **logmsg, const char *path)
8977 const struct got_error *err = NULL;
8978 FILE *f = NULL;
8979 struct stat sb;
8980 size_t r;
8982 *logmsg = NULL;
8983 memset(&sb, 0, sizeof(sb));
8985 f = fopen(path, "re");
8986 if (f == NULL)
8987 return got_error_from_errno2("fopen", path);
8989 if (fstat(fileno(f), &sb) == -1) {
8990 err = got_error_from_errno2("fstat", path);
8991 goto done;
8993 if (sb.st_size == 0) {
8994 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8995 goto done;
8998 *logmsg = malloc(sb.st_size + 1);
8999 if (*logmsg == NULL) {
9000 err = got_error_from_errno("malloc");
9001 goto done;
9004 r = fread(*logmsg, 1, sb.st_size, f);
9005 if (r != sb.st_size) {
9006 if (ferror(f))
9007 err = got_error_from_errno2("fread", path);
9008 else
9009 err = got_error(GOT_ERR_IO);
9010 goto done;
9012 (*logmsg)[sb.st_size] = '\0';
9013 done:
9014 if (fclose(f) == EOF && err == NULL)
9015 err = got_error_from_errno2("fclose", path);
9016 if (err) {
9017 free(*logmsg);
9018 *logmsg = NULL;
9020 return err;
9023 static const struct got_error *
9024 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9025 const char *diff_path, char **logmsg, void *arg)
9027 char *initial_content = NULL;
9028 struct got_pathlist_entry *pe;
9029 const struct got_error *err = NULL;
9030 char *template = NULL;
9031 char *prepared_msg = NULL, *merged_msg = NULL;
9032 struct collect_commit_logmsg_arg *a = arg;
9033 int initial_content_len;
9034 int fd = -1;
9035 size_t len;
9037 /* if a message was specified on the command line, just use it */
9038 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9039 len = strlen(a->cmdline_log) + 1;
9040 *logmsg = malloc(len + 1);
9041 if (*logmsg == NULL)
9042 return got_error_from_errno("malloc");
9043 strlcpy(*logmsg, a->cmdline_log, len);
9044 return NULL;
9045 } else if (a->prepared_log != NULL && a->non_interactive)
9046 return read_prepared_logmsg(logmsg, a->prepared_log);
9048 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9049 return got_error_from_errno("asprintf");
9051 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9052 if (err)
9053 goto done;
9055 if (a->prepared_log) {
9056 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9057 if (err)
9058 goto done;
9059 } else if (a->merged_log) {
9060 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9061 if (err)
9062 goto done;
9065 initial_content_len = asprintf(&initial_content,
9066 "%s%s\n# changes to be committed on branch %s:\n",
9067 prepared_msg ? prepared_msg : "",
9068 merged_msg ? merged_msg : "", a->branch_name);
9069 if (initial_content_len == -1) {
9070 err = got_error_from_errno("asprintf");
9071 goto done;
9074 if (write(fd, initial_content, initial_content_len) == -1) {
9075 err = got_error_from_errno2("write", a->logmsg_path);
9076 goto done;
9079 TAILQ_FOREACH(pe, commitable_paths, entry) {
9080 struct got_commitable *ct = pe->data;
9081 dprintf(fd, "# %c %s\n",
9082 got_commitable_get_status(ct),
9083 got_commitable_get_path(ct));
9086 if (diff_path) {
9087 dprintf(fd, "# detailed changes can be viewed in %s\n",
9088 diff_path);
9091 if (close(fd) == -1) {
9092 err = got_error_from_errno2("close", a->logmsg_path);
9093 goto done;
9095 fd = -1;
9097 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9098 initial_content_len, a->prepared_log ? 0 : 1);
9099 done:
9100 free(initial_content);
9101 free(template);
9102 free(prepared_msg);
9103 free(merged_msg);
9105 if (fd != -1 && close(fd) == -1 && err == NULL)
9106 err = got_error_from_errno2("close", a->logmsg_path);
9108 /* Editor is done; we can now apply unveil(2) */
9109 if (err == NULL)
9110 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9111 if (err) {
9112 free(*logmsg);
9113 *logmsg = NULL;
9115 return err;
9118 static const struct got_error *
9119 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9120 const char *type, int has_content)
9122 const struct got_error *err = NULL;
9123 char *logmsg = NULL;
9125 err = got_object_commit_get_logmsg(&logmsg, commit);
9126 if (err)
9127 return err;
9129 if (fprintf(f, "%s# log message of %s commit %s:%s",
9130 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9131 err = got_ferror(f, GOT_ERR_IO);
9133 free(logmsg);
9134 return err;
9138 * Lookup "logmsg" references of backed-out and cherrypicked commits
9139 * belonging to the current work tree. If found, and the worktree has
9140 * at least one modified file that was changed in the referenced commit,
9141 * add its log message to a new temporary file at *logmsg_path.
9142 * Add all refs found to matched_refs to be scheduled for removal on
9143 * successful commit.
9145 static const struct got_error *
9146 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9147 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9148 struct got_repository *repo)
9150 const struct got_error *err;
9151 struct got_commit_object *commit = NULL;
9152 struct got_object_id *id = NULL;
9153 struct got_reflist_head refs;
9154 struct got_reflist_entry *re, *re_match;
9155 FILE *f = NULL;
9156 char *uuidstr = NULL;
9157 int added_logmsg = 0;
9159 TAILQ_INIT(&refs);
9161 *logmsg_path = NULL;
9163 err = got_worktree_get_uuid(&uuidstr, worktree);
9164 if (err)
9165 goto done;
9167 err = got_ref_list(&refs, repo, "refs/got/worktree",
9168 got_ref_cmp_by_name, repo);
9169 if (err)
9170 goto done;
9172 TAILQ_FOREACH(re, &refs, entry) {
9173 const char *refname, *type;
9174 struct wt_commitable_path_arg wcpa;
9175 int add_logmsg = 0;
9177 refname = got_ref_get_name(re->ref);
9179 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9180 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9181 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9182 type = "cherrypicked";
9183 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9184 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9185 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9186 type = "backed-out";
9187 } else
9188 continue;
9190 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9191 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9192 else
9193 continue;
9195 err = got_repo_match_object_id(&id, NULL, refname,
9196 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9197 if (err)
9198 goto done;
9200 err = got_object_open_as_commit(&commit, repo, id);
9201 if (err)
9202 goto done;
9204 wcpa.commit_paths = paths;
9205 wcpa.has_changes = &add_logmsg;
9207 err = commit_path_changed_in_worktree(&wcpa, id,
9208 worktree, repo);
9209 if (err)
9210 goto done;
9212 if (add_logmsg) {
9213 if (f == NULL) {
9214 err = got_opentemp_named(logmsg_path, &f,
9215 "got-commit-logmsg", "");
9216 if (err)
9217 goto done;
9219 err = cat_logmsg(f, commit, refname, type,
9220 added_logmsg);
9221 if (err)
9222 goto done;
9223 if (!added_logmsg)
9224 ++added_logmsg;
9226 err = got_reflist_entry_dup(&re_match, re);
9227 if (err)
9228 goto done;
9229 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9232 got_object_commit_close(commit);
9233 commit = NULL;
9234 free(id);
9235 id = NULL;
9238 done:
9239 free(id);
9240 free(uuidstr);
9241 got_ref_list_free(&refs);
9242 if (commit)
9243 got_object_commit_close(commit);
9244 if (f && fclose(f) == EOF && err == NULL)
9245 err = got_error_from_errno("fclose");
9246 if (!added_logmsg) {
9247 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9248 err = got_error_from_errno2("unlink", *logmsg_path);
9249 *logmsg_path = NULL;
9251 return err;
9254 static const struct got_error *
9255 cmd_commit(int argc, char *argv[])
9257 const struct got_error *error = NULL;
9258 struct got_worktree *worktree = NULL;
9259 struct got_repository *repo = NULL;
9260 char *cwd = NULL, *id_str = NULL;
9261 struct got_object_id *id = NULL;
9262 const char *logmsg = NULL;
9263 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9264 struct collect_commit_logmsg_arg cl_arg;
9265 const char *author = NULL;
9266 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9267 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9268 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9269 int show_diff = 1, commit_conflicts = 0;
9270 struct got_pathlist_head paths;
9271 struct got_reflist_head refs;
9272 struct got_reflist_entry *re;
9273 int *pack_fds = NULL;
9275 TAILQ_INIT(&refs);
9276 TAILQ_INIT(&paths);
9277 cl_arg.logmsg_path = NULL;
9279 #ifndef PROFILE
9280 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9281 "unveil", NULL) == -1)
9282 err(1, "pledge");
9283 #endif
9285 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9286 switch (ch) {
9287 case 'A':
9288 author = optarg;
9289 error = valid_author(author);
9290 if (error)
9291 return error;
9292 break;
9293 case 'C':
9294 commit_conflicts = 1;
9295 break;
9296 case 'F':
9297 if (logmsg != NULL)
9298 option_conflict('F', 'm');
9299 prepared_logmsg = realpath(optarg, NULL);
9300 if (prepared_logmsg == NULL)
9301 return got_error_from_errno2("realpath",
9302 optarg);
9303 break;
9304 case 'm':
9305 if (prepared_logmsg)
9306 option_conflict('m', 'F');
9307 logmsg = optarg;
9308 break;
9309 case 'N':
9310 non_interactive = 1;
9311 break;
9312 case 'n':
9313 show_diff = 0;
9314 break;
9315 case 'S':
9316 allow_bad_symlinks = 1;
9317 break;
9318 default:
9319 usage_commit();
9320 /* NOTREACHED */
9324 argc -= optind;
9325 argv += optind;
9327 cwd = getcwd(NULL, 0);
9328 if (cwd == NULL) {
9329 error = got_error_from_errno("getcwd");
9330 goto done;
9333 error = got_repo_pack_fds_open(&pack_fds);
9334 if (error != NULL)
9335 goto done;
9337 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9338 if (error) {
9339 if (error->code == GOT_ERR_NOT_WORKTREE)
9340 error = wrap_not_worktree_error(error, "commit", cwd);
9341 goto done;
9344 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9345 if (error)
9346 goto done;
9347 if (rebase_in_progress) {
9348 error = got_error(GOT_ERR_REBASING);
9349 goto done;
9352 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9353 worktree);
9354 if (error)
9355 goto done;
9357 error = get_gitconfig_path(&gitconfig_path);
9358 if (error)
9359 goto done;
9360 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9361 gitconfig_path, pack_fds);
9362 if (error != NULL)
9363 goto done;
9365 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9366 if (error)
9367 goto done;
9368 if (merge_in_progress) {
9369 error = got_error(GOT_ERR_MERGE_BUSY);
9370 goto done;
9373 error = get_author(&committer, repo, worktree);
9374 if (error)
9375 goto done;
9377 if (author == NULL)
9378 author = committer;
9381 * unveil(2) traverses exec(2); if an editor is used we have
9382 * to apply unveil after the log message has been written.
9384 if (logmsg == NULL || strlen(logmsg) == 0)
9385 error = get_editor(&editor);
9386 else
9387 error = apply_unveil(got_repo_get_path(repo), 0,
9388 got_worktree_get_root_path(worktree));
9389 if (error)
9390 goto done;
9392 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9393 if (error)
9394 goto done;
9396 if (prepared_logmsg == NULL) {
9397 error = lookup_logmsg_ref(&merged_logmsg,
9398 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9399 if (error)
9400 goto done;
9403 cl_arg.editor = editor;
9404 cl_arg.cmdline_log = logmsg;
9405 cl_arg.prepared_log = prepared_logmsg;
9406 cl_arg.merged_log = merged_logmsg;
9407 cl_arg.non_interactive = non_interactive;
9408 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9409 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9410 if (!histedit_in_progress) {
9411 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9412 error = got_error(GOT_ERR_COMMIT_BRANCH);
9413 goto done;
9415 cl_arg.branch_name += 11;
9417 cl_arg.repo_path = got_repo_get_path(repo);
9418 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9419 allow_bad_symlinks, show_diff, commit_conflicts,
9420 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9421 if (error) {
9422 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9423 cl_arg.logmsg_path != NULL)
9424 preserve_logmsg = 1;
9425 goto done;
9428 error = got_object_id_str(&id_str, id);
9429 if (error)
9430 goto done;
9431 printf("Created commit %s\n", id_str);
9433 TAILQ_FOREACH(re, &refs, entry) {
9434 error = got_ref_delete(re->ref, repo);
9435 if (error)
9436 goto done;
9439 done:
9440 if (preserve_logmsg) {
9441 fprintf(stderr, "%s: log message preserved in %s\n",
9442 getprogname(), cl_arg.logmsg_path);
9443 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9444 error == NULL)
9445 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9446 free(cl_arg.logmsg_path);
9447 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9448 error = got_error_from_errno2("unlink", merged_logmsg);
9449 free(merged_logmsg);
9450 if (repo) {
9451 const struct got_error *close_err = got_repo_close(repo);
9452 if (error == NULL)
9453 error = close_err;
9455 if (worktree)
9456 got_worktree_close(worktree);
9457 if (pack_fds) {
9458 const struct got_error *pack_err =
9459 got_repo_pack_fds_close(pack_fds);
9460 if (error == NULL)
9461 error = pack_err;
9463 got_ref_list_free(&refs);
9464 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9465 free(cwd);
9466 free(id_str);
9467 free(gitconfig_path);
9468 free(editor);
9469 free(committer);
9470 free(prepared_logmsg);
9471 return error;
9474 __dead static void
9475 usage_send(void)
9477 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9478 "[-r repository-path] [-t tag] [remote-repository]\n",
9479 getprogname());
9480 exit(1);
9483 static void
9484 print_load_info(int print_colored, int print_found, int print_trees,
9485 int ncolored, int nfound, int ntrees)
9487 if (print_colored) {
9488 printf("%d commit%s colored", ncolored,
9489 ncolored == 1 ? "" : "s");
9491 if (print_found) {
9492 printf("%s%d object%s found",
9493 ncolored > 0 ? "; " : "",
9494 nfound, nfound == 1 ? "" : "s");
9496 if (print_trees) {
9497 printf("; %d tree%s scanned", ntrees,
9498 ntrees == 1 ? "" : "s");
9502 struct got_send_progress_arg {
9503 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9504 int verbosity;
9505 int last_ncolored;
9506 int last_nfound;
9507 int last_ntrees;
9508 int loading_done;
9509 int last_ncommits;
9510 int last_nobj_total;
9511 int last_p_deltify;
9512 int last_p_written;
9513 int last_p_sent;
9514 int printed_something;
9515 int sent_something;
9516 struct got_pathlist_head *delete_branches;
9519 static const struct got_error *
9520 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9521 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9522 int nobj_written, off_t bytes_sent, const char *refname,
9523 const char *errmsg, int success)
9525 struct got_send_progress_arg *a = arg;
9526 char scaled_packsize[FMT_SCALED_STRSIZE];
9527 char scaled_sent[FMT_SCALED_STRSIZE];
9528 int p_deltify = 0, p_written = 0, p_sent = 0;
9529 int print_colored = 0, print_found = 0, print_trees = 0;
9530 int print_searching = 0, print_total = 0;
9531 int print_deltify = 0, print_written = 0, print_sent = 0;
9533 if (a->verbosity < 0)
9534 return NULL;
9536 if (refname) {
9537 const char *status = success ? "accepted" : "rejected";
9539 if (success) {
9540 struct got_pathlist_entry *pe;
9541 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9542 const char *branchname = pe->path;
9543 if (got_path_cmp(branchname, refname,
9544 strlen(branchname), strlen(refname)) == 0) {
9545 status = "deleted";
9546 a->sent_something = 1;
9547 break;
9552 if (a->printed_something)
9553 putchar('\n');
9554 printf("Server has %s %s", status, refname);
9555 if (errmsg)
9556 printf(": %s", errmsg);
9557 a->printed_something = 1;
9558 return NULL;
9561 if (a->last_ncolored != ncolored) {
9562 print_colored = 1;
9563 a->last_ncolored = ncolored;
9566 if (a->last_nfound != nfound) {
9567 print_colored = 1;
9568 print_found = 1;
9569 a->last_nfound = nfound;
9572 if (a->last_ntrees != ntrees) {
9573 print_colored = 1;
9574 print_found = 1;
9575 print_trees = 1;
9576 a->last_ntrees = ntrees;
9579 if ((print_colored || print_found || print_trees) &&
9580 !a->loading_done) {
9581 printf("\r");
9582 print_load_info(print_colored, print_found, print_trees,
9583 ncolored, nfound, ntrees);
9584 a->printed_something = 1;
9585 fflush(stdout);
9586 return NULL;
9587 } else if (!a->loading_done) {
9588 printf("\r");
9589 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9590 printf("\n");
9591 a->loading_done = 1;
9594 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9595 return got_error_from_errno("fmt_scaled");
9596 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9597 return got_error_from_errno("fmt_scaled");
9599 if (a->last_ncommits != ncommits) {
9600 print_searching = 1;
9601 a->last_ncommits = ncommits;
9604 if (a->last_nobj_total != nobj_total) {
9605 print_searching = 1;
9606 print_total = 1;
9607 a->last_nobj_total = nobj_total;
9610 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9611 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9612 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9613 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9614 return got_error(GOT_ERR_NO_SPACE);
9617 if (nobj_deltify > 0 || nobj_written > 0) {
9618 if (nobj_deltify > 0) {
9619 p_deltify = (nobj_deltify * 100) / nobj_total;
9620 if (p_deltify != a->last_p_deltify) {
9621 a->last_p_deltify = p_deltify;
9622 print_searching = 1;
9623 print_total = 1;
9624 print_deltify = 1;
9627 if (nobj_written > 0) {
9628 p_written = (nobj_written * 100) / nobj_total;
9629 if (p_written != a->last_p_written) {
9630 a->last_p_written = p_written;
9631 print_searching = 1;
9632 print_total = 1;
9633 print_deltify = 1;
9634 print_written = 1;
9639 if (bytes_sent > 0) {
9640 p_sent = (bytes_sent * 100) / packfile_size;
9641 if (p_sent != a->last_p_sent) {
9642 a->last_p_sent = p_sent;
9643 print_searching = 1;
9644 print_total = 1;
9645 print_deltify = 1;
9646 print_written = 1;
9647 print_sent = 1;
9649 a->sent_something = 1;
9652 if (print_searching || print_total || print_deltify || print_written ||
9653 print_sent)
9654 printf("\r");
9655 if (print_searching)
9656 printf("packing %d reference%s", ncommits,
9657 ncommits == 1 ? "" : "s");
9658 if (print_total)
9659 printf("; %d object%s", nobj_total,
9660 nobj_total == 1 ? "" : "s");
9661 if (print_deltify)
9662 printf("; deltify: %d%%", p_deltify);
9663 if (print_sent)
9664 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9665 scaled_packsize, p_sent);
9666 else if (print_written)
9667 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9668 scaled_packsize, p_written);
9669 if (print_searching || print_total || print_deltify ||
9670 print_written || print_sent) {
9671 a->printed_something = 1;
9672 fflush(stdout);
9674 return NULL;
9677 static const struct got_error *
9678 cmd_send(int argc, char *argv[])
9680 const struct got_error *error = NULL;
9681 char *cwd = NULL, *repo_path = NULL;
9682 const char *remote_name;
9683 char *proto = NULL, *host = NULL, *port = NULL;
9684 char *repo_name = NULL, *server_path = NULL;
9685 const struct got_remote_repo *remotes, *remote = NULL;
9686 int nremotes, nbranches = 0, ndelete_branches = 0;
9687 struct got_repository *repo = NULL;
9688 struct got_worktree *worktree = NULL;
9689 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9690 struct got_pathlist_head branches;
9691 struct got_pathlist_head tags;
9692 struct got_reflist_head all_branches;
9693 struct got_reflist_head all_tags;
9694 struct got_pathlist_head delete_args;
9695 struct got_pathlist_head delete_branches;
9696 struct got_reflist_entry *re;
9697 struct got_pathlist_entry *pe;
9698 int i, ch, sendfd = -1, sendstatus;
9699 pid_t sendpid = -1;
9700 struct got_send_progress_arg spa;
9701 int verbosity = 0, overwrite_refs = 0;
9702 int send_all_branches = 0, send_all_tags = 0;
9703 struct got_reference *ref = NULL;
9704 int *pack_fds = NULL;
9706 TAILQ_INIT(&branches);
9707 TAILQ_INIT(&tags);
9708 TAILQ_INIT(&all_branches);
9709 TAILQ_INIT(&all_tags);
9710 TAILQ_INIT(&delete_args);
9711 TAILQ_INIT(&delete_branches);
9713 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9714 switch (ch) {
9715 case 'a':
9716 send_all_branches = 1;
9717 break;
9718 case 'b':
9719 error = got_pathlist_append(&branches, optarg, NULL);
9720 if (error)
9721 return error;
9722 nbranches++;
9723 break;
9724 case 'd':
9725 error = got_pathlist_append(&delete_args, optarg, NULL);
9726 if (error)
9727 return error;
9728 break;
9729 case 'f':
9730 overwrite_refs = 1;
9731 break;
9732 case 'q':
9733 verbosity = -1;
9734 break;
9735 case 'r':
9736 repo_path = realpath(optarg, NULL);
9737 if (repo_path == NULL)
9738 return got_error_from_errno2("realpath",
9739 optarg);
9740 got_path_strip_trailing_slashes(repo_path);
9741 break;
9742 case 'T':
9743 send_all_tags = 1;
9744 break;
9745 case 't':
9746 error = got_pathlist_append(&tags, optarg, NULL);
9747 if (error)
9748 return error;
9749 break;
9750 case 'v':
9751 if (verbosity < 0)
9752 verbosity = 0;
9753 else if (verbosity < 3)
9754 verbosity++;
9755 break;
9756 default:
9757 usage_send();
9758 /* NOTREACHED */
9761 argc -= optind;
9762 argv += optind;
9764 if (send_all_branches && !TAILQ_EMPTY(&branches))
9765 option_conflict('a', 'b');
9766 if (send_all_tags && !TAILQ_EMPTY(&tags))
9767 option_conflict('T', 't');
9770 if (argc == 0)
9771 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9772 else if (argc == 1)
9773 remote_name = argv[0];
9774 else
9775 usage_send();
9777 cwd = getcwd(NULL, 0);
9778 if (cwd == NULL) {
9779 error = got_error_from_errno("getcwd");
9780 goto done;
9783 error = got_repo_pack_fds_open(&pack_fds);
9784 if (error != NULL)
9785 goto done;
9787 if (repo_path == NULL) {
9788 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9789 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9790 goto done;
9791 else
9792 error = NULL;
9793 if (worktree) {
9794 repo_path =
9795 strdup(got_worktree_get_repo_path(worktree));
9796 if (repo_path == NULL)
9797 error = got_error_from_errno("strdup");
9798 if (error)
9799 goto done;
9800 } else {
9801 repo_path = strdup(cwd);
9802 if (repo_path == NULL) {
9803 error = got_error_from_errno("strdup");
9804 goto done;
9809 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9810 if (error)
9811 goto done;
9813 if (worktree) {
9814 worktree_conf = got_worktree_get_gotconfig(worktree);
9815 if (worktree_conf) {
9816 got_gotconfig_get_remotes(&nremotes, &remotes,
9817 worktree_conf);
9818 for (i = 0; i < nremotes; i++) {
9819 if (strcmp(remotes[i].name, remote_name) == 0) {
9820 remote = &remotes[i];
9821 break;
9826 if (remote == NULL) {
9827 repo_conf = got_repo_get_gotconfig(repo);
9828 if (repo_conf) {
9829 got_gotconfig_get_remotes(&nremotes, &remotes,
9830 repo_conf);
9831 for (i = 0; i < nremotes; i++) {
9832 if (strcmp(remotes[i].name, remote_name) == 0) {
9833 remote = &remotes[i];
9834 break;
9839 if (remote == NULL) {
9840 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9841 for (i = 0; i < nremotes; i++) {
9842 if (strcmp(remotes[i].name, remote_name) == 0) {
9843 remote = &remotes[i];
9844 break;
9848 if (remote == NULL) {
9849 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9850 goto done;
9853 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9854 &repo_name, remote->send_url);
9855 if (error)
9856 goto done;
9858 if (strcmp(proto, "git") == 0) {
9859 #ifndef PROFILE
9860 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9861 "sendfd dns inet unveil", NULL) == -1)
9862 err(1, "pledge");
9863 #endif
9864 } else if (strcmp(proto, "git+ssh") == 0 ||
9865 strcmp(proto, "ssh") == 0) {
9866 #ifndef PROFILE
9867 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9868 "sendfd unveil", NULL) == -1)
9869 err(1, "pledge");
9870 #endif
9871 } else if (strcmp(proto, "http") == 0 ||
9872 strcmp(proto, "git+http") == 0) {
9873 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9874 goto done;
9875 } else {
9876 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9877 goto done;
9880 error = got_dial_apply_unveil(proto);
9881 if (error)
9882 goto done;
9884 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9885 if (error)
9886 goto done;
9888 if (send_all_branches) {
9889 error = got_ref_list(&all_branches, repo, "refs/heads",
9890 got_ref_cmp_by_name, NULL);
9891 if (error)
9892 goto done;
9893 TAILQ_FOREACH(re, &all_branches, entry) {
9894 const char *branchname = got_ref_get_name(re->ref);
9895 error = got_pathlist_append(&branches,
9896 branchname, NULL);
9897 if (error)
9898 goto done;
9899 nbranches++;
9901 } else if (nbranches == 0) {
9902 for (i = 0; i < remote->nsend_branches; i++) {
9903 error = got_pathlist_append(&branches,
9904 remote->send_branches[i], NULL);
9905 if (error)
9906 goto done;
9910 if (send_all_tags) {
9911 error = got_ref_list(&all_tags, repo, "refs/tags",
9912 got_ref_cmp_by_name, NULL);
9913 if (error)
9914 goto done;
9915 TAILQ_FOREACH(re, &all_tags, entry) {
9916 const char *tagname = got_ref_get_name(re->ref);
9917 error = got_pathlist_append(&tags,
9918 tagname, NULL);
9919 if (error)
9920 goto done;
9925 * To prevent accidents only branches in refs/heads/ can be deleted
9926 * with 'got send -d'.
9927 * Deleting anything else requires local repository access or Git.
9929 TAILQ_FOREACH(pe, &delete_args, entry) {
9930 const char *branchname = pe->path;
9931 char *s;
9932 struct got_pathlist_entry *new;
9933 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9934 s = strdup(branchname);
9935 if (s == NULL) {
9936 error = got_error_from_errno("strdup");
9937 goto done;
9939 } else {
9940 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9941 error = got_error_from_errno("asprintf");
9942 goto done;
9945 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9946 if (error || new == NULL /* duplicate */)
9947 free(s);
9948 if (error)
9949 goto done;
9950 ndelete_branches++;
9953 if (nbranches == 0 && ndelete_branches == 0) {
9954 struct got_reference *head_ref;
9955 if (worktree)
9956 error = got_ref_open(&head_ref, repo,
9957 got_worktree_get_head_ref_name(worktree), 0);
9958 else
9959 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9960 if (error)
9961 goto done;
9962 if (got_ref_is_symbolic(head_ref)) {
9963 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9964 got_ref_close(head_ref);
9965 if (error)
9966 goto done;
9967 } else
9968 ref = head_ref;
9969 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9970 NULL);
9971 if (error)
9972 goto done;
9973 nbranches++;
9976 if (verbosity >= 0) {
9977 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9978 remote->name, proto, host,
9979 port ? ":" : "", port ? port : "",
9980 *server_path == '/' ? "" : "/", server_path);
9983 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9984 server_path, verbosity);
9985 if (error)
9986 goto done;
9988 memset(&spa, 0, sizeof(spa));
9989 spa.last_scaled_packsize[0] = '\0';
9990 spa.last_p_deltify = -1;
9991 spa.last_p_written = -1;
9992 spa.verbosity = verbosity;
9993 spa.delete_branches = &delete_branches;
9994 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9995 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9996 check_cancelled, NULL);
9997 if (spa.printed_something)
9998 putchar('\n');
9999 if (error)
10000 goto done;
10001 if (!spa.sent_something && verbosity >= 0)
10002 printf("Already up-to-date\n");
10003 done:
10004 if (sendpid > 0) {
10005 if (kill(sendpid, SIGTERM) == -1)
10006 error = got_error_from_errno("kill");
10007 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10008 error = got_error_from_errno("waitpid");
10010 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10011 error = got_error_from_errno("close");
10012 if (repo) {
10013 const struct got_error *close_err = got_repo_close(repo);
10014 if (error == NULL)
10015 error = close_err;
10017 if (worktree)
10018 got_worktree_close(worktree);
10019 if (pack_fds) {
10020 const struct got_error *pack_err =
10021 got_repo_pack_fds_close(pack_fds);
10022 if (error == NULL)
10023 error = pack_err;
10025 if (ref)
10026 got_ref_close(ref);
10027 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10028 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10029 got_ref_list_free(&all_branches);
10030 got_ref_list_free(&all_tags);
10031 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10032 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10033 free(cwd);
10034 free(repo_path);
10035 free(proto);
10036 free(host);
10037 free(port);
10038 free(server_path);
10039 free(repo_name);
10040 return error;
10044 * Print and if delete is set delete all ref_prefix references.
10045 * If wanted_ref is not NULL, only print or delete this reference.
10047 static const struct got_error *
10048 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10049 const char *wanted_ref, int delete, struct got_worktree *worktree,
10050 struct got_repository *repo)
10052 const struct got_error *err;
10053 struct got_pathlist_head paths;
10054 struct got_reflist_head refs;
10055 struct got_reflist_entry *re;
10056 struct got_reflist_object_id_map *refs_idmap = NULL;
10057 struct got_commit_object *commit = NULL;
10058 struct got_object_id *id = NULL;
10059 const char *header_prefix;
10060 char *uuidstr = NULL;
10061 int found = 0;
10063 TAILQ_INIT(&refs);
10064 TAILQ_INIT(&paths);
10066 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10067 if (err)
10068 goto done;
10070 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10071 if (err)
10072 goto done;
10074 if (worktree != NULL) {
10075 err = got_worktree_get_uuid(&uuidstr, worktree);
10076 if (err)
10077 goto done;
10080 if (wanted_ref) {
10081 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10082 wanted_ref += 11;
10085 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10086 header_prefix = "backout";
10087 else
10088 header_prefix = "cherrypick";
10090 TAILQ_FOREACH(re, &refs, entry) {
10091 const char *refname, *wt;
10093 refname = got_ref_get_name(re->ref);
10095 err = check_cancelled(NULL);
10096 if (err)
10097 goto done;
10099 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10100 refname += prefix_len + 1; /* skip '-' delimiter */
10101 else
10102 continue;
10104 wt = refname;
10106 if (worktree == NULL || strncmp(refname, uuidstr,
10107 GOT_WORKTREE_UUID_STRLEN) == 0)
10108 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10109 else
10110 continue;
10112 err = got_repo_match_object_id(&id, NULL, refname,
10113 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10114 if (err)
10115 goto done;
10117 err = got_object_open_as_commit(&commit, repo, id);
10118 if (err)
10119 goto done;
10121 if (wanted_ref)
10122 found = strncmp(wanted_ref, refname,
10123 strlen(wanted_ref)) == 0;
10124 if (wanted_ref && !found) {
10125 struct got_reflist_head *ci_refs;
10127 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10128 id);
10130 if (ci_refs) {
10131 char *refs_str = NULL;
10132 char const *r = NULL;
10134 err = build_refs_str(&refs_str, ci_refs, id,
10135 repo, 1);
10136 if (err)
10137 goto done;
10139 r = refs_str;
10140 while (r) {
10141 if (strncmp(r, wanted_ref,
10142 strlen(wanted_ref)) == 0) {
10143 found = 1;
10144 break;
10146 r = strchr(r, ' ');
10147 if (r)
10148 ++r;
10150 free(refs_str);
10154 if (wanted_ref == NULL || found) {
10155 if (delete) {
10156 err = got_ref_delete(re->ref, repo);
10157 if (err)
10158 goto done;
10159 printf("Deleted: ");
10160 err = print_commit_oneline(commit, id, repo,
10161 refs_idmap);
10162 } else {
10164 * Print paths modified by commit to help
10165 * associate commits with worktree changes.
10167 err = get_changed_paths(&paths, commit,
10168 repo, NULL);
10169 if (err)
10170 goto done;
10172 err = print_commit(commit, id, repo, NULL,
10173 &paths, NULL, 0, 0, refs_idmap, NULL,
10174 header_prefix);
10175 got_pathlist_free(&paths,
10176 GOT_PATHLIST_FREE_ALL);
10178 if (worktree == NULL)
10179 printf("work tree: %.*s\n\n",
10180 GOT_WORKTREE_UUID_STRLEN, wt);
10182 if (err || found)
10183 goto done;
10186 got_object_commit_close(commit);
10187 commit = NULL;
10188 free(id);
10189 id = NULL;
10192 if (wanted_ref != NULL && !found)
10193 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10195 done:
10196 free(id);
10197 free(uuidstr);
10198 got_ref_list_free(&refs);
10199 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10200 if (refs_idmap)
10201 got_reflist_object_id_map_free(refs_idmap);
10202 if (commit)
10203 got_object_commit_close(commit);
10204 return err;
10208 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10209 * identified by id for log messages to prepopulate the editor on commit.
10211 static const struct got_error *
10212 logmsg_ref(struct got_object_id *id, const char *prefix,
10213 struct got_worktree *worktree, struct got_repository *repo)
10215 const struct got_error *err = NULL;
10216 char *idstr, *ref = NULL, *refname = NULL;
10217 int histedit_in_progress;
10218 int rebase_in_progress, merge_in_progress;
10221 * Silenty refuse to create merge reference if any histedit, merge,
10222 * or rebase operation is in progress.
10224 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10225 worktree);
10226 if (err)
10227 return err;
10228 if (histedit_in_progress)
10229 return NULL;
10231 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10232 if (err)
10233 return err;
10234 if (rebase_in_progress)
10235 return NULL;
10237 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10238 repo);
10239 if (err)
10240 return err;
10241 if (merge_in_progress)
10242 return NULL;
10244 err = got_object_id_str(&idstr, id);
10245 if (err)
10246 return err;
10248 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10249 if (err)
10250 goto done;
10252 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10253 err = got_error_from_errno("asprintf");
10254 goto done;
10257 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10258 -1, repo);
10259 done:
10260 free(ref);
10261 free(idstr);
10262 free(refname);
10263 return err;
10266 __dead static void
10267 usage_cherrypick(void)
10269 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10270 getprogname());
10271 exit(1);
10274 static const struct got_error *
10275 cmd_cherrypick(int argc, char *argv[])
10277 const struct got_error *error = NULL;
10278 struct got_worktree *worktree = NULL;
10279 struct got_repository *repo = NULL;
10280 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10281 struct got_object_id *commit_id = NULL;
10282 struct got_commit_object *commit = NULL;
10283 struct got_object_qid *pid;
10284 int ch, list_refs = 0, remove_refs = 0;
10285 struct got_update_progress_arg upa;
10286 int *pack_fds = NULL;
10288 #ifndef PROFILE
10289 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10290 "unveil", NULL) == -1)
10291 err(1, "pledge");
10292 #endif
10294 while ((ch = getopt(argc, argv, "lX")) != -1) {
10295 switch (ch) {
10296 case 'l':
10297 list_refs = 1;
10298 break;
10299 case 'X':
10300 remove_refs = 1;
10301 break;
10302 default:
10303 usage_cherrypick();
10304 /* NOTREACHED */
10308 argc -= optind;
10309 argv += optind;
10311 if (list_refs || remove_refs) {
10312 if (argc != 0 && argc != 1)
10313 usage_cherrypick();
10314 } else if (argc != 1)
10315 usage_cherrypick();
10316 if (list_refs && remove_refs)
10317 option_conflict('l', 'X');
10319 cwd = getcwd(NULL, 0);
10320 if (cwd == NULL) {
10321 error = got_error_from_errno("getcwd");
10322 goto done;
10325 error = got_repo_pack_fds_open(&pack_fds);
10326 if (error != NULL)
10327 goto done;
10329 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10330 if (error) {
10331 if (list_refs || remove_refs) {
10332 if (error->code != GOT_ERR_NOT_WORKTREE)
10333 goto done;
10334 } else {
10335 if (error->code == GOT_ERR_NOT_WORKTREE)
10336 error = wrap_not_worktree_error(error,
10337 "cherrypick", cwd);
10338 goto done;
10342 error = got_repo_open(&repo,
10343 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10344 NULL, pack_fds);
10345 if (error != NULL)
10346 goto done;
10348 error = apply_unveil(got_repo_get_path(repo), 0,
10349 worktree ? got_worktree_get_root_path(worktree) : NULL);
10350 if (error)
10351 goto done;
10353 if (list_refs || remove_refs) {
10354 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10355 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10356 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10357 goto done;
10360 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10361 if (error != NULL)
10362 goto done;
10364 error = got_repo_match_object_id(&commit_id, NULL,
10365 keyword_idstr != NULL ? keyword_idstr : argv[0],
10366 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10367 if (error)
10368 goto done;
10369 error = got_object_id_str(&commit_id_str, commit_id);
10370 if (error)
10371 goto done;
10373 error = got_object_open_as_commit(&commit, repo, commit_id);
10374 if (error)
10375 goto done;
10376 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10377 memset(&upa, 0, sizeof(upa));
10378 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10379 commit_id, repo, update_progress, &upa, check_cancelled,
10380 NULL);
10381 if (error != NULL)
10382 goto done;
10384 if (upa.did_something) {
10385 error = logmsg_ref(commit_id,
10386 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10387 if (error)
10388 goto done;
10389 printf("Merged commit %s\n", commit_id_str);
10391 print_merge_progress_stats(&upa);
10392 done:
10393 free(cwd);
10394 free(keyword_idstr);
10395 if (commit)
10396 got_object_commit_close(commit);
10397 free(commit_id_str);
10398 if (worktree)
10399 got_worktree_close(worktree);
10400 if (repo) {
10401 const struct got_error *close_err = got_repo_close(repo);
10402 if (error == NULL)
10403 error = close_err;
10405 if (pack_fds) {
10406 const struct got_error *pack_err =
10407 got_repo_pack_fds_close(pack_fds);
10408 if (error == NULL)
10409 error = pack_err;
10412 return error;
10415 __dead static void
10416 usage_backout(void)
10418 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10419 exit(1);
10422 static const struct got_error *
10423 cmd_backout(int argc, char *argv[])
10425 const struct got_error *error = NULL;
10426 struct got_worktree *worktree = NULL;
10427 struct got_repository *repo = NULL;
10428 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10429 struct got_object_id *commit_id = NULL;
10430 struct got_commit_object *commit = NULL;
10431 struct got_object_qid *pid;
10432 int ch, list_refs = 0, remove_refs = 0;
10433 struct got_update_progress_arg upa;
10434 int *pack_fds = NULL;
10436 #ifndef PROFILE
10437 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10438 "unveil", NULL) == -1)
10439 err(1, "pledge");
10440 #endif
10442 while ((ch = getopt(argc, argv, "lX")) != -1) {
10443 switch (ch) {
10444 case 'l':
10445 list_refs = 1;
10446 break;
10447 case 'X':
10448 remove_refs = 1;
10449 break;
10450 default:
10451 usage_backout();
10452 /* NOTREACHED */
10456 argc -= optind;
10457 argv += optind;
10459 if (list_refs || remove_refs) {
10460 if (argc != 0 && argc != 1)
10461 usage_backout();
10462 } else if (argc != 1)
10463 usage_backout();
10464 if (list_refs && remove_refs)
10465 option_conflict('l', 'X');
10467 cwd = getcwd(NULL, 0);
10468 if (cwd == NULL) {
10469 error = got_error_from_errno("getcwd");
10470 goto done;
10473 error = got_repo_pack_fds_open(&pack_fds);
10474 if (error != NULL)
10475 goto done;
10477 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10478 if (error) {
10479 if (list_refs || remove_refs) {
10480 if (error->code != GOT_ERR_NOT_WORKTREE)
10481 goto done;
10482 } else {
10483 if (error->code == GOT_ERR_NOT_WORKTREE)
10484 error = wrap_not_worktree_error(error,
10485 "backout", cwd);
10486 goto done;
10490 error = got_repo_open(&repo,
10491 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10492 NULL, pack_fds);
10493 if (error != NULL)
10494 goto done;
10496 error = apply_unveil(got_repo_get_path(repo), 0,
10497 worktree ? got_worktree_get_root_path(worktree) : NULL);
10498 if (error)
10499 goto done;
10501 if (list_refs || remove_refs) {
10502 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10503 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10504 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10505 goto done;
10508 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10509 if (error != NULL)
10510 goto done;
10512 error = got_repo_match_object_id(&commit_id, NULL,
10513 keyword_idstr != NULL ? keyword_idstr : argv[0],
10514 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10515 if (error)
10516 goto done;
10517 error = got_object_id_str(&commit_id_str, commit_id);
10518 if (error)
10519 goto done;
10521 error = got_object_open_as_commit(&commit, repo, commit_id);
10522 if (error)
10523 goto done;
10524 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10525 if (pid == NULL) {
10526 error = got_error(GOT_ERR_ROOT_COMMIT);
10527 goto done;
10530 memset(&upa, 0, sizeof(upa));
10531 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10532 repo, update_progress, &upa, check_cancelled, NULL);
10533 if (error != NULL)
10534 goto done;
10536 if (upa.did_something) {
10537 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10538 worktree, repo);
10539 if (error)
10540 goto done;
10541 printf("Backed out commit %s\n", commit_id_str);
10543 print_merge_progress_stats(&upa);
10544 done:
10545 free(cwd);
10546 free(keyword_idstr);
10547 if (commit)
10548 got_object_commit_close(commit);
10549 free(commit_id_str);
10550 if (worktree)
10551 got_worktree_close(worktree);
10552 if (repo) {
10553 const struct got_error *close_err = got_repo_close(repo);
10554 if (error == NULL)
10555 error = close_err;
10557 if (pack_fds) {
10558 const struct got_error *pack_err =
10559 got_repo_pack_fds_close(pack_fds);
10560 if (error == NULL)
10561 error = pack_err;
10563 return error;
10566 __dead static void
10567 usage_rebase(void)
10569 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10570 exit(1);
10573 static void
10574 trim_logmsg(char *logmsg, int limit)
10576 char *nl;
10577 size_t len;
10579 len = strlen(logmsg);
10580 if (len > limit)
10581 len = limit;
10582 logmsg[len] = '\0';
10583 nl = strchr(logmsg, '\n');
10584 if (nl)
10585 *nl = '\0';
10588 static const struct got_error *
10589 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10591 const struct got_error *err;
10592 char *logmsg0 = NULL;
10593 const char *s;
10595 err = got_object_commit_get_logmsg(&logmsg0, commit);
10596 if (err)
10597 return err;
10599 s = logmsg0;
10600 while (isspace((unsigned char)s[0]))
10601 s++;
10603 *logmsg = strdup(s);
10604 if (*logmsg == NULL) {
10605 err = got_error_from_errno("strdup");
10606 goto done;
10609 trim_logmsg(*logmsg, limit);
10610 done:
10611 free(logmsg0);
10612 return err;
10615 static const struct got_error *
10616 show_rebase_merge_conflict(struct got_object_id *id,
10617 struct got_repository *repo)
10619 const struct got_error *err;
10620 struct got_commit_object *commit = NULL;
10621 char *id_str = NULL, *logmsg = NULL;
10623 err = got_object_open_as_commit(&commit, repo, id);
10624 if (err)
10625 return err;
10627 err = got_object_id_str(&id_str, id);
10628 if (err)
10629 goto done;
10631 id_str[12] = '\0';
10633 err = get_short_logmsg(&logmsg, 42, commit);
10634 if (err)
10635 goto done;
10637 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10638 done:
10639 free(id_str);
10640 got_object_commit_close(commit);
10641 free(logmsg);
10642 return err;
10645 static const struct got_error *
10646 show_rebase_progress(struct got_commit_object *commit,
10647 struct got_object_id *old_id, struct got_object_id *new_id)
10649 const struct got_error *err;
10650 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10652 err = got_object_id_str(&old_id_str, old_id);
10653 if (err)
10654 goto done;
10656 if (new_id) {
10657 err = got_object_id_str(&new_id_str, new_id);
10658 if (err)
10659 goto done;
10662 old_id_str[12] = '\0';
10663 if (new_id_str)
10664 new_id_str[12] = '\0';
10666 err = get_short_logmsg(&logmsg, 42, commit);
10667 if (err)
10668 goto done;
10670 printf("%s -> %s: %s\n", old_id_str,
10671 new_id_str ? new_id_str : "no-op change", logmsg);
10672 done:
10673 free(old_id_str);
10674 free(new_id_str);
10675 free(logmsg);
10676 return err;
10679 static const struct got_error *
10680 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10681 struct got_reference *branch, struct got_reference *tmp_branch,
10682 struct got_repository *repo, int create_backup)
10684 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10685 return got_worktree_rebase_complete(worktree, fileindex,
10686 tmp_branch, branch, repo, create_backup);
10689 static const struct got_error *
10690 rebase_commit(struct got_pathlist_head *merged_paths,
10691 struct got_worktree *worktree, struct got_fileindex *fileindex,
10692 struct got_reference *tmp_branch, const char *committer,
10693 struct got_object_id *commit_id, int allow_conflict,
10694 struct got_repository *repo)
10696 const struct got_error *error;
10697 struct got_commit_object *commit;
10698 struct got_object_id *new_commit_id;
10700 error = got_object_open_as_commit(&commit, repo, commit_id);
10701 if (error)
10702 return error;
10704 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10705 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10706 allow_conflict, repo);
10707 if (error) {
10708 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10709 goto done;
10710 error = show_rebase_progress(commit, commit_id, NULL);
10711 } else {
10712 error = show_rebase_progress(commit, commit_id, new_commit_id);
10713 free(new_commit_id);
10715 done:
10716 got_object_commit_close(commit);
10717 return error;
10720 struct check_path_prefix_arg {
10721 const char *path_prefix;
10722 size_t len;
10723 int errcode;
10726 static const struct got_error *
10727 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10728 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10729 struct got_object_id *id1, struct got_object_id *id2,
10730 const char *path1, const char *path2,
10731 mode_t mode1, mode_t mode2, struct got_repository *repo)
10733 struct check_path_prefix_arg *a = arg;
10735 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10736 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10737 return got_error(a->errcode);
10739 return NULL;
10742 static const struct got_error *
10743 check_path_prefix(struct got_object_id *parent_id,
10744 struct got_object_id *commit_id, const char *path_prefix,
10745 int errcode, struct got_repository *repo)
10747 const struct got_error *err;
10748 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10749 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10750 struct check_path_prefix_arg cpp_arg;
10752 if (got_path_is_root_dir(path_prefix))
10753 return NULL;
10755 err = got_object_open_as_commit(&commit, repo, commit_id);
10756 if (err)
10757 goto done;
10759 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10760 if (err)
10761 goto done;
10763 err = got_object_open_as_tree(&tree1, repo,
10764 got_object_commit_get_tree_id(parent_commit));
10765 if (err)
10766 goto done;
10768 err = got_object_open_as_tree(&tree2, repo,
10769 got_object_commit_get_tree_id(commit));
10770 if (err)
10771 goto done;
10773 cpp_arg.path_prefix = path_prefix;
10774 while (cpp_arg.path_prefix[0] == '/')
10775 cpp_arg.path_prefix++;
10776 cpp_arg.len = strlen(cpp_arg.path_prefix);
10777 cpp_arg.errcode = errcode;
10778 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10779 check_path_prefix_in_diff, &cpp_arg, 0);
10780 done:
10781 if (tree1)
10782 got_object_tree_close(tree1);
10783 if (tree2)
10784 got_object_tree_close(tree2);
10785 if (commit)
10786 got_object_commit_close(commit);
10787 if (parent_commit)
10788 got_object_commit_close(parent_commit);
10789 return err;
10792 static const struct got_error *
10793 collect_commits(struct got_object_id_queue *commits,
10794 struct got_object_id *initial_commit_id,
10795 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10796 const char *path_prefix, int path_prefix_errcode,
10797 struct got_repository *repo)
10799 const struct got_error *err = NULL;
10800 struct got_commit_graph *graph = NULL;
10801 struct got_object_id parent_id, commit_id;
10802 struct got_object_qid *qid;
10804 err = got_commit_graph_open(&graph, "/", 1);
10805 if (err)
10806 return err;
10808 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10809 check_cancelled, NULL);
10810 if (err)
10811 goto done;
10813 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10814 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10815 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10816 check_cancelled, NULL);
10817 if (err) {
10818 if (err->code == GOT_ERR_ITER_COMPLETED) {
10819 err = got_error_msg(GOT_ERR_ANCESTRY,
10820 "ran out of commits to rebase before "
10821 "youngest common ancestor commit has "
10822 "been reached?!?");
10824 goto done;
10825 } else {
10826 err = check_path_prefix(&parent_id, &commit_id,
10827 path_prefix, path_prefix_errcode, repo);
10828 if (err)
10829 goto done;
10831 err = got_object_qid_alloc(&qid, &commit_id);
10832 if (err)
10833 goto done;
10834 STAILQ_INSERT_HEAD(commits, qid, entry);
10836 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10839 done:
10840 got_commit_graph_close(graph);
10841 return err;
10844 static const struct got_error *
10845 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10847 const struct got_error *err = NULL;
10848 time_t committer_time;
10849 struct tm tm;
10850 char datebuf[11]; /* YYYY-MM-DD + NUL */
10851 char *author0 = NULL, *author, *smallerthan;
10852 char *logmsg0 = NULL, *logmsg, *newline;
10854 committer_time = got_object_commit_get_committer_time(commit);
10855 if (gmtime_r(&committer_time, &tm) == NULL)
10856 return got_error_from_errno("gmtime_r");
10857 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10858 return got_error(GOT_ERR_NO_SPACE);
10860 author0 = strdup(got_object_commit_get_author(commit));
10861 if (author0 == NULL)
10862 return got_error_from_errno("strdup");
10863 author = author0;
10864 smallerthan = strchr(author, '<');
10865 if (smallerthan && smallerthan[1] != '\0')
10866 author = smallerthan + 1;
10867 author[strcspn(author, "@>")] = '\0';
10869 err = got_object_commit_get_logmsg(&logmsg0, commit);
10870 if (err)
10871 goto done;
10872 logmsg = logmsg0;
10873 while (*logmsg == '\n')
10874 logmsg++;
10875 newline = strchr(logmsg, '\n');
10876 if (newline)
10877 *newline = '\0';
10879 if (asprintf(brief_str, "%s %s %s",
10880 datebuf, author, logmsg) == -1)
10881 err = got_error_from_errno("asprintf");
10882 done:
10883 free(author0);
10884 free(logmsg0);
10885 return err;
10888 static const struct got_error *
10889 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10890 struct got_repository *repo)
10892 const struct got_error *err;
10893 char *id_str;
10895 err = got_object_id_str(&id_str, id);
10896 if (err)
10897 return err;
10899 err = got_ref_delete(ref, repo);
10900 if (err)
10901 goto done;
10903 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10904 done:
10905 free(id_str);
10906 return err;
10909 static const struct got_error *
10910 print_backup_ref(const char *branch_name, const char *new_id_str,
10911 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10912 struct got_reflist_object_id_map *refs_idmap,
10913 struct got_repository *repo)
10915 const struct got_error *err = NULL;
10916 struct got_reflist_head *refs;
10917 char *refs_str = NULL;
10918 struct got_object_id *new_commit_id = NULL;
10919 struct got_commit_object *new_commit = NULL;
10920 char *new_commit_brief_str = NULL;
10921 struct got_object_id *yca_id = NULL;
10922 struct got_commit_object *yca_commit = NULL;
10923 char *yca_id_str = NULL, *yca_brief_str = NULL;
10924 char *custom_refs_str;
10926 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10927 return got_error_from_errno("asprintf");
10929 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10930 0, 0, refs_idmap, custom_refs_str, NULL);
10931 if (err)
10932 goto done;
10934 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10935 if (err)
10936 goto done;
10938 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10939 if (refs) {
10940 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10941 if (err)
10942 goto done;
10945 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10946 if (err)
10947 goto done;
10949 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10950 if (err)
10951 goto done;
10953 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10954 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10955 if (err)
10956 goto done;
10958 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10959 refs_str ? " (" : "", refs_str ? refs_str : "",
10960 refs_str ? ")" : "", new_commit_brief_str);
10961 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10962 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10963 free(refs_str);
10964 refs_str = NULL;
10966 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10967 if (err)
10968 goto done;
10970 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10971 if (err)
10972 goto done;
10974 err = got_object_id_str(&yca_id_str, yca_id);
10975 if (err)
10976 goto done;
10978 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10979 if (refs) {
10980 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10981 if (err)
10982 goto done;
10984 printf("history forked at %s%s%s%s\n %s\n",
10985 yca_id_str,
10986 refs_str ? " (" : "", refs_str ? refs_str : "",
10987 refs_str ? ")" : "", yca_brief_str);
10989 done:
10990 free(custom_refs_str);
10991 free(new_commit_id);
10992 free(refs_str);
10993 free(yca_id);
10994 free(yca_id_str);
10995 free(yca_brief_str);
10996 if (new_commit)
10997 got_object_commit_close(new_commit);
10998 if (yca_commit)
10999 got_object_commit_close(yca_commit);
11001 return err;
11004 static const struct got_error *
11005 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11006 struct got_repository *repo)
11008 const struct got_error *err;
11009 struct got_reflist_head refs;
11010 struct got_reflist_entry *re;
11011 char *uuidstr = NULL;
11012 static char msg[160];
11014 TAILQ_INIT(&refs);
11016 err = got_worktree_get_uuid(&uuidstr, worktree);
11017 if (err)
11018 goto done;
11020 err = got_ref_list(&refs, repo, "refs/got/worktree",
11021 got_ref_cmp_by_name, repo);
11022 if (err)
11023 goto done;
11025 TAILQ_FOREACH(re, &refs, entry) {
11026 const char *cmd, *refname, *type;
11028 refname = got_ref_get_name(re->ref);
11030 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11031 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11032 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11033 cmd = "cherrypick";
11034 type = "cherrypicked";
11035 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11036 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11037 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11038 cmd = "backout";
11039 type = "backed-out";
11040 } else
11041 continue;
11043 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11044 continue;
11046 snprintf(msg, sizeof(msg),
11047 "work tree has references created by %s commits which "
11048 "must be removed with 'got %s -X' before running the %s "
11049 "command", type, cmd, caller);
11050 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11051 goto done;
11054 done:
11055 free(uuidstr);
11056 got_ref_list_free(&refs);
11057 return err;
11060 static const struct got_error *
11061 process_backup_refs(const char *backup_ref_prefix,
11062 const char *wanted_branch_name,
11063 int delete, struct got_repository *repo)
11065 const struct got_error *err;
11066 struct got_reflist_head refs, backup_refs;
11067 struct got_reflist_entry *re;
11068 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11069 struct got_object_id *old_commit_id = NULL;
11070 char *branch_name = NULL;
11071 struct got_commit_object *old_commit = NULL;
11072 struct got_reflist_object_id_map *refs_idmap = NULL;
11073 int wanted_branch_found = 0;
11075 TAILQ_INIT(&refs);
11076 TAILQ_INIT(&backup_refs);
11078 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11079 if (err)
11080 return err;
11082 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11083 if (err)
11084 goto done;
11086 if (wanted_branch_name) {
11087 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11088 wanted_branch_name += 11;
11091 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11092 got_ref_cmp_by_commit_timestamp_descending, repo);
11093 if (err)
11094 goto done;
11096 TAILQ_FOREACH(re, &backup_refs, entry) {
11097 const char *refname = got_ref_get_name(re->ref);
11098 char *slash;
11100 err = check_cancelled(NULL);
11101 if (err)
11102 break;
11104 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11105 if (err)
11106 break;
11108 err = got_object_open_as_commit(&old_commit, repo,
11109 old_commit_id);
11110 if (err)
11111 break;
11113 if (strncmp(backup_ref_prefix, refname,
11114 backup_ref_prefix_len) == 0)
11115 refname += backup_ref_prefix_len;
11117 while (refname[0] == '/')
11118 refname++;
11120 branch_name = strdup(refname);
11121 if (branch_name == NULL) {
11122 err = got_error_from_errno("strdup");
11123 break;
11125 slash = strrchr(branch_name, '/');
11126 if (slash) {
11127 *slash = '\0';
11128 refname += strlen(branch_name) + 1;
11131 if (wanted_branch_name == NULL ||
11132 strcmp(wanted_branch_name, branch_name) == 0) {
11133 wanted_branch_found = 1;
11134 if (delete) {
11135 err = delete_backup_ref(re->ref,
11136 old_commit_id, repo);
11137 } else {
11138 err = print_backup_ref(branch_name, refname,
11139 old_commit_id, old_commit, refs_idmap,
11140 repo);
11142 if (err)
11143 break;
11146 free(old_commit_id);
11147 old_commit_id = NULL;
11148 free(branch_name);
11149 branch_name = NULL;
11150 got_object_commit_close(old_commit);
11151 old_commit = NULL;
11154 if (wanted_branch_name && !wanted_branch_found) {
11155 err = got_error_fmt(GOT_ERR_NOT_REF,
11156 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11158 done:
11159 if (refs_idmap)
11160 got_reflist_object_id_map_free(refs_idmap);
11161 got_ref_list_free(&refs);
11162 got_ref_list_free(&backup_refs);
11163 free(old_commit_id);
11164 free(branch_name);
11165 if (old_commit)
11166 got_object_commit_close(old_commit);
11167 return err;
11170 static const struct got_error *
11171 abort_progress(void *arg, unsigned char status, const char *path)
11174 * Unversioned files should not clutter progress output when
11175 * an operation is aborted.
11177 if (status == GOT_STATUS_UNVERSIONED)
11178 return NULL;
11180 return update_progress(arg, status, path);
11183 static const struct got_error *
11184 cmd_rebase(int argc, char *argv[])
11186 const struct got_error *error = NULL;
11187 struct got_worktree *worktree = NULL;
11188 struct got_repository *repo = NULL;
11189 struct got_fileindex *fileindex = NULL;
11190 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11191 struct got_reference *branch = NULL;
11192 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11193 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11194 struct got_object_id *resume_commit_id = NULL;
11195 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11196 struct got_object_id *head_commit_id = NULL;
11197 struct got_reference *head_ref = NULL;
11198 struct got_commit_object *commit = NULL;
11199 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11200 int histedit_in_progress = 0, merge_in_progress = 0;
11201 int create_backup = 1, list_backups = 0, delete_backups = 0;
11202 int allow_conflict = 0;
11203 struct got_object_id_queue commits;
11204 struct got_pathlist_head merged_paths;
11205 const struct got_object_id_queue *parent_ids;
11206 struct got_object_qid *qid, *pid;
11207 struct got_update_progress_arg upa;
11208 int *pack_fds = NULL;
11210 STAILQ_INIT(&commits);
11211 TAILQ_INIT(&merged_paths);
11212 memset(&upa, 0, sizeof(upa));
11214 #ifndef PROFILE
11215 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11216 "unveil", NULL) == -1)
11217 err(1, "pledge");
11218 #endif
11220 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11221 switch (ch) {
11222 case 'a':
11223 abort_rebase = 1;
11224 break;
11225 case 'C':
11226 allow_conflict = 1;
11227 break;
11228 case 'c':
11229 continue_rebase = 1;
11230 break;
11231 case 'l':
11232 list_backups = 1;
11233 break;
11234 case 'X':
11235 delete_backups = 1;
11236 break;
11237 default:
11238 usage_rebase();
11239 /* NOTREACHED */
11243 argc -= optind;
11244 argv += optind;
11246 if (list_backups) {
11247 if (abort_rebase)
11248 option_conflict('l', 'a');
11249 if (allow_conflict)
11250 option_conflict('l', 'C');
11251 if (continue_rebase)
11252 option_conflict('l', 'c');
11253 if (delete_backups)
11254 option_conflict('l', 'X');
11255 if (argc != 0 && argc != 1)
11256 usage_rebase();
11257 } else if (delete_backups) {
11258 if (abort_rebase)
11259 option_conflict('X', 'a');
11260 if (allow_conflict)
11261 option_conflict('X', 'C');
11262 if (continue_rebase)
11263 option_conflict('X', 'c');
11264 if (list_backups)
11265 option_conflict('l', 'X');
11266 if (argc != 0 && argc != 1)
11267 usage_rebase();
11268 } else if (allow_conflict) {
11269 if (abort_rebase)
11270 option_conflict('C', 'a');
11271 if (!continue_rebase)
11272 errx(1, "-C option requires -c");
11273 } else {
11274 if (abort_rebase && continue_rebase)
11275 usage_rebase();
11276 else if (abort_rebase || continue_rebase) {
11277 if (argc != 0)
11278 usage_rebase();
11279 } else if (argc != 1)
11280 usage_rebase();
11283 cwd = getcwd(NULL, 0);
11284 if (cwd == NULL) {
11285 error = got_error_from_errno("getcwd");
11286 goto done;
11289 error = got_repo_pack_fds_open(&pack_fds);
11290 if (error != NULL)
11291 goto done;
11293 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11294 if (error) {
11295 if (list_backups || delete_backups) {
11296 if (error->code != GOT_ERR_NOT_WORKTREE)
11297 goto done;
11298 } else {
11299 if (error->code == GOT_ERR_NOT_WORKTREE)
11300 error = wrap_not_worktree_error(error,
11301 "rebase", cwd);
11302 goto done;
11306 error = get_gitconfig_path(&gitconfig_path);
11307 if (error)
11308 goto done;
11309 error = got_repo_open(&repo,
11310 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11311 gitconfig_path, pack_fds);
11312 if (error != NULL)
11313 goto done;
11315 if (worktree != NULL && !list_backups && !delete_backups) {
11316 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11317 if (error)
11318 goto done;
11321 error = get_author(&committer, repo, worktree);
11322 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11323 goto done;
11325 error = apply_unveil(got_repo_get_path(repo), 0,
11326 worktree ? got_worktree_get_root_path(worktree) : NULL);
11327 if (error)
11328 goto done;
11330 if (list_backups || delete_backups) {
11331 error = process_backup_refs(
11332 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11333 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11334 goto done; /* nothing else to do */
11337 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11338 worktree);
11339 if (error)
11340 goto done;
11341 if (histedit_in_progress) {
11342 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11343 goto done;
11346 error = got_worktree_merge_in_progress(&merge_in_progress,
11347 worktree, repo);
11348 if (error)
11349 goto done;
11350 if (merge_in_progress) {
11351 error = got_error(GOT_ERR_MERGE_BUSY);
11352 goto done;
11355 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11356 if (error)
11357 goto done;
11359 if (abort_rebase) {
11360 if (!rebase_in_progress) {
11361 error = got_error(GOT_ERR_NOT_REBASING);
11362 goto done;
11364 error = got_worktree_rebase_continue(&resume_commit_id,
11365 &new_base_branch, &tmp_branch, &branch, &fileindex,
11366 worktree, repo);
11367 if (error)
11368 goto done;
11369 printf("Switching work tree to %s\n",
11370 got_ref_get_symref_target(new_base_branch));
11371 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11372 new_base_branch, abort_progress, &upa);
11373 if (error)
11374 goto done;
11375 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11376 print_merge_progress_stats(&upa);
11377 goto done; /* nothing else to do */
11380 if (continue_rebase) {
11381 if (!rebase_in_progress) {
11382 error = got_error(GOT_ERR_NOT_REBASING);
11383 goto done;
11385 error = got_worktree_rebase_continue(&resume_commit_id,
11386 &new_base_branch, &tmp_branch, &branch, &fileindex,
11387 worktree, repo);
11388 if (error)
11389 goto done;
11391 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11392 committer, resume_commit_id, allow_conflict, repo);
11393 if (error)
11394 goto done;
11396 yca_id = got_object_id_dup(resume_commit_id);
11397 if (yca_id == NULL) {
11398 error = got_error_from_errno("got_object_id_dup");
11399 goto done;
11401 } else {
11402 error = got_ref_open(&branch, repo, argv[0], 0);
11403 if (error != NULL)
11404 goto done;
11405 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11406 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11407 "will not rebase a branch which lives outside "
11408 "the \"refs/heads/\" reference namespace");
11409 goto done;
11413 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11414 if (error)
11415 goto done;
11417 if (!continue_rebase) {
11418 struct got_object_id *base_commit_id;
11420 error = got_ref_open(&head_ref, repo,
11421 got_worktree_get_head_ref_name(worktree), 0);
11422 if (error)
11423 goto done;
11424 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11425 if (error)
11426 goto done;
11427 base_commit_id = got_worktree_get_base_commit_id(worktree);
11428 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11429 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11430 goto done;
11433 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11434 base_commit_id, branch_head_commit_id, 1, repo,
11435 check_cancelled, NULL);
11436 if (error) {
11437 if (error->code == GOT_ERR_ANCESTRY) {
11438 error = got_error_msg(GOT_ERR_ANCESTRY,
11439 "specified branch shares no common "
11440 "ancestry with work tree's branch");
11442 goto done;
11445 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11446 struct got_pathlist_head paths;
11447 printf("%s is already based on %s\n",
11448 got_ref_get_name(branch),
11449 got_worktree_get_head_ref_name(worktree));
11450 error = switch_head_ref(branch, branch_head_commit_id,
11451 worktree, repo);
11452 if (error)
11453 goto done;
11454 error = got_worktree_set_base_commit_id(worktree, repo,
11455 branch_head_commit_id);
11456 if (error)
11457 goto done;
11458 TAILQ_INIT(&paths);
11459 error = got_pathlist_append(&paths, "", NULL);
11460 if (error)
11461 goto done;
11462 error = got_worktree_checkout_files(worktree,
11463 &paths, repo, update_progress, &upa,
11464 check_cancelled, NULL);
11465 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11466 if (error)
11467 goto done;
11468 if (upa.did_something) {
11469 char *id_str;
11470 error = got_object_id_str(&id_str,
11471 branch_head_commit_id);
11472 if (error)
11473 goto done;
11474 printf("Updated to %s: %s\n",
11475 got_worktree_get_head_ref_name(worktree),
11476 id_str);
11477 free(id_str);
11478 } else
11479 printf("Already up-to-date\n");
11480 print_update_progress_stats(&upa);
11481 goto done;
11485 commit_id = branch_head_commit_id;
11486 error = got_object_open_as_commit(&commit, repo, commit_id);
11487 if (error)
11488 goto done;
11490 parent_ids = got_object_commit_get_parent_ids(commit);
11491 pid = STAILQ_FIRST(parent_ids);
11492 if (pid) {
11493 error = collect_commits(&commits, commit_id, &pid->id,
11494 yca_id, got_worktree_get_path_prefix(worktree),
11495 GOT_ERR_REBASE_PATH, repo);
11496 if (error)
11497 goto done;
11500 got_object_commit_close(commit);
11501 commit = NULL;
11503 if (!continue_rebase) {
11504 error = got_worktree_rebase_prepare(&new_base_branch,
11505 &tmp_branch, &fileindex, worktree, branch, repo);
11506 if (error)
11507 goto done;
11510 if (STAILQ_EMPTY(&commits)) {
11511 if (continue_rebase) {
11512 error = rebase_complete(worktree, fileindex,
11513 branch, tmp_branch, repo, create_backup);
11514 goto done;
11515 } else {
11516 /* Fast-forward the reference of the branch. */
11517 struct got_object_id *new_head_commit_id;
11518 char *id_str;
11519 error = got_ref_resolve(&new_head_commit_id, repo,
11520 new_base_branch);
11521 if (error)
11522 goto done;
11523 error = got_object_id_str(&id_str, new_head_commit_id);
11524 if (error)
11525 goto done;
11526 printf("Forwarding %s to commit %s\n",
11527 got_ref_get_name(branch), id_str);
11528 free(id_str);
11529 error = got_ref_change_ref(branch,
11530 new_head_commit_id);
11531 if (error)
11532 goto done;
11533 /* No backup needed since objects did not change. */
11534 create_backup = 0;
11538 pid = NULL;
11539 STAILQ_FOREACH(qid, &commits, entry) {
11541 commit_id = &qid->id;
11542 parent_id = pid ? &pid->id : yca_id;
11543 pid = qid;
11545 memset(&upa, 0, sizeof(upa));
11546 error = got_worktree_rebase_merge_files(&merged_paths,
11547 worktree, fileindex, parent_id, commit_id, repo,
11548 update_progress, &upa, check_cancelled, NULL);
11549 if (error)
11550 goto done;
11552 print_merge_progress_stats(&upa);
11553 if (upa.conflicts > 0 || upa.missing > 0 ||
11554 upa.not_deleted > 0 || upa.unversioned > 0) {
11555 if (upa.conflicts > 0) {
11556 error = show_rebase_merge_conflict(&qid->id,
11557 repo);
11558 if (error)
11559 goto done;
11561 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11562 break;
11565 error = rebase_commit(&merged_paths, worktree, fileindex,
11566 tmp_branch, committer, commit_id, 0, repo);
11567 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11568 if (error)
11569 goto done;
11572 if (upa.conflicts > 0 || upa.missing > 0 ||
11573 upa.not_deleted > 0 || upa.unversioned > 0) {
11574 error = got_worktree_rebase_postpone(worktree, fileindex);
11575 if (error)
11576 goto done;
11577 if (upa.conflicts > 0 && upa.missing == 0 &&
11578 upa.not_deleted == 0 && upa.unversioned == 0) {
11579 error = got_error_msg(GOT_ERR_CONFLICTS,
11580 "conflicts must be resolved before rebasing "
11581 "can continue");
11582 } else if (upa.conflicts > 0) {
11583 error = got_error_msg(GOT_ERR_CONFLICTS,
11584 "conflicts must be resolved before rebasing "
11585 "can continue; changes destined for some "
11586 "files were not yet merged and should be "
11587 "merged manually if required before the "
11588 "rebase operation is continued");
11589 } else {
11590 error = got_error_msg(GOT_ERR_CONFLICTS,
11591 "changes destined for some files were not "
11592 "yet merged and should be merged manually "
11593 "if required before the rebase operation "
11594 "is continued");
11596 } else
11597 error = rebase_complete(worktree, fileindex, branch,
11598 tmp_branch, repo, create_backup);
11599 done:
11600 free(cwd);
11601 free(committer);
11602 free(gitconfig_path);
11603 got_object_id_queue_free(&commits);
11604 free(branch_head_commit_id);
11605 free(resume_commit_id);
11606 free(head_commit_id);
11607 free(yca_id);
11608 if (commit)
11609 got_object_commit_close(commit);
11610 if (branch)
11611 got_ref_close(branch);
11612 if (new_base_branch)
11613 got_ref_close(new_base_branch);
11614 if (tmp_branch)
11615 got_ref_close(tmp_branch);
11616 if (head_ref)
11617 got_ref_close(head_ref);
11618 if (worktree)
11619 got_worktree_close(worktree);
11620 if (repo) {
11621 const struct got_error *close_err = got_repo_close(repo);
11622 if (error == NULL)
11623 error = close_err;
11625 if (pack_fds) {
11626 const struct got_error *pack_err =
11627 got_repo_pack_fds_close(pack_fds);
11628 if (error == NULL)
11629 error = pack_err;
11631 return error;
11634 __dead static void
11635 usage_histedit(void)
11637 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11638 "[branch]\n", getprogname());
11639 exit(1);
11642 #define GOT_HISTEDIT_PICK 'p'
11643 #define GOT_HISTEDIT_EDIT 'e'
11644 #define GOT_HISTEDIT_FOLD 'f'
11645 #define GOT_HISTEDIT_DROP 'd'
11646 #define GOT_HISTEDIT_MESG 'm'
11648 static const struct got_histedit_cmd {
11649 unsigned char code;
11650 const char *name;
11651 const char *desc;
11652 } got_histedit_cmds[] = {
11653 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11654 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11655 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11656 "be used" },
11657 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11658 { GOT_HISTEDIT_MESG, "mesg",
11659 "single-line log message for commit above (open editor if empty)" },
11662 struct got_histedit_list_entry {
11663 TAILQ_ENTRY(got_histedit_list_entry) entry;
11664 struct got_object_id *commit_id;
11665 const struct got_histedit_cmd *cmd;
11666 char *logmsg;
11668 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11670 static const struct got_error *
11671 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11672 FILE *f, struct got_repository *repo)
11674 const struct got_error *err = NULL;
11675 char *logmsg = NULL, *id_str = NULL;
11676 struct got_commit_object *commit = NULL;
11677 int n;
11679 err = got_object_open_as_commit(&commit, repo, commit_id);
11680 if (err)
11681 goto done;
11683 err = get_short_logmsg(&logmsg, 34, commit);
11684 if (err)
11685 goto done;
11687 err = got_object_id_str(&id_str, commit_id);
11688 if (err)
11689 goto done;
11691 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11692 if (n < 0)
11693 err = got_ferror(f, GOT_ERR_IO);
11694 done:
11695 if (commit)
11696 got_object_commit_close(commit);
11697 free(id_str);
11698 free(logmsg);
11699 return err;
11702 static const struct got_error *
11703 histedit_write_commit_list(struct got_object_id_queue *commits,
11704 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11705 int edit_only, struct got_repository *repo)
11707 const struct got_error *err = NULL;
11708 struct got_object_qid *qid;
11709 const char *histedit_cmd = NULL;
11711 if (STAILQ_EMPTY(commits))
11712 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11714 STAILQ_FOREACH(qid, commits, entry) {
11715 histedit_cmd = got_histedit_cmds[0].name;
11716 if (drop_only)
11717 histedit_cmd = "drop";
11718 else if (edit_only)
11719 histedit_cmd = "edit";
11720 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11721 histedit_cmd = "fold";
11722 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11723 if (err)
11724 break;
11725 if (edit_logmsg_only) {
11726 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11727 if (n < 0) {
11728 err = got_ferror(f, GOT_ERR_IO);
11729 break;
11734 return err;
11737 static const struct got_error *
11738 write_cmd_list(FILE *f, const char *branch_name,
11739 struct got_object_id_queue *commits)
11741 const struct got_error *err = NULL;
11742 size_t i;
11743 int n;
11744 char *id_str;
11745 struct got_object_qid *qid;
11747 qid = STAILQ_FIRST(commits);
11748 err = got_object_id_str(&id_str, &qid->id);
11749 if (err)
11750 return err;
11752 n = fprintf(f,
11753 "# Editing the history of branch '%s' starting at\n"
11754 "# commit %s\n"
11755 "# Commits will be processed in order from top to "
11756 "bottom of this file.\n", branch_name, id_str);
11757 if (n < 0) {
11758 err = got_ferror(f, GOT_ERR_IO);
11759 goto done;
11762 n = fprintf(f, "# Available histedit commands:\n");
11763 if (n < 0) {
11764 err = got_ferror(f, GOT_ERR_IO);
11765 goto done;
11768 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11769 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11770 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11771 cmd->desc);
11772 if (n < 0) {
11773 err = got_ferror(f, GOT_ERR_IO);
11774 break;
11777 done:
11778 free(id_str);
11779 return err;
11782 static const struct got_error *
11783 histedit_syntax_error(int lineno)
11785 static char msg[42];
11786 int ret;
11788 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11789 lineno);
11790 if (ret < 0 || (size_t)ret >= sizeof(msg))
11791 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11793 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11796 static const struct got_error *
11797 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11798 char *logmsg, struct got_repository *repo)
11800 const struct got_error *err;
11801 struct got_commit_object *folded_commit = NULL;
11802 char *id_str, *folded_logmsg = NULL;
11804 err = got_object_id_str(&id_str, hle->commit_id);
11805 if (err)
11806 return err;
11808 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11809 if (err)
11810 goto done;
11812 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11813 if (err)
11814 goto done;
11815 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11816 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11817 folded_logmsg) == -1) {
11818 err = got_error_from_errno("asprintf");
11820 done:
11821 if (folded_commit)
11822 got_object_commit_close(folded_commit);
11823 free(id_str);
11824 free(folded_logmsg);
11825 return err;
11828 static struct got_histedit_list_entry *
11829 get_folded_commits(struct got_histedit_list_entry *hle)
11831 struct got_histedit_list_entry *prev, *folded = NULL;
11833 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11834 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11835 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11836 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11837 folded = prev;
11838 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11841 return folded;
11844 static const struct got_error *
11845 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11846 struct got_repository *repo)
11848 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11849 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11850 const struct got_error *err = NULL;
11851 struct got_commit_object *commit = NULL;
11852 int logmsg_len;
11853 int fd = -1;
11854 struct got_histedit_list_entry *folded = NULL;
11856 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11857 if (err)
11858 return err;
11860 folded = get_folded_commits(hle);
11861 if (folded) {
11862 while (folded != hle) {
11863 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11864 folded = TAILQ_NEXT(folded, entry);
11865 continue;
11867 err = append_folded_commit_msg(&new_msg, folded,
11868 logmsg, repo);
11869 if (err)
11870 goto done;
11871 free(logmsg);
11872 logmsg = new_msg;
11873 folded = TAILQ_NEXT(folded, entry);
11877 err = got_object_id_str(&id_str, hle->commit_id);
11878 if (err)
11879 goto done;
11880 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11881 if (err)
11882 goto done;
11883 logmsg_len = asprintf(&new_msg,
11884 "%s\n# original log message of commit %s: %s",
11885 logmsg ? logmsg : "", id_str, orig_logmsg);
11886 if (logmsg_len == -1) {
11887 err = got_error_from_errno("asprintf");
11888 goto done;
11890 free(logmsg);
11891 logmsg = new_msg;
11893 err = got_object_id_str(&id_str, hle->commit_id);
11894 if (err)
11895 goto done;
11897 err = got_opentemp_named_fd(&logmsg_path, &fd,
11898 GOT_TMPDIR_STR "/got-logmsg", "");
11899 if (err)
11900 goto done;
11902 if (write(fd, logmsg, logmsg_len) == -1) {
11903 err = got_error_from_errno2("write", logmsg_path);
11904 goto done;
11906 if (close(fd) == -1) {
11907 err = got_error_from_errno2("close", logmsg_path);
11908 goto done;
11910 fd = -1;
11912 err = get_editor(&editor);
11913 if (err)
11914 goto done;
11916 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11917 logmsg_len, 0);
11918 if (err) {
11919 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11920 goto done;
11921 err = NULL;
11922 hle->logmsg = strdup(new_msg);
11923 if (hle->logmsg == NULL)
11924 err = got_error_from_errno("strdup");
11926 done:
11927 if (fd != -1 && close(fd) == -1 && err == NULL)
11928 err = got_error_from_errno2("close", logmsg_path);
11929 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11930 err = got_error_from_errno2("unlink", logmsg_path);
11931 free(logmsg_path);
11932 free(logmsg);
11933 free(orig_logmsg);
11934 free(editor);
11935 if (commit)
11936 got_object_commit_close(commit);
11937 return err;
11940 static const struct got_error *
11941 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11942 FILE *f, struct got_repository *repo)
11944 const struct got_error *err = NULL;
11945 char *line = NULL, *p, *end;
11946 size_t i, linesize = 0;
11947 ssize_t linelen;
11948 int lineno = 0, lastcmd = -1;
11949 const struct got_histedit_cmd *cmd;
11950 struct got_object_id *commit_id = NULL;
11951 struct got_histedit_list_entry *hle = NULL;
11953 for (;;) {
11954 linelen = getline(&line, &linesize, f);
11955 if (linelen == -1) {
11956 const struct got_error *getline_err;
11957 if (feof(f))
11958 break;
11959 getline_err = got_error_from_errno("getline");
11960 err = got_ferror(f, getline_err->code);
11961 break;
11963 lineno++;
11964 p = line;
11965 while (isspace((unsigned char)p[0]))
11966 p++;
11967 if (p[0] == '#' || p[0] == '\0')
11968 continue;
11969 cmd = NULL;
11970 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11971 cmd = &got_histedit_cmds[i];
11972 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11973 isspace((unsigned char)p[strlen(cmd->name)])) {
11974 p += strlen(cmd->name);
11975 break;
11977 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11978 p++;
11979 break;
11982 if (i == nitems(got_histedit_cmds)) {
11983 err = histedit_syntax_error(lineno);
11984 break;
11986 while (isspace((unsigned char)p[0]))
11987 p++;
11988 if (cmd->code == GOT_HISTEDIT_MESG) {
11989 if (lastcmd != GOT_HISTEDIT_PICK &&
11990 lastcmd != GOT_HISTEDIT_EDIT) {
11991 err = got_error(GOT_ERR_HISTEDIT_CMD);
11992 break;
11994 if (p[0] == '\0') {
11995 err = histedit_edit_logmsg(hle, repo);
11996 if (err)
11997 break;
11998 } else {
11999 hle->logmsg = strdup(p);
12000 if (hle->logmsg == NULL) {
12001 err = got_error_from_errno("strdup");
12002 break;
12005 lastcmd = cmd->code;
12006 continue;
12007 } else {
12008 end = p;
12009 while (end[0] && !isspace((unsigned char)end[0]))
12010 end++;
12011 *end = '\0';
12013 err = got_object_resolve_id_str(&commit_id, repo, p);
12014 if (err) {
12015 /* override error code */
12016 err = histedit_syntax_error(lineno);
12017 break;
12020 hle = malloc(sizeof(*hle));
12021 if (hle == NULL) {
12022 err = got_error_from_errno("malloc");
12023 break;
12025 hle->cmd = cmd;
12026 hle->commit_id = commit_id;
12027 hle->logmsg = NULL;
12028 commit_id = NULL;
12029 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12030 lastcmd = cmd->code;
12033 free(line);
12034 free(commit_id);
12035 return err;
12038 static const struct got_error *
12039 histedit_check_script(struct got_histedit_list *histedit_cmds,
12040 struct got_object_id_queue *commits, struct got_repository *repo)
12042 const struct got_error *err = NULL;
12043 struct got_object_qid *qid;
12044 struct got_histedit_list_entry *hle;
12045 static char msg[92];
12046 char *id_str;
12048 if (TAILQ_EMPTY(histedit_cmds))
12049 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12050 "histedit script contains no commands");
12051 if (STAILQ_EMPTY(commits))
12052 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12054 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12055 struct got_histedit_list_entry *hle2;
12056 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12057 if (hle == hle2)
12058 continue;
12059 if (got_object_id_cmp(hle->commit_id,
12060 hle2->commit_id) != 0)
12061 continue;
12062 err = got_object_id_str(&id_str, hle->commit_id);
12063 if (err)
12064 return err;
12065 snprintf(msg, sizeof(msg), "commit %s is listed "
12066 "more than once in histedit script", id_str);
12067 free(id_str);
12068 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12072 STAILQ_FOREACH(qid, commits, entry) {
12073 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12074 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12075 break;
12077 if (hle == NULL) {
12078 err = got_object_id_str(&id_str, &qid->id);
12079 if (err)
12080 return err;
12081 snprintf(msg, sizeof(msg),
12082 "commit %s missing from histedit script", id_str);
12083 free(id_str);
12084 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12088 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12089 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12090 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12091 "last commit in histedit script cannot be folded");
12093 return NULL;
12096 static const struct got_error *
12097 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12098 const char *path, struct got_object_id_queue *commits,
12099 struct got_repository *repo)
12101 const struct got_error *err = NULL;
12102 struct stat st, st2;
12103 struct timespec timeout;
12104 char *editor;
12105 FILE *f = NULL;
12107 err = get_editor(&editor);
12108 if (err)
12109 return err;
12111 if (stat(path, &st) == -1) {
12112 err = got_error_from_errno2("stat", path);
12113 goto done;
12116 if (spawn_editor(editor, path) == -1) {
12117 err = got_error_from_errno("failed spawning editor");
12118 goto done;
12121 timeout.tv_sec = 0;
12122 timeout.tv_nsec = 1;
12123 nanosleep(&timeout, NULL);
12125 if (stat(path, &st2) == -1) {
12126 err = got_error_from_errno2("stat", path);
12127 goto done;
12130 if (st.st_size == st2.st_size &&
12131 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12132 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12133 "no changes made to histedit script, aborting");
12134 goto done;
12137 f = fopen(path, "re");
12138 if (f == NULL) {
12139 err = got_error_from_errno("fopen");
12140 goto done;
12142 err = histedit_parse_list(histedit_cmds, f, repo);
12143 if (err)
12144 goto done;
12146 err = histedit_check_script(histedit_cmds, commits, repo);
12147 done:
12148 if (f && fclose(f) == EOF && err == NULL)
12149 err = got_error_from_errno("fclose");
12150 free(editor);
12151 return err;
12154 static const struct got_error *
12155 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12156 struct got_object_id_queue *, const char *, const char *,
12157 struct got_repository *);
12159 static const struct got_error *
12160 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12161 struct got_object_id_queue *commits, const char *branch_name,
12162 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12163 struct got_repository *repo)
12165 const struct got_error *err;
12166 FILE *f = NULL;
12167 char *path = NULL;
12169 err = got_opentemp_named(&path, &f, "got-histedit", "");
12170 if (err)
12171 return err;
12173 err = write_cmd_list(f, branch_name, commits);
12174 if (err)
12175 goto done;
12177 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12178 fold_only, drop_only, edit_only, repo);
12179 if (err)
12180 goto done;
12182 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12183 rewind(f);
12184 err = histedit_parse_list(histedit_cmds, f, repo);
12185 } else {
12186 if (fclose(f) == EOF) {
12187 err = got_error_from_errno("fclose");
12188 goto done;
12190 f = NULL;
12191 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12192 if (err) {
12193 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12194 err->code != GOT_ERR_HISTEDIT_CMD)
12195 goto done;
12196 err = histedit_edit_list_retry(histedit_cmds, err,
12197 commits, path, branch_name, repo);
12200 done:
12201 if (f && fclose(f) == EOF && err == NULL)
12202 err = got_error_from_errno("fclose");
12203 if (path && unlink(path) != 0 && err == NULL)
12204 err = got_error_from_errno2("unlink", path);
12205 free(path);
12206 return err;
12209 static const struct got_error *
12210 histedit_save_list(struct got_histedit_list *histedit_cmds,
12211 struct got_worktree *worktree, struct got_repository *repo)
12213 const struct got_error *err = NULL;
12214 char *path = NULL;
12215 FILE *f = NULL;
12216 struct got_histedit_list_entry *hle;
12218 err = got_worktree_get_histedit_script_path(&path, worktree);
12219 if (err)
12220 return err;
12222 f = fopen(path, "we");
12223 if (f == NULL) {
12224 err = got_error_from_errno2("fopen", path);
12225 goto done;
12227 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12228 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12229 repo);
12230 if (err)
12231 break;
12233 if (hle->logmsg) {
12234 int n = fprintf(f, "%c %s\n",
12235 GOT_HISTEDIT_MESG, hle->logmsg);
12236 if (n < 0) {
12237 err = got_ferror(f, GOT_ERR_IO);
12238 break;
12242 done:
12243 if (f && fclose(f) == EOF && err == NULL)
12244 err = got_error_from_errno("fclose");
12245 free(path);
12246 return err;
12249 static void
12250 histedit_free_list(struct got_histedit_list *histedit_cmds)
12252 struct got_histedit_list_entry *hle;
12254 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12255 TAILQ_REMOVE(histedit_cmds, hle, entry);
12256 free(hle);
12260 static const struct got_error *
12261 histedit_load_list(struct got_histedit_list *histedit_cmds,
12262 const char *path, struct got_repository *repo)
12264 const struct got_error *err = NULL;
12265 FILE *f = NULL;
12267 f = fopen(path, "re");
12268 if (f == NULL) {
12269 err = got_error_from_errno2("fopen", path);
12270 goto done;
12273 err = histedit_parse_list(histedit_cmds, f, repo);
12274 done:
12275 if (f && fclose(f) == EOF && err == NULL)
12276 err = got_error_from_errno("fclose");
12277 return err;
12280 static const struct got_error *
12281 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12282 const struct got_error *edit_err, struct got_object_id_queue *commits,
12283 const char *path, const char *branch_name, struct got_repository *repo)
12285 const struct got_error *err = NULL, *prev_err = edit_err;
12286 int resp = ' ';
12288 while (resp != 'c' && resp != 'r' && resp != 'a') {
12289 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12290 "or (a)bort: ", getprogname(), prev_err->msg);
12291 resp = getchar();
12292 if (resp == '\n')
12293 resp = getchar();
12294 if (resp == 'c') {
12295 histedit_free_list(histedit_cmds);
12296 err = histedit_run_editor(histedit_cmds, path, commits,
12297 repo);
12298 if (err) {
12299 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12300 err->code != GOT_ERR_HISTEDIT_CMD)
12301 break;
12302 prev_err = err;
12303 resp = ' ';
12304 continue;
12306 break;
12307 } else if (resp == 'r') {
12308 histedit_free_list(histedit_cmds);
12309 err = histedit_edit_script(histedit_cmds,
12310 commits, branch_name, 0, 0, 0, 0, repo);
12311 if (err) {
12312 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12313 err->code != GOT_ERR_HISTEDIT_CMD)
12314 break;
12315 prev_err = err;
12316 resp = ' ';
12317 continue;
12319 break;
12320 } else if (resp == 'a') {
12321 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12322 break;
12323 } else
12324 printf("invalid response '%c'\n", resp);
12327 return err;
12330 static const struct got_error *
12331 histedit_complete(struct got_worktree *worktree,
12332 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12333 struct got_reference *branch, struct got_repository *repo)
12335 printf("Switching work tree to %s\n",
12336 got_ref_get_symref_target(branch));
12337 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12338 branch, repo);
12341 static const struct got_error *
12342 show_histedit_progress(struct got_commit_object *commit,
12343 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12345 const struct got_error *err;
12346 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12348 err = got_object_id_str(&old_id_str, hle->commit_id);
12349 if (err)
12350 goto done;
12352 if (new_id) {
12353 err = got_object_id_str(&new_id_str, new_id);
12354 if (err)
12355 goto done;
12358 old_id_str[12] = '\0';
12359 if (new_id_str)
12360 new_id_str[12] = '\0';
12362 if (hle->logmsg) {
12363 logmsg = strdup(hle->logmsg);
12364 if (logmsg == NULL) {
12365 err = got_error_from_errno("strdup");
12366 goto done;
12368 trim_logmsg(logmsg, 42);
12369 } else {
12370 err = get_short_logmsg(&logmsg, 42, commit);
12371 if (err)
12372 goto done;
12375 switch (hle->cmd->code) {
12376 case GOT_HISTEDIT_PICK:
12377 case GOT_HISTEDIT_EDIT:
12378 printf("%s -> %s: %s\n", old_id_str,
12379 new_id_str ? new_id_str : "no-op change", logmsg);
12380 break;
12381 case GOT_HISTEDIT_DROP:
12382 case GOT_HISTEDIT_FOLD:
12383 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12384 logmsg);
12385 break;
12386 default:
12387 break;
12389 done:
12390 free(old_id_str);
12391 free(new_id_str);
12392 return err;
12395 static const struct got_error *
12396 histedit_commit(struct got_pathlist_head *merged_paths,
12397 struct got_worktree *worktree, struct got_fileindex *fileindex,
12398 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12399 const char *committer, int allow_conflict, struct got_repository *repo)
12401 const struct got_error *err;
12402 struct got_commit_object *commit;
12403 struct got_object_id *new_commit_id;
12405 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12406 && hle->logmsg == NULL) {
12407 err = histedit_edit_logmsg(hle, repo);
12408 if (err)
12409 return err;
12412 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12413 if (err)
12414 return err;
12416 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12417 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12418 hle->logmsg, allow_conflict, repo);
12419 if (err) {
12420 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12421 goto done;
12422 err = show_histedit_progress(commit, hle, NULL);
12423 } else {
12424 err = show_histedit_progress(commit, hle, new_commit_id);
12425 free(new_commit_id);
12427 done:
12428 got_object_commit_close(commit);
12429 return err;
12432 static const struct got_error *
12433 histedit_skip_commit(struct got_histedit_list_entry *hle,
12434 struct got_worktree *worktree, struct got_repository *repo)
12436 const struct got_error *error;
12437 struct got_commit_object *commit;
12439 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12440 repo);
12441 if (error)
12442 return error;
12444 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12445 if (error)
12446 return error;
12448 error = show_histedit_progress(commit, hle, NULL);
12449 got_object_commit_close(commit);
12450 return error;
12453 static const struct got_error *
12454 check_local_changes(void *arg, unsigned char status,
12455 unsigned char staged_status, const char *path,
12456 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12457 struct got_object_id *commit_id, int dirfd, const char *de_name)
12459 int *have_local_changes = arg;
12461 switch (status) {
12462 case GOT_STATUS_ADD:
12463 case GOT_STATUS_DELETE:
12464 case GOT_STATUS_MODIFY:
12465 case GOT_STATUS_CONFLICT:
12466 *have_local_changes = 1;
12467 return got_error(GOT_ERR_CANCELLED);
12468 default:
12469 break;
12472 switch (staged_status) {
12473 case GOT_STATUS_ADD:
12474 case GOT_STATUS_DELETE:
12475 case GOT_STATUS_MODIFY:
12476 *have_local_changes = 1;
12477 return got_error(GOT_ERR_CANCELLED);
12478 default:
12479 break;
12482 return NULL;
12485 static const struct got_error *
12486 cmd_histedit(int argc, char *argv[])
12488 const struct got_error *error = NULL;
12489 struct got_worktree *worktree = NULL;
12490 struct got_fileindex *fileindex = NULL;
12491 struct got_repository *repo = NULL;
12492 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12493 struct got_reference *branch = NULL;
12494 struct got_reference *tmp_branch = NULL;
12495 struct got_object_id *resume_commit_id = NULL;
12496 struct got_object_id *base_commit_id = NULL;
12497 struct got_object_id *head_commit_id = NULL;
12498 struct got_commit_object *commit = NULL;
12499 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12500 struct got_update_progress_arg upa;
12501 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12502 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12503 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12504 const char *edit_script_path = NULL;
12505 struct got_object_id_queue commits;
12506 struct got_pathlist_head merged_paths;
12507 const struct got_object_id_queue *parent_ids;
12508 struct got_object_qid *pid;
12509 struct got_histedit_list histedit_cmds;
12510 struct got_histedit_list_entry *hle;
12511 int *pack_fds = NULL;
12513 STAILQ_INIT(&commits);
12514 TAILQ_INIT(&histedit_cmds);
12515 TAILQ_INIT(&merged_paths);
12516 memset(&upa, 0, sizeof(upa));
12518 #ifndef PROFILE
12519 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12520 "unveil", NULL) == -1)
12521 err(1, "pledge");
12522 #endif
12524 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12525 switch (ch) {
12526 case 'a':
12527 abort_edit = 1;
12528 break;
12529 case 'C':
12530 allow_conflict = 1;
12531 break;
12532 case 'c':
12533 continue_edit = 1;
12534 break;
12535 case 'd':
12536 drop_only = 1;
12537 break;
12538 case 'e':
12539 edit_only = 1;
12540 break;
12541 case 'F':
12542 edit_script_path = optarg;
12543 break;
12544 case 'f':
12545 fold_only = 1;
12546 break;
12547 case 'l':
12548 list_backups = 1;
12549 break;
12550 case 'm':
12551 edit_logmsg_only = 1;
12552 break;
12553 case 'X':
12554 delete_backups = 1;
12555 break;
12556 default:
12557 usage_histedit();
12558 /* NOTREACHED */
12562 argc -= optind;
12563 argv += optind;
12565 if (abort_edit && allow_conflict)
12566 option_conflict('a', 'C');
12567 if (abort_edit && continue_edit)
12568 option_conflict('a', 'c');
12569 if (edit_script_path && allow_conflict)
12570 option_conflict('F', 'C');
12571 if (edit_script_path && edit_logmsg_only)
12572 option_conflict('F', 'm');
12573 if (abort_edit && edit_logmsg_only)
12574 option_conflict('a', 'm');
12575 if (edit_logmsg_only && allow_conflict)
12576 option_conflict('m', 'C');
12577 if (continue_edit && edit_logmsg_only)
12578 option_conflict('c', 'm');
12579 if (abort_edit && fold_only)
12580 option_conflict('a', 'f');
12581 if (fold_only && allow_conflict)
12582 option_conflict('f', 'C');
12583 if (continue_edit && fold_only)
12584 option_conflict('c', 'f');
12585 if (fold_only && edit_logmsg_only)
12586 option_conflict('f', 'm');
12587 if (edit_script_path && fold_only)
12588 option_conflict('F', 'f');
12589 if (abort_edit && edit_only)
12590 option_conflict('a', 'e');
12591 if (continue_edit && edit_only)
12592 option_conflict('c', 'e');
12593 if (edit_only && edit_logmsg_only)
12594 option_conflict('e', 'm');
12595 if (edit_script_path && edit_only)
12596 option_conflict('F', 'e');
12597 if (fold_only && edit_only)
12598 option_conflict('f', 'e');
12599 if (drop_only && abort_edit)
12600 option_conflict('d', 'a');
12601 if (drop_only && allow_conflict)
12602 option_conflict('d', 'C');
12603 if (drop_only && continue_edit)
12604 option_conflict('d', 'c');
12605 if (drop_only && edit_logmsg_only)
12606 option_conflict('d', 'm');
12607 if (drop_only && edit_only)
12608 option_conflict('d', 'e');
12609 if (drop_only && edit_script_path)
12610 option_conflict('d', 'F');
12611 if (drop_only && fold_only)
12612 option_conflict('d', 'f');
12613 if (list_backups) {
12614 if (abort_edit)
12615 option_conflict('l', 'a');
12616 if (allow_conflict)
12617 option_conflict('l', 'C');
12618 if (continue_edit)
12619 option_conflict('l', 'c');
12620 if (edit_script_path)
12621 option_conflict('l', 'F');
12622 if (edit_logmsg_only)
12623 option_conflict('l', 'm');
12624 if (drop_only)
12625 option_conflict('l', 'd');
12626 if (fold_only)
12627 option_conflict('l', 'f');
12628 if (edit_only)
12629 option_conflict('l', 'e');
12630 if (delete_backups)
12631 option_conflict('l', 'X');
12632 if (argc != 0 && argc != 1)
12633 usage_histedit();
12634 } else if (delete_backups) {
12635 if (abort_edit)
12636 option_conflict('X', 'a');
12637 if (allow_conflict)
12638 option_conflict('X', 'C');
12639 if (continue_edit)
12640 option_conflict('X', 'c');
12641 if (drop_only)
12642 option_conflict('X', 'd');
12643 if (edit_script_path)
12644 option_conflict('X', 'F');
12645 if (edit_logmsg_only)
12646 option_conflict('X', 'm');
12647 if (fold_only)
12648 option_conflict('X', 'f');
12649 if (edit_only)
12650 option_conflict('X', 'e');
12651 if (list_backups)
12652 option_conflict('X', 'l');
12653 if (argc != 0 && argc != 1)
12654 usage_histedit();
12655 } else if (allow_conflict && !continue_edit)
12656 errx(1, "-C option requires -c");
12657 else if (argc != 0)
12658 usage_histedit();
12661 * This command cannot apply unveil(2) in all cases because the
12662 * user may choose to run an editor to edit the histedit script
12663 * and to edit individual commit log messages.
12664 * unveil(2) traverses exec(2); if an editor is used we have to
12665 * apply unveil after edit script and log messages have been written.
12666 * XXX TODO: Make use of unveil(2) where possible.
12669 cwd = getcwd(NULL, 0);
12670 if (cwd == NULL) {
12671 error = got_error_from_errno("getcwd");
12672 goto done;
12675 error = got_repo_pack_fds_open(&pack_fds);
12676 if (error != NULL)
12677 goto done;
12679 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12680 if (error) {
12681 if (list_backups || delete_backups) {
12682 if (error->code != GOT_ERR_NOT_WORKTREE)
12683 goto done;
12684 } else {
12685 if (error->code == GOT_ERR_NOT_WORKTREE)
12686 error = wrap_not_worktree_error(error,
12687 "histedit", cwd);
12688 goto done;
12692 if (list_backups || delete_backups) {
12693 error = got_repo_open(&repo,
12694 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12695 NULL, pack_fds);
12696 if (error != NULL)
12697 goto done;
12698 error = apply_unveil(got_repo_get_path(repo), 0,
12699 worktree ? got_worktree_get_root_path(worktree) : NULL);
12700 if (error)
12701 goto done;
12702 error = process_backup_refs(
12703 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12704 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12705 goto done; /* nothing else to do */
12708 error = get_gitconfig_path(&gitconfig_path);
12709 if (error)
12710 goto done;
12711 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12712 gitconfig_path, pack_fds);
12713 if (error != NULL)
12714 goto done;
12716 if (worktree != NULL && !list_backups && !delete_backups) {
12717 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12718 if (error)
12719 goto done;
12722 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12723 if (error)
12724 goto done;
12725 if (rebase_in_progress) {
12726 error = got_error(GOT_ERR_REBASING);
12727 goto done;
12730 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12731 repo);
12732 if (error)
12733 goto done;
12734 if (merge_in_progress) {
12735 error = got_error(GOT_ERR_MERGE_BUSY);
12736 goto done;
12739 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12740 if (error)
12741 goto done;
12743 if (edit_in_progress && edit_logmsg_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 -m option can be used");
12748 goto done;
12750 if (edit_in_progress && drop_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 -d option can be used");
12755 goto done;
12757 if (edit_in_progress && fold_only) {
12758 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12759 "histedit operation is in progress in this "
12760 "work tree and must be continued or aborted "
12761 "before the -f option can be used");
12762 goto done;
12764 if (edit_in_progress && edit_only) {
12765 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12766 "histedit operation is in progress in this "
12767 "work tree and must be continued or aborted "
12768 "before the -e option can be used");
12769 goto done;
12772 if (edit_in_progress && abort_edit) {
12773 error = got_worktree_histedit_continue(&resume_commit_id,
12774 &tmp_branch, &branch, &base_commit_id, &fileindex,
12775 worktree, repo);
12776 if (error)
12777 goto done;
12778 printf("Switching work tree to %s\n",
12779 got_ref_get_symref_target(branch));
12780 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12781 branch, base_commit_id, abort_progress, &upa);
12782 if (error)
12783 goto done;
12784 printf("Histedit of %s aborted\n",
12785 got_ref_get_symref_target(branch));
12786 print_merge_progress_stats(&upa);
12787 goto done; /* nothing else to do */
12788 } else if (abort_edit) {
12789 error = got_error(GOT_ERR_NOT_HISTEDIT);
12790 goto done;
12793 error = get_author(&committer, repo, worktree);
12794 if (error)
12795 goto done;
12797 if (continue_edit) {
12798 char *path;
12800 if (!edit_in_progress) {
12801 error = got_error(GOT_ERR_NOT_HISTEDIT);
12802 goto done;
12805 error = got_worktree_get_histedit_script_path(&path, worktree);
12806 if (error)
12807 goto done;
12809 error = histedit_load_list(&histedit_cmds, path, repo);
12810 free(path);
12811 if (error)
12812 goto done;
12814 error = got_worktree_histedit_continue(&resume_commit_id,
12815 &tmp_branch, &branch, &base_commit_id, &fileindex,
12816 worktree, repo);
12817 if (error)
12818 goto done;
12820 error = got_ref_resolve(&head_commit_id, repo, branch);
12821 if (error)
12822 goto done;
12824 error = got_object_open_as_commit(&commit, repo,
12825 head_commit_id);
12826 if (error)
12827 goto done;
12828 parent_ids = got_object_commit_get_parent_ids(commit);
12829 pid = STAILQ_FIRST(parent_ids);
12830 if (pid == NULL) {
12831 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12832 goto done;
12834 error = collect_commits(&commits, head_commit_id, &pid->id,
12835 base_commit_id, got_worktree_get_path_prefix(worktree),
12836 GOT_ERR_HISTEDIT_PATH, repo);
12837 got_object_commit_close(commit);
12838 commit = NULL;
12839 if (error)
12840 goto done;
12841 } else {
12842 if (edit_in_progress) {
12843 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12844 goto done;
12847 error = got_ref_open(&branch, repo,
12848 got_worktree_get_head_ref_name(worktree), 0);
12849 if (error != NULL)
12850 goto done;
12852 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12853 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12854 "will not edit commit history of a branch outside "
12855 "the \"refs/heads/\" reference namespace");
12856 goto done;
12859 error = got_ref_resolve(&head_commit_id, repo, branch);
12860 got_ref_close(branch);
12861 branch = NULL;
12862 if (error)
12863 goto done;
12865 error = got_object_open_as_commit(&commit, repo,
12866 head_commit_id);
12867 if (error)
12868 goto done;
12869 parent_ids = got_object_commit_get_parent_ids(commit);
12870 pid = STAILQ_FIRST(parent_ids);
12871 if (pid == NULL) {
12872 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12873 goto done;
12875 error = collect_commits(&commits, head_commit_id, &pid->id,
12876 got_worktree_get_base_commit_id(worktree),
12877 got_worktree_get_path_prefix(worktree),
12878 GOT_ERR_HISTEDIT_PATH, repo);
12879 got_object_commit_close(commit);
12880 commit = NULL;
12881 if (error)
12882 goto done;
12884 if (STAILQ_EMPTY(&commits)) {
12885 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12886 goto done;
12889 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12890 &base_commit_id, &fileindex, worktree, repo);
12891 if (error)
12892 goto done;
12894 if (edit_script_path) {
12895 error = histedit_load_list(&histedit_cmds,
12896 edit_script_path, repo);
12897 if (error) {
12898 got_worktree_histedit_abort(worktree, fileindex,
12899 repo, branch, base_commit_id,
12900 abort_progress, &upa);
12901 print_merge_progress_stats(&upa);
12902 goto done;
12904 } else {
12905 const char *branch_name;
12906 branch_name = got_ref_get_symref_target(branch);
12907 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12908 branch_name += 11;
12909 error = histedit_edit_script(&histedit_cmds, &commits,
12910 branch_name, edit_logmsg_only, fold_only,
12911 drop_only, edit_only, repo);
12912 if (error) {
12913 got_worktree_histedit_abort(worktree, fileindex,
12914 repo, branch, base_commit_id,
12915 abort_progress, &upa);
12916 print_merge_progress_stats(&upa);
12917 goto done;
12922 error = histedit_save_list(&histedit_cmds, worktree,
12923 repo);
12924 if (error) {
12925 got_worktree_histedit_abort(worktree, fileindex,
12926 repo, branch, base_commit_id,
12927 abort_progress, &upa);
12928 print_merge_progress_stats(&upa);
12929 goto done;
12934 error = histedit_check_script(&histedit_cmds, &commits, repo);
12935 if (error)
12936 goto done;
12938 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12939 if (resume_commit_id) {
12940 if (got_object_id_cmp(hle->commit_id,
12941 resume_commit_id) != 0)
12942 continue;
12944 resume_commit_id = NULL;
12945 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12946 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12947 error = histedit_skip_commit(hle, worktree,
12948 repo);
12949 if (error)
12950 goto done;
12951 } else {
12952 struct got_pathlist_head paths;
12953 int have_changes = 0;
12955 TAILQ_INIT(&paths);
12956 error = got_pathlist_append(&paths, "", NULL);
12957 if (error)
12958 goto done;
12959 error = got_worktree_status(worktree, &paths,
12960 repo, 0, check_local_changes, &have_changes,
12961 check_cancelled, NULL);
12962 got_pathlist_free(&paths,
12963 GOT_PATHLIST_FREE_NONE);
12964 if (error) {
12965 if (error->code != GOT_ERR_CANCELLED)
12966 goto done;
12967 if (sigint_received || sigpipe_received)
12968 goto done;
12970 if (have_changes) {
12971 error = histedit_commit(NULL, worktree,
12972 fileindex, tmp_branch, hle,
12973 committer, allow_conflict, repo);
12974 if (error)
12975 goto done;
12976 } else {
12977 error = got_object_open_as_commit(
12978 &commit, repo, hle->commit_id);
12979 if (error)
12980 goto done;
12981 error = show_histedit_progress(commit,
12982 hle, NULL);
12983 got_object_commit_close(commit);
12984 commit = NULL;
12985 if (error)
12986 goto done;
12989 continue;
12992 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12993 error = histedit_skip_commit(hle, worktree, repo);
12994 if (error)
12995 goto done;
12996 continue;
12999 error = got_object_open_as_commit(&commit, repo,
13000 hle->commit_id);
13001 if (error)
13002 goto done;
13003 parent_ids = got_object_commit_get_parent_ids(commit);
13004 pid = STAILQ_FIRST(parent_ids);
13006 error = got_worktree_histedit_merge_files(&merged_paths,
13007 worktree, fileindex, &pid->id, hle->commit_id, repo,
13008 update_progress, &upa, check_cancelled, NULL);
13009 if (error)
13010 goto done;
13011 got_object_commit_close(commit);
13012 commit = NULL;
13014 print_merge_progress_stats(&upa);
13015 if (upa.conflicts > 0 || upa.missing > 0 ||
13016 upa.not_deleted > 0 || upa.unversioned > 0) {
13017 if (upa.conflicts > 0) {
13018 error = show_rebase_merge_conflict(
13019 hle->commit_id, repo);
13020 if (error)
13021 goto done;
13023 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13024 break;
13027 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13028 char *id_str;
13029 error = got_object_id_str(&id_str, hle->commit_id);
13030 if (error)
13031 goto done;
13032 printf("Stopping histedit for amending commit %s\n",
13033 id_str);
13034 free(id_str);
13035 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13036 error = got_worktree_histedit_postpone(worktree,
13037 fileindex);
13038 goto done;
13041 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13042 error = histedit_skip_commit(hle, worktree, repo);
13043 if (error)
13044 goto done;
13045 continue;
13048 error = histedit_commit(&merged_paths, worktree, fileindex,
13049 tmp_branch, hle, committer, allow_conflict, repo);
13050 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13051 if (error)
13052 goto done;
13055 if (upa.conflicts > 0 || upa.missing > 0 ||
13056 upa.not_deleted > 0 || upa.unversioned > 0) {
13057 error = got_worktree_histedit_postpone(worktree, fileindex);
13058 if (error)
13059 goto done;
13060 if (upa.conflicts > 0 && upa.missing == 0 &&
13061 upa.not_deleted == 0 && upa.unversioned == 0) {
13062 error = got_error_msg(GOT_ERR_CONFLICTS,
13063 "conflicts must be resolved before histedit "
13064 "can continue");
13065 } else if (upa.conflicts > 0) {
13066 error = got_error_msg(GOT_ERR_CONFLICTS,
13067 "conflicts must be resolved before histedit "
13068 "can continue; changes destined for some "
13069 "files were not yet merged and should be "
13070 "merged manually if required before the "
13071 "histedit operation is continued");
13072 } else {
13073 error = got_error_msg(GOT_ERR_CONFLICTS,
13074 "changes destined for some files were not "
13075 "yet merged and should be merged manually "
13076 "if required before the histedit operation "
13077 "is continued");
13079 } else
13080 error = histedit_complete(worktree, fileindex, tmp_branch,
13081 branch, repo);
13082 done:
13083 free(cwd);
13084 free(committer);
13085 free(gitconfig_path);
13086 got_object_id_queue_free(&commits);
13087 histedit_free_list(&histedit_cmds);
13088 free(head_commit_id);
13089 free(base_commit_id);
13090 free(resume_commit_id);
13091 if (commit)
13092 got_object_commit_close(commit);
13093 if (branch)
13094 got_ref_close(branch);
13095 if (tmp_branch)
13096 got_ref_close(tmp_branch);
13097 if (worktree)
13098 got_worktree_close(worktree);
13099 if (repo) {
13100 const struct got_error *close_err = got_repo_close(repo);
13101 if (error == NULL)
13102 error = close_err;
13104 if (pack_fds) {
13105 const struct got_error *pack_err =
13106 got_repo_pack_fds_close(pack_fds);
13107 if (error == NULL)
13108 error = pack_err;
13110 return error;
13113 __dead static void
13114 usage_integrate(void)
13116 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13117 exit(1);
13120 static const struct got_error *
13121 cmd_integrate(int argc, char *argv[])
13123 const struct got_error *error = NULL;
13124 struct got_repository *repo = NULL;
13125 struct got_worktree *worktree = NULL;
13126 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13127 const char *branch_arg = NULL;
13128 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13129 struct got_fileindex *fileindex = NULL;
13130 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13131 int ch;
13132 struct got_update_progress_arg upa;
13133 int *pack_fds = NULL;
13135 #ifndef PROFILE
13136 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13137 "unveil", NULL) == -1)
13138 err(1, "pledge");
13139 #endif
13141 while ((ch = getopt(argc, argv, "")) != -1) {
13142 switch (ch) {
13143 default:
13144 usage_integrate();
13145 /* NOTREACHED */
13149 argc -= optind;
13150 argv += optind;
13152 if (argc != 1)
13153 usage_integrate();
13154 branch_arg = argv[0];
13156 cwd = getcwd(NULL, 0);
13157 if (cwd == NULL) {
13158 error = got_error_from_errno("getcwd");
13159 goto done;
13162 error = got_repo_pack_fds_open(&pack_fds);
13163 if (error != NULL)
13164 goto done;
13166 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13167 if (error) {
13168 if (error->code == GOT_ERR_NOT_WORKTREE)
13169 error = wrap_not_worktree_error(error, "integrate",
13170 cwd);
13171 goto done;
13174 error = check_rebase_or_histedit_in_progress(worktree);
13175 if (error)
13176 goto done;
13178 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13179 NULL, pack_fds);
13180 if (error != NULL)
13181 goto done;
13183 error = apply_unveil(got_repo_get_path(repo), 0,
13184 got_worktree_get_root_path(worktree));
13185 if (error)
13186 goto done;
13188 error = check_merge_in_progress(worktree, repo);
13189 if (error)
13190 goto done;
13192 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13193 error = got_error_from_errno("asprintf");
13194 goto done;
13197 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13198 &base_branch_ref, worktree, refname, repo);
13199 if (error)
13200 goto done;
13202 refname = strdup(got_ref_get_name(branch_ref));
13203 if (refname == NULL) {
13204 error = got_error_from_errno("strdup");
13205 got_worktree_integrate_abort(worktree, fileindex, repo,
13206 branch_ref, base_branch_ref);
13207 goto done;
13209 base_refname = strdup(got_ref_get_name(base_branch_ref));
13210 if (base_refname == NULL) {
13211 error = got_error_from_errno("strdup");
13212 got_worktree_integrate_abort(worktree, fileindex, repo,
13213 branch_ref, base_branch_ref);
13214 goto done;
13216 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13217 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13218 got_worktree_integrate_abort(worktree, fileindex, repo,
13219 branch_ref, base_branch_ref);
13220 goto done;
13223 error = got_ref_resolve(&commit_id, repo, branch_ref);
13224 if (error)
13225 goto done;
13227 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13228 if (error)
13229 goto done;
13231 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13232 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13233 "specified branch has already been integrated");
13234 got_worktree_integrate_abort(worktree, fileindex, repo,
13235 branch_ref, base_branch_ref);
13236 goto done;
13239 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13240 if (error) {
13241 if (error->code == GOT_ERR_ANCESTRY)
13242 error = got_error(GOT_ERR_REBASE_REQUIRED);
13243 got_worktree_integrate_abort(worktree, fileindex, repo,
13244 branch_ref, base_branch_ref);
13245 goto done;
13248 memset(&upa, 0, sizeof(upa));
13249 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13250 branch_ref, base_branch_ref, update_progress, &upa,
13251 check_cancelled, NULL);
13252 if (error)
13253 goto done;
13255 printf("Integrated %s into %s\n", refname, base_refname);
13256 print_update_progress_stats(&upa);
13257 done:
13258 if (repo) {
13259 const struct got_error *close_err = got_repo_close(repo);
13260 if (error == NULL)
13261 error = close_err;
13263 if (worktree)
13264 got_worktree_close(worktree);
13265 if (pack_fds) {
13266 const struct got_error *pack_err =
13267 got_repo_pack_fds_close(pack_fds);
13268 if (error == NULL)
13269 error = pack_err;
13271 free(cwd);
13272 free(base_commit_id);
13273 free(commit_id);
13274 free(refname);
13275 free(base_refname);
13276 return error;
13279 __dead static void
13280 usage_merge(void)
13282 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13283 exit(1);
13286 static const struct got_error *
13287 cmd_merge(int argc, char *argv[])
13289 const struct got_error *error = NULL;
13290 struct got_worktree *worktree = NULL;
13291 struct got_repository *repo = NULL;
13292 struct got_fileindex *fileindex = NULL;
13293 char *cwd = NULL, *id_str = NULL, *author = NULL;
13294 char *gitconfig_path = NULL;
13295 struct got_reference *branch = NULL, *wt_branch = NULL;
13296 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13297 struct got_object_id *wt_branch_tip = NULL;
13298 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13299 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13300 struct got_update_progress_arg upa;
13301 struct got_object_id *merge_commit_id = NULL;
13302 char *branch_name = NULL;
13303 int *pack_fds = NULL;
13305 memset(&upa, 0, sizeof(upa));
13307 #ifndef PROFILE
13308 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13309 "unveil", NULL) == -1)
13310 err(1, "pledge");
13311 #endif
13313 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13314 switch (ch) {
13315 case 'a':
13316 abort_merge = 1;
13317 break;
13318 case 'C':
13319 allow_conflict = 1;
13320 break;
13321 case 'c':
13322 continue_merge = 1;
13323 break;
13324 case 'M':
13325 prefer_fast_forward = 0;
13326 break;
13327 case 'n':
13328 interrupt_merge = 1;
13329 break;
13330 default:
13331 usage_merge();
13332 /* NOTREACHED */
13336 argc -= optind;
13337 argv += optind;
13339 if (abort_merge) {
13340 if (continue_merge)
13341 option_conflict('a', 'c');
13342 if (!prefer_fast_forward)
13343 option_conflict('a', 'M');
13344 if (interrupt_merge)
13345 option_conflict('a', 'n');
13346 } else if (continue_merge) {
13347 if (!prefer_fast_forward)
13348 option_conflict('c', 'M');
13349 if (interrupt_merge)
13350 option_conflict('c', 'n');
13352 if (allow_conflict) {
13353 if (!continue_merge)
13354 errx(1, "-C option requires -c");
13356 if (abort_merge || continue_merge) {
13357 if (argc != 0)
13358 usage_merge();
13359 } else if (argc != 1)
13360 usage_merge();
13362 cwd = getcwd(NULL, 0);
13363 if (cwd == NULL) {
13364 error = got_error_from_errno("getcwd");
13365 goto done;
13368 error = got_repo_pack_fds_open(&pack_fds);
13369 if (error != NULL)
13370 goto done;
13372 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13373 if (error) {
13374 if (error->code == GOT_ERR_NOT_WORKTREE)
13375 error = wrap_not_worktree_error(error,
13376 "merge", cwd);
13377 goto done;
13380 error = get_gitconfig_path(&gitconfig_path);
13381 if (error)
13382 goto done;
13383 error = got_repo_open(&repo,
13384 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13385 gitconfig_path, pack_fds);
13386 if (error != NULL)
13387 goto done;
13389 if (worktree != NULL) {
13390 error = worktree_has_logmsg_ref("merge", worktree, repo);
13391 if (error)
13392 goto done;
13395 error = apply_unveil(got_repo_get_path(repo), 0,
13396 worktree ? got_worktree_get_root_path(worktree) : NULL);
13397 if (error)
13398 goto done;
13400 error = check_rebase_or_histedit_in_progress(worktree);
13401 if (error)
13402 goto done;
13404 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13405 repo);
13406 if (error)
13407 goto done;
13409 if (merge_in_progress && !(abort_merge || continue_merge)) {
13410 error = got_error(GOT_ERR_MERGE_BUSY);
13411 goto done;
13414 if (!merge_in_progress && (abort_merge || continue_merge)) {
13415 error = got_error(GOT_ERR_NOT_MERGING);
13416 goto done;
13419 if (abort_merge) {
13420 error = got_worktree_merge_continue(&branch_name,
13421 &branch_tip, &fileindex, worktree, repo);
13422 if (error)
13423 goto done;
13424 error = got_worktree_merge_abort(worktree, fileindex, repo,
13425 abort_progress, &upa);
13426 if (error)
13427 goto done;
13428 printf("Merge of %s aborted\n", branch_name);
13429 goto done; /* nothing else to do */
13432 if (strncmp(got_worktree_get_head_ref_name(worktree),
13433 "refs/heads/", 11) != 0) {
13434 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13435 "work tree's current branch %s is outside the "
13436 "\"refs/heads/\" reference namespace; "
13437 "update -b required",
13438 got_worktree_get_head_ref_name(worktree));
13439 goto done;
13442 error = get_author(&author, repo, worktree);
13443 if (error)
13444 goto done;
13446 error = got_ref_open(&wt_branch, repo,
13447 got_worktree_get_head_ref_name(worktree), 0);
13448 if (error)
13449 goto done;
13450 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13451 if (error)
13452 goto done;
13454 if (continue_merge) {
13455 struct got_object_id *base_commit_id;
13456 base_commit_id = got_worktree_get_base_commit_id(worktree);
13457 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13458 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13459 goto done;
13461 error = got_worktree_merge_continue(&branch_name,
13462 &branch_tip, &fileindex, worktree, repo);
13463 if (error)
13464 goto done;
13465 } else {
13466 error = got_ref_open(&branch, repo, argv[0], 0);
13467 if (error != NULL)
13468 goto done;
13469 branch_name = strdup(got_ref_get_name(branch));
13470 if (branch_name == NULL) {
13471 error = got_error_from_errno("strdup");
13472 goto done;
13474 error = got_ref_resolve(&branch_tip, repo, branch);
13475 if (error)
13476 goto done;
13479 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13480 wt_branch_tip, branch_tip, 0, repo,
13481 check_cancelled, NULL);
13482 if (error && error->code != GOT_ERR_ANCESTRY)
13483 goto done;
13485 if (!continue_merge) {
13486 error = check_path_prefix(wt_branch_tip, branch_tip,
13487 got_worktree_get_path_prefix(worktree),
13488 GOT_ERR_MERGE_PATH, repo);
13489 if (error)
13490 goto done;
13491 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13492 if (error)
13493 goto done;
13494 if (prefer_fast_forward && yca_id &&
13495 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13496 struct got_pathlist_head paths;
13497 if (interrupt_merge) {
13498 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13499 "there are no changes to merge since %s "
13500 "is already based on %s; merge cannot be "
13501 "interrupted for amending; -n",
13502 branch_name, got_ref_get_name(wt_branch));
13503 goto done;
13505 printf("Forwarding %s to %s\n",
13506 got_ref_get_name(wt_branch), branch_name);
13507 error = got_ref_change_ref(wt_branch, branch_tip);
13508 if (error)
13509 goto done;
13510 error = got_ref_write(wt_branch, repo);
13511 if (error)
13512 goto done;
13513 error = got_worktree_set_base_commit_id(worktree, repo,
13514 branch_tip);
13515 if (error)
13516 goto done;
13517 TAILQ_INIT(&paths);
13518 error = got_pathlist_append(&paths, "", NULL);
13519 if (error)
13520 goto done;
13521 error = got_worktree_checkout_files(worktree,
13522 &paths, repo, update_progress, &upa,
13523 check_cancelled, NULL);
13524 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13525 if (error)
13526 goto done;
13527 if (upa.did_something) {
13528 char *id_str;
13529 error = got_object_id_str(&id_str, branch_tip);
13530 if (error)
13531 goto done;
13532 printf("Updated to commit %s\n", id_str);
13533 free(id_str);
13534 } else
13535 printf("Already up-to-date\n");
13536 print_update_progress_stats(&upa);
13537 goto done;
13539 error = got_worktree_merge_write_refs(worktree, branch, repo);
13540 if (error)
13541 goto done;
13543 error = got_worktree_merge_branch(worktree, fileindex,
13544 yca_id, branch_tip, repo, update_progress, &upa,
13545 check_cancelled, NULL);
13546 if (error)
13547 goto done;
13548 print_merge_progress_stats(&upa);
13549 if (!upa.did_something) {
13550 error = got_worktree_merge_abort(worktree, fileindex,
13551 repo, abort_progress, &upa);
13552 if (error)
13553 goto done;
13554 printf("Already up-to-date\n");
13555 goto done;
13559 if (interrupt_merge) {
13560 error = got_worktree_merge_postpone(worktree, fileindex);
13561 if (error)
13562 goto done;
13563 printf("Merge of %s interrupted on request\n", branch_name);
13564 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13565 upa.not_deleted > 0 || upa.unversioned > 0) {
13566 error = got_worktree_merge_postpone(worktree, fileindex);
13567 if (error)
13568 goto done;
13569 if (upa.conflicts > 0 && upa.missing == 0 &&
13570 upa.not_deleted == 0 && upa.unversioned == 0) {
13571 error = got_error_msg(GOT_ERR_CONFLICTS,
13572 "conflicts must be resolved before merging "
13573 "can continue");
13574 } else if (upa.conflicts > 0) {
13575 error = got_error_msg(GOT_ERR_CONFLICTS,
13576 "conflicts must be resolved before merging "
13577 "can continue; changes destined for some "
13578 "files were not yet merged and "
13579 "should be merged manually if required before the "
13580 "merge operation is continued");
13581 } else {
13582 error = got_error_msg(GOT_ERR_CONFLICTS,
13583 "changes destined for some "
13584 "files were not yet merged and should be "
13585 "merged manually if required before the "
13586 "merge operation is continued");
13588 goto done;
13589 } else {
13590 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13591 fileindex, author, NULL, 1, branch_tip, branch_name,
13592 allow_conflict, repo, continue_merge ? print_status : NULL,
13593 NULL);
13594 if (error)
13595 goto done;
13596 error = got_worktree_merge_complete(worktree, fileindex, repo);
13597 if (error)
13598 goto done;
13599 error = got_object_id_str(&id_str, merge_commit_id);
13600 if (error)
13601 goto done;
13602 printf("Merged %s into %s: %s\n", branch_name,
13603 got_worktree_get_head_ref_name(worktree),
13604 id_str);
13607 done:
13608 free(gitconfig_path);
13609 free(id_str);
13610 free(merge_commit_id);
13611 free(author);
13612 free(branch_tip);
13613 free(branch_name);
13614 free(yca_id);
13615 if (branch)
13616 got_ref_close(branch);
13617 if (wt_branch)
13618 got_ref_close(wt_branch);
13619 if (worktree)
13620 got_worktree_close(worktree);
13621 if (repo) {
13622 const struct got_error *close_err = got_repo_close(repo);
13623 if (error == NULL)
13624 error = close_err;
13626 if (pack_fds) {
13627 const struct got_error *pack_err =
13628 got_repo_pack_fds_close(pack_fds);
13629 if (error == NULL)
13630 error = pack_err;
13632 return error;
13635 __dead static void
13636 usage_stage(void)
13638 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13639 "[path ...]\n", getprogname());
13640 exit(1);
13643 static const struct got_error *
13644 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13645 const char *path, struct got_object_id *blob_id,
13646 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13647 int dirfd, const char *de_name)
13649 const struct got_error *err = NULL;
13650 char *id_str = NULL;
13652 if (staged_status != GOT_STATUS_ADD &&
13653 staged_status != GOT_STATUS_MODIFY &&
13654 staged_status != GOT_STATUS_DELETE)
13655 return NULL;
13657 if (staged_status == GOT_STATUS_ADD ||
13658 staged_status == GOT_STATUS_MODIFY)
13659 err = got_object_id_str(&id_str, staged_blob_id);
13660 else
13661 err = got_object_id_str(&id_str, blob_id);
13662 if (err)
13663 return err;
13665 printf("%s %c %s\n", id_str, staged_status, path);
13666 free(id_str);
13667 return NULL;
13670 static const struct got_error *
13671 cmd_stage(int argc, char *argv[])
13673 const struct got_error *error = NULL;
13674 struct got_repository *repo = NULL;
13675 struct got_worktree *worktree = NULL;
13676 char *cwd = NULL;
13677 struct got_pathlist_head paths;
13678 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13679 FILE *patch_script_file = NULL;
13680 const char *patch_script_path = NULL;
13681 struct choose_patch_arg cpa;
13682 int *pack_fds = NULL;
13684 TAILQ_INIT(&paths);
13686 #ifndef PROFILE
13687 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13688 "unveil", NULL) == -1)
13689 err(1, "pledge");
13690 #endif
13692 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13693 switch (ch) {
13694 case 'F':
13695 patch_script_path = optarg;
13696 break;
13697 case 'l':
13698 list_stage = 1;
13699 break;
13700 case 'p':
13701 pflag = 1;
13702 break;
13703 case 'S':
13704 allow_bad_symlinks = 1;
13705 break;
13706 default:
13707 usage_stage();
13708 /* NOTREACHED */
13712 argc -= optind;
13713 argv += optind;
13715 if (list_stage && (pflag || patch_script_path))
13716 errx(1, "-l option cannot be used with other options");
13717 if (patch_script_path && !pflag)
13718 errx(1, "-F option can only be used together with -p option");
13720 cwd = getcwd(NULL, 0);
13721 if (cwd == NULL) {
13722 error = got_error_from_errno("getcwd");
13723 goto done;
13726 error = got_repo_pack_fds_open(&pack_fds);
13727 if (error != NULL)
13728 goto done;
13730 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13731 if (error) {
13732 if (error->code == GOT_ERR_NOT_WORKTREE)
13733 error = wrap_not_worktree_error(error, "stage", cwd);
13734 goto done;
13737 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13738 NULL, pack_fds);
13739 if (error != NULL)
13740 goto done;
13742 if (patch_script_path) {
13743 patch_script_file = fopen(patch_script_path, "re");
13744 if (patch_script_file == NULL) {
13745 error = got_error_from_errno2("fopen",
13746 patch_script_path);
13747 goto done;
13750 error = apply_unveil(got_repo_get_path(repo), 0,
13751 got_worktree_get_root_path(worktree));
13752 if (error)
13753 goto done;
13755 error = check_merge_in_progress(worktree, repo);
13756 if (error)
13757 goto done;
13759 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13760 if (error)
13761 goto done;
13763 if (list_stage)
13764 error = got_worktree_status(worktree, &paths, repo, 0,
13765 print_stage, NULL, check_cancelled, NULL);
13766 else {
13767 cpa.patch_script_file = patch_script_file;
13768 cpa.action = "stage";
13769 error = got_worktree_stage(worktree, &paths,
13770 pflag ? NULL : print_status, NULL,
13771 pflag ? choose_patch : NULL, &cpa,
13772 allow_bad_symlinks, repo);
13774 done:
13775 if (patch_script_file && fclose(patch_script_file) == EOF &&
13776 error == NULL)
13777 error = got_error_from_errno2("fclose", patch_script_path);
13778 if (repo) {
13779 const struct got_error *close_err = got_repo_close(repo);
13780 if (error == NULL)
13781 error = close_err;
13783 if (worktree)
13784 got_worktree_close(worktree);
13785 if (pack_fds) {
13786 const struct got_error *pack_err =
13787 got_repo_pack_fds_close(pack_fds);
13788 if (error == NULL)
13789 error = pack_err;
13791 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13792 free(cwd);
13793 return error;
13796 __dead static void
13797 usage_unstage(void)
13799 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13800 "[path ...]\n", getprogname());
13801 exit(1);
13805 static const struct got_error *
13806 cmd_unstage(int argc, char *argv[])
13808 const struct got_error *error = NULL;
13809 struct got_repository *repo = NULL;
13810 struct got_worktree *worktree = NULL;
13811 char *cwd = NULL;
13812 struct got_pathlist_head paths;
13813 int ch, pflag = 0;
13814 struct got_update_progress_arg upa;
13815 FILE *patch_script_file = NULL;
13816 const char *patch_script_path = NULL;
13817 struct choose_patch_arg cpa;
13818 int *pack_fds = NULL;
13820 TAILQ_INIT(&paths);
13822 #ifndef PROFILE
13823 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13824 "unveil", NULL) == -1)
13825 err(1, "pledge");
13826 #endif
13828 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13829 switch (ch) {
13830 case 'F':
13831 patch_script_path = optarg;
13832 break;
13833 case 'p':
13834 pflag = 1;
13835 break;
13836 default:
13837 usage_unstage();
13838 /* NOTREACHED */
13842 argc -= optind;
13843 argv += optind;
13845 if (patch_script_path && !pflag)
13846 errx(1, "-F option can only be used together with -p option");
13848 cwd = getcwd(NULL, 0);
13849 if (cwd == NULL) {
13850 error = got_error_from_errno("getcwd");
13851 goto done;
13854 error = got_repo_pack_fds_open(&pack_fds);
13855 if (error != NULL)
13856 goto done;
13858 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13859 if (error) {
13860 if (error->code == GOT_ERR_NOT_WORKTREE)
13861 error = wrap_not_worktree_error(error, "unstage", cwd);
13862 goto done;
13865 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13866 NULL, pack_fds);
13867 if (error != NULL)
13868 goto done;
13870 if (patch_script_path) {
13871 patch_script_file = fopen(patch_script_path, "re");
13872 if (patch_script_file == NULL) {
13873 error = got_error_from_errno2("fopen",
13874 patch_script_path);
13875 goto done;
13879 error = apply_unveil(got_repo_get_path(repo), 0,
13880 got_worktree_get_root_path(worktree));
13881 if (error)
13882 goto done;
13884 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13885 if (error)
13886 goto done;
13888 cpa.patch_script_file = patch_script_file;
13889 cpa.action = "unstage";
13890 memset(&upa, 0, sizeof(upa));
13891 error = got_worktree_unstage(worktree, &paths, update_progress,
13892 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13893 if (!error)
13894 print_merge_progress_stats(&upa);
13895 done:
13896 if (patch_script_file && fclose(patch_script_file) == EOF &&
13897 error == NULL)
13898 error = got_error_from_errno2("fclose", patch_script_path);
13899 if (repo) {
13900 const struct got_error *close_err = got_repo_close(repo);
13901 if (error == NULL)
13902 error = close_err;
13904 if (worktree)
13905 got_worktree_close(worktree);
13906 if (pack_fds) {
13907 const struct got_error *pack_err =
13908 got_repo_pack_fds_close(pack_fds);
13909 if (error == NULL)
13910 error = pack_err;
13912 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13913 free(cwd);
13914 return error;
13917 __dead static void
13918 usage_cat(void)
13920 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13921 "arg ...\n", getprogname());
13922 exit(1);
13925 static const struct got_error *
13926 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13928 const struct got_error *err;
13929 struct got_blob_object *blob;
13930 int fd = -1;
13932 fd = got_opentempfd();
13933 if (fd == -1)
13934 return got_error_from_errno("got_opentempfd");
13936 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13937 if (err)
13938 goto done;
13940 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13941 done:
13942 if (fd != -1 && close(fd) == -1 && err == NULL)
13943 err = got_error_from_errno("close");
13944 if (blob)
13945 got_object_blob_close(blob);
13946 return err;
13949 static const struct got_error *
13950 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13952 const struct got_error *err;
13953 struct got_tree_object *tree;
13954 int nentries, i;
13956 err = got_object_open_as_tree(&tree, repo, id);
13957 if (err)
13958 return err;
13960 nentries = got_object_tree_get_nentries(tree);
13961 for (i = 0; i < nentries; i++) {
13962 struct got_tree_entry *te;
13963 char *id_str;
13964 if (sigint_received || sigpipe_received)
13965 break;
13966 te = got_object_tree_get_entry(tree, i);
13967 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13968 if (err)
13969 break;
13970 fprintf(outfile, "%s %.7o %s\n", id_str,
13971 got_tree_entry_get_mode(te),
13972 got_tree_entry_get_name(te));
13973 free(id_str);
13976 got_object_tree_close(tree);
13977 return err;
13980 static const struct got_error *
13981 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13983 const struct got_error *err;
13984 struct got_commit_object *commit;
13985 const struct got_object_id_queue *parent_ids;
13986 struct got_object_qid *pid;
13987 char *id_str = NULL;
13988 const char *logmsg = NULL;
13989 char gmtoff[6];
13991 err = got_object_open_as_commit(&commit, repo, id);
13992 if (err)
13993 return err;
13995 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13996 if (err)
13997 goto done;
13999 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14000 parent_ids = got_object_commit_get_parent_ids(commit);
14001 fprintf(outfile, "numparents %d\n",
14002 got_object_commit_get_nparents(commit));
14003 STAILQ_FOREACH(pid, parent_ids, entry) {
14004 char *pid_str;
14005 err = got_object_id_str(&pid_str, &pid->id);
14006 if (err)
14007 goto done;
14008 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14009 free(pid_str);
14011 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14012 got_object_commit_get_author_gmtoff(commit));
14013 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14014 got_object_commit_get_author(commit),
14015 (long long)got_object_commit_get_author_time(commit),
14016 gmtoff);
14018 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14019 got_object_commit_get_committer_gmtoff(commit));
14020 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14021 got_object_commit_get_committer(commit),
14022 (long long)got_object_commit_get_committer_time(commit),
14023 gmtoff);
14025 logmsg = got_object_commit_get_logmsg_raw(commit);
14026 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14027 fprintf(outfile, "%s", logmsg);
14028 done:
14029 free(id_str);
14030 got_object_commit_close(commit);
14031 return err;
14034 static const struct got_error *
14035 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14037 const struct got_error *err;
14038 struct got_tag_object *tag;
14039 char *id_str = NULL;
14040 const char *tagmsg = NULL;
14041 char gmtoff[6];
14043 err = got_object_open_as_tag(&tag, repo, id);
14044 if (err)
14045 return err;
14047 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14048 if (err)
14049 goto done;
14051 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14053 switch (got_object_tag_get_object_type(tag)) {
14054 case GOT_OBJ_TYPE_BLOB:
14055 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14056 GOT_OBJ_LABEL_BLOB);
14057 break;
14058 case GOT_OBJ_TYPE_TREE:
14059 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14060 GOT_OBJ_LABEL_TREE);
14061 break;
14062 case GOT_OBJ_TYPE_COMMIT:
14063 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14064 GOT_OBJ_LABEL_COMMIT);
14065 break;
14066 case GOT_OBJ_TYPE_TAG:
14067 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14068 GOT_OBJ_LABEL_TAG);
14069 break;
14070 default:
14071 break;
14074 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14075 got_object_tag_get_name(tag));
14077 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14078 got_object_tag_get_tagger_gmtoff(tag));
14079 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14080 got_object_tag_get_tagger(tag),
14081 (long long)got_object_tag_get_tagger_time(tag),
14082 gmtoff);
14084 tagmsg = got_object_tag_get_message(tag);
14085 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14086 fprintf(outfile, "%s", tagmsg);
14087 done:
14088 free(id_str);
14089 got_object_tag_close(tag);
14090 return err;
14093 static const struct got_error *
14094 cmd_cat(int argc, char *argv[])
14096 const struct got_error *error;
14097 struct got_repository *repo = NULL;
14098 struct got_worktree *worktree = NULL;
14099 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14100 char *keyword_idstr = NULL;
14101 const char *commit_id_str = NULL;
14102 struct got_object_id *id = NULL, *commit_id = NULL;
14103 struct got_commit_object *commit = NULL;
14104 int ch, obj_type, i, force_path = 0;
14105 struct got_reflist_head refs;
14106 int *pack_fds = NULL;
14108 TAILQ_INIT(&refs);
14110 #ifndef PROFILE
14111 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14112 NULL) == -1)
14113 err(1, "pledge");
14114 #endif
14116 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14117 switch (ch) {
14118 case 'c':
14119 commit_id_str = optarg;
14120 break;
14121 case 'P':
14122 force_path = 1;
14123 break;
14124 case 'r':
14125 repo_path = realpath(optarg, NULL);
14126 if (repo_path == NULL)
14127 return got_error_from_errno2("realpath",
14128 optarg);
14129 got_path_strip_trailing_slashes(repo_path);
14130 break;
14131 default:
14132 usage_cat();
14133 /* NOTREACHED */
14137 argc -= optind;
14138 argv += optind;
14140 cwd = getcwd(NULL, 0);
14141 if (cwd == NULL) {
14142 error = got_error_from_errno("getcwd");
14143 goto done;
14146 error = got_repo_pack_fds_open(&pack_fds);
14147 if (error != NULL)
14148 goto done;
14150 if (repo_path == NULL) {
14151 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14152 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14153 goto done;
14154 if (worktree) {
14155 repo_path = strdup(
14156 got_worktree_get_repo_path(worktree));
14157 if (repo_path == NULL) {
14158 error = got_error_from_errno("strdup");
14159 goto done;
14162 if (commit_id_str == NULL) {
14163 /* Release work tree lock. */
14164 got_worktree_close(worktree);
14165 worktree = NULL;
14170 if (repo_path == NULL) {
14171 repo_path = strdup(cwd);
14172 if (repo_path == NULL)
14173 return got_error_from_errno("strdup");
14176 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14177 free(repo_path);
14178 if (error != NULL)
14179 goto done;
14181 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14182 if (error)
14183 goto done;
14185 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14186 if (error)
14187 goto done;
14189 if (commit_id_str != NULL) {
14190 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14191 repo, worktree);
14192 if (error != NULL)
14193 goto done;
14194 if (keyword_idstr != NULL)
14195 commit_id_str = keyword_idstr;
14196 if (worktree != NULL) {
14197 got_worktree_close(worktree);
14198 worktree = NULL;
14200 } else
14201 commit_id_str = GOT_REF_HEAD;
14202 error = got_repo_match_object_id(&commit_id, NULL,
14203 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14204 if (error)
14205 goto done;
14207 error = got_object_open_as_commit(&commit, repo, commit_id);
14208 if (error)
14209 goto done;
14211 for (i = 0; i < argc; i++) {
14212 if (force_path) {
14213 error = got_object_id_by_path(&id, repo, commit,
14214 argv[i]);
14215 if (error)
14216 break;
14217 } else {
14218 error = got_repo_match_object_id(&id, &label, argv[i],
14219 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14220 repo);
14221 if (error) {
14222 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14223 error->code != GOT_ERR_NOT_REF)
14224 break;
14225 error = got_object_id_by_path(&id, repo,
14226 commit, argv[i]);
14227 if (error)
14228 break;
14232 error = got_object_get_type(&obj_type, repo, id);
14233 if (error)
14234 break;
14236 switch (obj_type) {
14237 case GOT_OBJ_TYPE_BLOB:
14238 error = cat_blob(id, repo, stdout);
14239 break;
14240 case GOT_OBJ_TYPE_TREE:
14241 error = cat_tree(id, repo, stdout);
14242 break;
14243 case GOT_OBJ_TYPE_COMMIT:
14244 error = cat_commit(id, repo, stdout);
14245 break;
14246 case GOT_OBJ_TYPE_TAG:
14247 error = cat_tag(id, repo, stdout);
14248 break;
14249 default:
14250 error = got_error(GOT_ERR_OBJ_TYPE);
14251 break;
14253 if (error)
14254 break;
14255 free(label);
14256 label = NULL;
14257 free(id);
14258 id = NULL;
14260 done:
14261 free(label);
14262 free(id);
14263 free(commit_id);
14264 free(keyword_idstr);
14265 if (commit)
14266 got_object_commit_close(commit);
14267 if (worktree)
14268 got_worktree_close(worktree);
14269 if (repo) {
14270 const struct got_error *close_err = got_repo_close(repo);
14271 if (error == NULL)
14272 error = close_err;
14274 if (pack_fds) {
14275 const struct got_error *pack_err =
14276 got_repo_pack_fds_close(pack_fds);
14277 if (error == NULL)
14278 error = pack_err;
14281 got_ref_list_free(&refs);
14282 return error;
14285 __dead static void
14286 usage_info(void)
14288 fprintf(stderr, "usage: %s info [path ...]\n",
14289 getprogname());
14290 exit(1);
14293 static const struct got_error *
14294 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14295 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14296 struct got_object_id *commit_id)
14298 const struct got_error *err = NULL;
14299 char *id_str = NULL;
14300 char datebuf[128];
14301 struct tm mytm, *tm;
14302 struct got_pathlist_head *paths = arg;
14303 struct got_pathlist_entry *pe;
14306 * Clear error indication from any of the path arguments which
14307 * would cause this file index entry to be displayed.
14309 TAILQ_FOREACH(pe, paths, entry) {
14310 if (got_path_cmp(path, pe->path, strlen(path),
14311 pe->path_len) == 0 ||
14312 got_path_is_child(path, pe->path, pe->path_len))
14313 pe->data = NULL; /* no error */
14316 printf(GOT_COMMIT_SEP_STR);
14317 if (S_ISLNK(mode))
14318 printf("symlink: %s\n", path);
14319 else if (S_ISREG(mode)) {
14320 printf("file: %s\n", path);
14321 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14322 } else if (S_ISDIR(mode))
14323 printf("directory: %s\n", path);
14324 else
14325 printf("something: %s\n", path);
14327 tm = localtime_r(&mtime, &mytm);
14328 if (tm == NULL)
14329 return NULL;
14330 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14331 return got_error(GOT_ERR_NO_SPACE);
14332 printf("timestamp: %s\n", datebuf);
14334 if (blob_id) {
14335 err = got_object_id_str(&id_str, blob_id);
14336 if (err)
14337 return err;
14338 printf("based on blob: %s\n", id_str);
14339 free(id_str);
14342 if (staged_blob_id) {
14343 err = got_object_id_str(&id_str, staged_blob_id);
14344 if (err)
14345 return err;
14346 printf("based on staged blob: %s\n", id_str);
14347 free(id_str);
14350 if (commit_id) {
14351 err = got_object_id_str(&id_str, commit_id);
14352 if (err)
14353 return err;
14354 printf("based on commit: %s\n", id_str);
14355 free(id_str);
14358 return NULL;
14361 static const struct got_error *
14362 cmd_info(int argc, char *argv[])
14364 const struct got_error *error = NULL;
14365 struct got_worktree *worktree = NULL;
14366 char *cwd = NULL, *id_str = NULL;
14367 struct got_pathlist_head paths;
14368 char *uuidstr = NULL;
14369 int ch, show_files = 0;
14371 TAILQ_INIT(&paths);
14373 #ifndef PROFILE
14374 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14375 NULL) == -1)
14376 err(1, "pledge");
14377 #endif
14379 while ((ch = getopt(argc, argv, "")) != -1) {
14380 switch (ch) {
14381 default:
14382 usage_info();
14383 /* NOTREACHED */
14387 argc -= optind;
14388 argv += optind;
14390 cwd = getcwd(NULL, 0);
14391 if (cwd == NULL) {
14392 error = got_error_from_errno("getcwd");
14393 goto done;
14396 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14397 if (error) {
14398 if (error->code == GOT_ERR_NOT_WORKTREE)
14399 error = wrap_not_worktree_error(error, "info", cwd);
14400 goto done;
14403 #ifndef PROFILE
14404 /* Remove "wpath cpath proc exec sendfd" promises. */
14405 if (pledge("stdio rpath flock unveil", NULL) == -1)
14406 err(1, "pledge");
14407 #endif
14408 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14409 if (error)
14410 goto done;
14412 if (argc >= 1) {
14413 error = get_worktree_paths_from_argv(&paths, argc, argv,
14414 worktree);
14415 if (error)
14416 goto done;
14417 show_files = 1;
14420 error = got_object_id_str(&id_str,
14421 got_worktree_get_base_commit_id(worktree));
14422 if (error)
14423 goto done;
14425 error = got_worktree_get_uuid(&uuidstr, worktree);
14426 if (error)
14427 goto done;
14429 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14430 printf("work tree base commit: %s\n", id_str);
14431 printf("work tree path prefix: %s\n",
14432 got_worktree_get_path_prefix(worktree));
14433 printf("work tree branch reference: %s\n",
14434 got_worktree_get_head_ref_name(worktree));
14435 printf("work tree UUID: %s\n", uuidstr);
14436 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14438 if (show_files) {
14439 struct got_pathlist_entry *pe;
14440 TAILQ_FOREACH(pe, &paths, entry) {
14441 if (pe->path_len == 0)
14442 continue;
14444 * Assume this path will fail. This will be corrected
14445 * in print_path_info() in case the path does suceeed.
14447 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14449 error = got_worktree_path_info(worktree, &paths,
14450 print_path_info, &paths, check_cancelled, NULL);
14451 if (error)
14452 goto done;
14453 TAILQ_FOREACH(pe, &paths, entry) {
14454 if (pe->data != NULL) {
14455 const struct got_error *perr;
14457 perr = pe->data;
14458 error = got_error_fmt(perr->code, "%s",
14459 pe->path);
14460 break;
14464 done:
14465 if (worktree)
14466 got_worktree_close(worktree);
14467 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14468 free(cwd);
14469 free(id_str);
14470 free(uuidstr);
14471 return error;