Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fflush(stdout);
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/usr/bin/vi");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_import(void)
352 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
353 "[-r repository-path] directory\n", getprogname());
354 exit(1);
357 static int
358 spawn_editor(const char *editor, const char *file)
360 pid_t pid;
361 sig_t sighup, sigint, sigquit;
362 int st = -1;
364 sighup = signal(SIGHUP, SIG_IGN);
365 sigint = signal(SIGINT, SIG_IGN);
366 sigquit = signal(SIGQUIT, SIG_IGN);
368 switch (pid = fork()) {
369 case -1:
370 goto doneediting;
371 case 0:
372 execl(editor, editor, file, (char *)NULL);
373 _exit(127);
376 while (waitpid(pid, &st, 0) == -1)
377 if (errno != EINTR)
378 break;
380 doneediting:
381 (void)signal(SIGHUP, sighup);
382 (void)signal(SIGINT, sigint);
383 (void)signal(SIGQUIT, sigquit);
385 if (!WIFEXITED(st)) {
386 errno = EINTR;
387 return -1;
390 return WEXITSTATUS(st);
393 static const struct got_error *
394 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
400 *logmsg = NULL;
401 *len = 0;
403 if (fseeko(fp, 0L, SEEK_SET) == -1)
404 return got_error_from_errno("fseeko");
406 *logmsg = malloc(filesize + 1);
407 if (*logmsg == NULL)
408 return got_error_from_errno("malloc");
409 (*logmsg)[0] = '\0';
411 while (getline(&line, &linesize, fp) != -1) {
412 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t logmsg_len;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (require_modification) {
458 struct timespec timeout;
460 timeout.tv_sec = 0;
461 timeout.tv_nsec = 1;
462 nanosleep(&timeout, NULL);
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno2("stat", logmsg_path);
468 if (require_modification && st.st_size == st2.st_size &&
469 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 fp = fopen(logmsg_path, "re");
474 if (fp == NULL) {
475 err = got_error_from_errno("fopen");
476 goto done;
479 /* strip comments and leading/trailing newlines */
480 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
481 if (err)
482 goto done;
483 if (logmsg_len == 0) {
484 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
485 "commit message cannot be empty, aborting");
486 goto done;
488 done:
489 if (fp && fclose(fp) == EOF && err == NULL)
490 err = got_error_from_errno("fclose");
491 if (err) {
492 free(*logmsg);
493 *logmsg = NULL;
495 return err;
498 static const struct got_error *
499 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
500 const char *path_dir, const char *branch_name)
502 char *initial_content = NULL;
503 const struct got_error *err = NULL;
504 int initial_content_len;
505 int fd = -1;
507 initial_content_len = asprintf(&initial_content,
508 "\n# %s to be imported to branch %s\n", path_dir,
509 branch_name);
510 if (initial_content_len == -1)
511 return got_error_from_errno("asprintf");
513 err = got_opentemp_named_fd(logmsg_path, &fd,
514 GOT_TMPDIR_STR "/got-importmsg", "");
515 if (err)
516 goto done;
518 if (write(fd, initial_content, initial_content_len) == -1) {
519 err = got_error_from_errno2("write", *logmsg_path);
520 goto done;
522 if (close(fd) == -1) {
523 err = got_error_from_errno2("close", *logmsg_path);
524 goto done;
526 fd = -1;
528 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
529 initial_content_len, 1);
530 done:
531 if (fd != -1 && close(fd) == -1 && err == NULL)
532 err = got_error_from_errno2("close", *logmsg_path);
533 free(initial_content);
534 if (err) {
535 free(*logmsg_path);
536 *logmsg_path = NULL;
538 return err;
541 static const struct got_error *
542 import_progress(void *arg, const char *path)
544 printf("A %s\n", path);
545 return NULL;
548 static const struct got_error *
549 valid_author(const char *author)
551 const char *email = author;
553 /*
554 * Git' expects the author (or committer) to be in the form
555 * "name <email>", which are mostly free form (see the
556 * "committer" description in git-fast-import(1)). We're only
557 * doing this to avoid git's object parser breaking on commits
558 * we create.
559 */
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (author != email && *author == '<' && *(author - 1) != ' ')
564 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
565 "between author name and email required", email);
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const char *
711 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 if (worktree)
717 worktree_conf = got_worktree_get_gotconfig(worktree);
718 repo_conf = got_repo_get_gotconfig(repo);
720 /*
721 * Priority of potential author information sources, from most
722 * significant to least significant:
723 * 1) work tree's .got/got.conf file
724 * 2) repository's got.conf file
725 */
727 if (worktree_conf)
728 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
729 if (got_signer_id == NULL)
730 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
732 return got_signer_id;
735 static const struct got_error *
736 get_gitconfig_path(char **gitconfig_path)
738 const char *homedir = getenv("HOME");
740 *gitconfig_path = NULL;
741 if (homedir) {
742 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
743 return got_error_from_errno("asprintf");
746 return NULL;
749 static const struct got_error *
750 cmd_import(int argc, char *argv[])
752 const struct got_error *error = NULL;
753 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
754 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
755 const char *branch_name = NULL;
756 char *id_str = NULL, *logmsg_path = NULL;
757 char refname[PATH_MAX] = "refs/heads/";
758 struct got_repository *repo = NULL;
759 struct got_reference *branch_ref = NULL, *head_ref = NULL;
760 struct got_object_id *new_commit_id = NULL;
761 int ch, n = 0;
762 struct got_pathlist_head ignores;
763 struct got_pathlist_entry *pe;
764 int preserve_logmsg = 0;
765 int *pack_fds = NULL;
767 TAILQ_INIT(&ignores);
769 #ifndef PROFILE
770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
771 "unveil",
772 NULL) == -1)
773 err(1, "pledge");
774 #endif
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 if (argc != 1)
814 usage_import();
816 if (repo_path == NULL) {
817 repo_path = getcwd(NULL, 0);
818 if (repo_path == NULL)
819 return got_error_from_errno("getcwd");
821 got_path_strip_trailing_slashes(repo_path);
822 error = get_gitconfig_path(&gitconfig_path);
823 if (error)
824 goto done;
825 error = got_repo_pack_fds_open(&pack_fds);
826 if (error != NULL)
827 goto done;
828 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
829 if (error)
830 goto done;
832 error = get_author(&author, repo, NULL);
833 if (error)
834 return error;
836 /*
837 * Don't let the user create a branch name with a leading '-'.
838 * While technically a valid reference name, this case is usually
839 * an unintended typo.
840 */
841 if (branch_name && branch_name[0] == '-')
842 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
844 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
845 if (error && error->code != GOT_ERR_NOT_REF)
846 goto done;
848 if (branch_name)
849 n = strlcat(refname, branch_name, sizeof(refname));
850 else if (head_ref && got_ref_is_symbolic(head_ref))
851 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
852 sizeof(refname));
853 else
854 n = strlcat(refname, "main", sizeof(refname));
855 if (n >= sizeof(refname)) {
856 error = got_error(GOT_ERR_NO_SPACE);
857 goto done;
860 error = got_ref_open(&branch_ref, repo, refname, 0);
861 if (error) {
862 if (error->code != GOT_ERR_NOT_REF)
863 goto done;
864 } else {
865 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
866 "import target branch already exists");
867 goto done;
870 path_dir = realpath(argv[0], NULL);
871 if (path_dir == NULL) {
872 error = got_error_from_errno2("realpath", argv[0]);
873 goto done;
875 got_path_strip_trailing_slashes(path_dir);
877 /*
878 * unveil(2) traverses exec(2); if an editor is used we have
879 * to apply unveil after the log message has been written.
880 */
881 if (logmsg == NULL || *logmsg == '\0') {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes, *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 struct got_pathlist_entry *pe;
2298 struct got_reflist_head remote_refs;
2299 struct got_reflist_entry *re;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL, have_bflag = 0;
2307 const char *remote_head = NULL, *worktree_branch = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&remote_refs);
2312 TAILQ_INIT(&wanted_branches);
2313 TAILQ_INIT(&wanted_refs);
2315 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2316 switch (ch) {
2317 case 'a':
2318 fetch_all_branches = 1;
2319 break;
2320 case 'b':
2321 error = got_pathlist_append(&wanted_branches,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 have_bflag = 1;
2326 break;
2327 case 'd':
2328 delete_refs = 1;
2329 break;
2330 case 'l':
2331 list_refs_only = 1;
2332 break;
2333 case 'q':
2334 verbosity = -1;
2335 break;
2336 case 'R':
2337 error = got_pathlist_append(&wanted_refs,
2338 optarg, NULL);
2339 if (error)
2340 return error;
2341 break;
2342 case 'r':
2343 repo_path = realpath(optarg, NULL);
2344 if (repo_path == NULL)
2345 return got_error_from_errno2("realpath",
2346 optarg);
2347 got_path_strip_trailing_slashes(repo_path);
2348 break;
2349 case 't':
2350 replace_tags = 1;
2351 break;
2352 case 'v':
2353 if (verbosity < 0)
2354 verbosity = 0;
2355 else if (verbosity < 3)
2356 verbosity++;
2357 break;
2358 case 'X':
2359 delete_remote = 1;
2360 break;
2361 default:
2362 usage_fetch();
2363 break;
2366 argc -= optind;
2367 argv += optind;
2369 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('a', 'b');
2371 if (list_refs_only) {
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('l', 'b');
2374 if (fetch_all_branches)
2375 option_conflict('l', 'a');
2376 if (delete_refs)
2377 option_conflict('l', 'd');
2378 if (delete_remote)
2379 option_conflict('l', 'X');
2381 if (delete_remote) {
2382 if (fetch_all_branches)
2383 option_conflict('X', 'a');
2384 if (!TAILQ_EMPTY(&wanted_branches))
2385 option_conflict('X', 'b');
2386 if (delete_refs)
2387 option_conflict('X', 'd');
2388 if (replace_tags)
2389 option_conflict('X', 't');
2390 if (!TAILQ_EMPTY(&wanted_refs))
2391 option_conflict('X', 'R');
2394 if (argc == 0) {
2395 if (delete_remote)
2396 errx(1, "-X option requires a remote name");
2397 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2398 } else if (argc == 1)
2399 remote_name = argv[0];
2400 else
2401 usage_fetch();
2403 cwd = getcwd(NULL, 0);
2404 if (cwd == NULL) {
2405 error = got_error_from_errno("getcwd");
2406 goto done;
2409 error = got_repo_pack_fds_open(&pack_fds);
2410 if (error != NULL)
2411 goto done;
2413 if (repo_path == NULL) {
2414 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2416 goto done;
2417 else
2418 error = NULL;
2419 if (worktree) {
2420 repo_path =
2421 strdup(got_worktree_get_repo_path(worktree));
2422 if (repo_path == NULL)
2423 error = got_error_from_errno("strdup");
2424 if (error)
2425 goto done;
2426 } else {
2427 repo_path = strdup(cwd);
2428 if (repo_path == NULL) {
2429 error = got_error_from_errno("strdup");
2430 goto done;
2435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2436 if (error)
2437 goto done;
2439 if (delete_remote) {
2440 error = delete_refs_for_remote(repo, remote_name);
2441 goto done; /* nothing else to do */
2444 if (worktree) {
2445 worktree_conf = got_worktree_get_gotconfig(worktree);
2446 if (worktree_conf) {
2447 got_gotconfig_get_remotes(&nremotes, &remotes,
2448 worktree_conf);
2449 for (i = 0; i < nremotes; i++) {
2450 if (strcmp(remotes[i].name, remote_name) == 0) {
2451 remote = &remotes[i];
2452 break;
2457 if (remote == NULL) {
2458 repo_conf = got_repo_get_gotconfig(repo);
2459 if (repo_conf) {
2460 got_gotconfig_get_remotes(&nremotes, &remotes,
2461 repo_conf);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2470 if (remote == NULL) {
2471 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 remote = &remotes[i];
2475 break;
2479 if (remote == NULL) {
2480 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_branches)) {
2485 if (!fetch_all_branches)
2486 fetch_all_branches = remote->fetch_all_branches;
2487 for (i = 0; i < remote->nfetch_branches; i++) {
2488 error = got_pathlist_append(&wanted_branches,
2489 remote->fetch_branches[i], NULL);
2490 if (error)
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_refs)) {
2495 for (i = 0; i < remote->nfetch_refs; i++) {
2496 error = got_pathlist_append(&wanted_refs,
2497 remote->fetch_refs[i], NULL);
2498 if (error)
2499 goto done;
2503 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2504 &repo_name, remote->fetch_url);
2505 if (error)
2506 goto done;
2508 if (strcmp(proto, "git") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd dns inet unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "git+ssh") == 0 ||
2515 strcmp(proto, "ssh") == 0) {
2516 #ifndef PROFILE
2517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2518 "sendfd unveil", NULL) == -1)
2519 err(1, "pledge");
2520 #endif
2521 } else if (strcmp(proto, "http") == 0 ||
2522 strcmp(proto, "git+http") == 0) {
2523 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2524 goto done;
2525 } else {
2526 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2527 goto done;
2530 error = got_dial_apply_unveil(proto);
2531 if (error)
2532 goto done;
2534 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2535 if (error)
2536 goto done;
2538 if (verbosity >= 0) {
2539 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2540 remote->name, proto, host,
2541 port ? ":" : "", port ? port : "",
2542 *server_path == '/' ? "" : "/", server_path);
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 if (!have_bflag) {
2552 * If set, get this remote's HEAD ref target so
2553 * if it has changed on the server we can fetch it.
2555 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2556 got_ref_cmp_by_name, repo);
2557 if (error)
2558 goto done;
2560 TAILQ_FOREACH(re, &remote_refs, entry) {
2561 const char *remote_refname, *remote_target;
2562 size_t remote_name_len;
2564 if (!got_ref_is_symbolic(re->ref))
2565 continue;
2567 remote_name_len = strlen(remote->name);
2568 remote_refname = got_ref_get_name(re->ref);
2570 /* we only want refs/remotes/$remote->name/HEAD */
2571 if (strncmp(remote_refname + 13, remote->name,
2572 remote_name_len) != 0)
2573 continue;
2575 if (strcmp(remote_refname + remote_name_len + 14,
2576 GOT_REF_HEAD) != 0)
2577 continue;
2580 * Take the name itself because we already
2581 * only match with refs/heads/ in fetch_pack().
2583 remote_target = got_ref_get_symref_target(re->ref);
2584 remote_head = remote_target + remote_name_len + 14;
2585 break;
2588 if (worktree) {
2589 const char *refname;
2591 refname = got_worktree_get_head_ref_name(worktree);
2592 if (strncmp(refname, "refs/heads/", 11) == 0)
2593 worktree_branch = refname;
2597 fpa.last_scaled_size[0] = '\0';
2598 fpa.last_p_indexed = -1;
2599 fpa.last_p_resolved = -1;
2600 fpa.verbosity = verbosity;
2601 fpa.repo = repo;
2602 fpa.create_configs = 0;
2603 fpa.configs_created = 0;
2604 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2606 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2607 remote->mirror_references, fetch_all_branches, &wanted_branches,
2608 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2609 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2610 if (error)
2611 goto done;
2613 if (list_refs_only) {
2614 error = list_remote_refs(&symrefs, &refs);
2615 goto done;
2618 if (pack_hash == NULL) {
2619 if (verbosity >= 0)
2620 printf("Already up-to-date\n");
2621 } else if (verbosity >= 0) {
2622 error = got_object_id_str(&id_str, pack_hash);
2623 if (error)
2624 goto done;
2625 printf("\nFetched %s.pack\n", id_str);
2626 free(id_str);
2627 id_str = NULL;
2630 /* Update references provided with the pack file. */
2631 TAILQ_FOREACH(pe, &refs, entry) {
2632 const char *refname = pe->path;
2633 struct got_object_id *id = pe->data;
2634 struct got_reference *ref;
2635 char *remote_refname;
2637 if (is_wanted_ref(&wanted_refs, refname) &&
2638 !remote->mirror_references) {
2639 error = update_wanted_ref(refname, id,
2640 remote->name, verbosity, repo);
2641 if (error)
2642 goto done;
2643 continue;
2646 if (remote->mirror_references ||
2647 strncmp("refs/tags/", refname, 10) == 0) {
2648 error = got_ref_open(&ref, repo, refname, 1);
2649 if (error) {
2650 if (error->code != GOT_ERR_NOT_REF)
2651 goto done;
2652 error = create_ref(refname, id, verbosity,
2653 repo);
2654 if (error)
2655 goto done;
2656 } else {
2657 error = update_ref(ref, id, replace_tags,
2658 verbosity, repo);
2659 unlock_err = got_ref_unlock(ref);
2660 if (unlock_err && error == NULL)
2661 error = unlock_err;
2662 got_ref_close(ref);
2663 if (error)
2664 goto done;
2666 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2667 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2668 remote_name, refname + 11) == -1) {
2669 error = got_error_from_errno("asprintf");
2670 goto done;
2673 error = got_ref_open(&ref, repo, remote_refname, 1);
2674 if (error) {
2675 if (error->code != GOT_ERR_NOT_REF)
2676 goto done;
2677 error = create_ref(remote_refname, id,
2678 verbosity, repo);
2679 if (error)
2680 goto done;
2681 } else {
2682 error = update_ref(ref, id, replace_tags,
2683 verbosity, repo);
2684 unlock_err = got_ref_unlock(ref);
2685 if (unlock_err && error == NULL)
2686 error = unlock_err;
2687 got_ref_close(ref);
2688 if (error)
2689 goto done;
2692 /* Also create a local branch if none exists yet. */
2693 error = got_ref_open(&ref, repo, refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(refname, id, verbosity,
2698 repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2709 if (delete_refs) {
2710 error = delete_missing_refs(&refs, &symrefs, remote,
2711 verbosity, repo);
2712 if (error)
2713 goto done;
2716 if (!remote->mirror_references) {
2717 /* Update remote HEAD reference if the server provided one. */
2718 TAILQ_FOREACH(pe, &symrefs, entry) {
2719 struct got_reference *target_ref;
2720 const char *refname = pe->path;
2721 const char *target = pe->data;
2722 char *remote_refname = NULL, *remote_target = NULL;
2724 if (strcmp(refname, GOT_REF_HEAD) != 0)
2725 continue;
2727 if (strncmp("refs/heads/", target, 11) != 0)
2728 continue;
2730 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2731 remote->name, refname) == -1) {
2732 error = got_error_from_errno("asprintf");
2733 goto done;
2735 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2736 remote->name, target + 11) == -1) {
2737 error = got_error_from_errno("asprintf");
2738 free(remote_refname);
2739 goto done;
2742 error = got_ref_open(&target_ref, repo, remote_target,
2743 0);
2744 if (error) {
2745 free(remote_refname);
2746 free(remote_target);
2747 if (error->code == GOT_ERR_NOT_REF) {
2748 error = NULL;
2749 continue;
2751 goto done;
2753 error = update_symref(remote_refname, target_ref,
2754 verbosity, repo);
2755 free(remote_refname);
2756 free(remote_target);
2757 got_ref_close(target_ref);
2758 if (error)
2759 goto done;
2762 done:
2763 if (fetchpid > 0) {
2764 if (kill(fetchpid, SIGTERM) == -1)
2765 error = got_error_from_errno("kill");
2766 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2767 error = got_error_from_errno("waitpid");
2769 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2770 error = got_error_from_errno("close");
2771 if (repo) {
2772 const struct got_error *close_err = got_repo_close(repo);
2773 if (error == NULL)
2774 error = close_err;
2776 if (worktree)
2777 got_worktree_close(worktree);
2778 if (pack_fds) {
2779 const struct got_error *pack_err =
2780 got_repo_pack_fds_close(pack_fds);
2781 if (error == NULL)
2782 error = pack_err;
2784 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2787 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2788 got_ref_list_free(&remote_refs);
2789 free(id_str);
2790 free(cwd);
2791 free(repo_path);
2792 free(pack_hash);
2793 free(proto);
2794 free(host);
2795 free(port);
2796 free(server_path);
2797 free(repo_name);
2798 return error;
2802 __dead static void
2803 usage_checkout(void)
2805 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2806 "[-p path-prefix] repository-path [work-tree-path]\n",
2807 getprogname());
2808 exit(1);
2811 static void
2812 show_worktree_base_ref_warning(void)
2814 fprintf(stderr, "%s: warning: could not create a reference "
2815 "to the work tree's base commit; the commit could be "
2816 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2817 "repository writable and running 'got update' will prevent this\n",
2818 getprogname());
2821 struct got_checkout_progress_arg {
2822 const char *worktree_path;
2823 int had_base_commit_ref_error;
2824 int verbosity;
2827 static const struct got_error *
2828 checkout_progress(void *arg, unsigned char status, const char *path)
2830 struct got_checkout_progress_arg *a = arg;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_BASE_REF_ERR) {
2837 a->had_base_commit_ref_error = 1;
2838 return NULL;
2841 while (path[0] == '/')
2842 path++;
2844 if (a->verbosity >= 0)
2845 printf("%c %s/%s\n", status, a->worktree_path, path);
2847 return NULL;
2850 static const struct got_error *
2851 check_cancelled(void *arg)
2853 if (sigint_received || sigpipe_received)
2854 return got_error(GOT_ERR_CANCELLED);
2855 return NULL;
2858 static const struct got_error *
2859 check_linear_ancestry(struct got_object_id *commit_id,
2860 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2861 struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct got_object_id *yca_id;
2866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2867 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2868 if (err)
2869 return err;
2871 if (yca_id == NULL)
2872 return got_error(GOT_ERR_ANCESTRY);
2875 * Require a straight line of history between the target commit
2876 * and the work tree's base commit.
2878 * Non-linear situations such as this require a rebase:
2880 * (commit) D F (base_commit)
2881 * \ /
2882 * C E
2883 * \ /
2884 * B (yca)
2885 * |
2886 * A
2888 * 'got update' only handles linear cases:
2889 * Update forwards in time: A (base/yca) - B - C - D (commit)
2890 * Update backwards in time: D (base) - C - B - A (commit/yca)
2892 if (allow_forwards_in_time_only) {
2893 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2894 return got_error(GOT_ERR_ANCESTRY);
2895 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2896 got_object_id_cmp(base_commit_id, yca_id) != 0)
2897 return got_error(GOT_ERR_ANCESTRY);
2899 free(yca_id);
2900 return NULL;
2903 static const struct got_error *
2904 check_same_branch(struct got_object_id *commit_id,
2905 struct got_reference *head_ref, struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2911 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2912 if (err)
2913 goto done;
2915 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2916 goto done;
2918 err = got_commit_graph_open(&graph, "/", 1);
2919 if (err)
2920 goto done;
2922 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2923 check_cancelled, NULL);
2924 if (err)
2925 goto done;
2927 for (;;) {
2928 struct got_object_id id;
2930 err = got_commit_graph_iter_next(&id, graph, repo,
2931 check_cancelled, NULL);
2932 if (err) {
2933 if (err->code == GOT_ERR_ITER_COMPLETED)
2934 err = got_error(GOT_ERR_ANCESTRY);
2935 break;
2938 if (got_object_id_cmp(&id, commit_id) == 0)
2939 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL, *keyword_idstr = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 #ifndef PROFILE
2994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2995 "unveil", NULL) == -1)
2996 err(1, "pledge");
2997 #endif
2999 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3000 switch (ch) {
3001 case 'b':
3002 branch_name = optarg;
3003 break;
3004 case 'c':
3005 commit_id_str = strdup(optarg);
3006 if (commit_id_str == NULL)
3007 return got_error_from_errno("strdup");
3008 break;
3009 case 'E':
3010 allow_nonempty = 1;
3011 break;
3012 case 'p':
3013 path_prefix = optarg;
3014 break;
3015 case 'q':
3016 verbosity = -1;
3017 break;
3018 default:
3019 usage_checkout();
3020 /* NOTREACHED */
3024 argc -= optind;
3025 argv += optind;
3027 if (argc == 1) {
3028 char *base, *dotgit;
3029 const char *path;
3030 repo_path = realpath(argv[0], NULL);
3031 if (repo_path == NULL)
3032 return got_error_from_errno2("realpath", argv[0]);
3033 cwd = getcwd(NULL, 0);
3034 if (cwd == NULL) {
3035 error = got_error_from_errno("getcwd");
3036 goto done;
3038 if (path_prefix[0])
3039 path = path_prefix;
3040 else
3041 path = repo_path;
3042 error = got_path_basename(&base, path);
3043 if (error)
3044 goto done;
3045 dotgit = strstr(base, ".git");
3046 if (dotgit)
3047 *dotgit = '\0';
3048 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3049 error = got_error_from_errno("asprintf");
3050 free(base);
3051 goto done;
3053 free(base);
3054 } else if (argc == 2) {
3055 repo_path = realpath(argv[0], NULL);
3056 if (repo_path == NULL) {
3057 error = got_error_from_errno2("realpath", argv[0]);
3058 goto done;
3060 worktree_path = realpath(argv[1], NULL);
3061 if (worktree_path == NULL) {
3062 if (errno != ENOENT) {
3063 error = got_error_from_errno2("realpath",
3064 argv[1]);
3065 goto done;
3067 worktree_path = strdup(argv[1]);
3068 if (worktree_path == NULL) {
3069 error = got_error_from_errno("strdup");
3070 goto done;
3073 } else
3074 usage_checkout();
3076 got_path_strip_trailing_slashes(repo_path);
3077 got_path_strip_trailing_slashes(worktree_path);
3079 error = got_repo_pack_fds_open(&pack_fds);
3080 if (error != NULL)
3081 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 /* Pre-create work tree path for unveil(2) */
3088 error = got_path_mkdir(worktree_path);
3089 if (error) {
3090 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3091 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3092 goto done;
3093 if (!allow_nonempty &&
3094 !got_path_dir_is_empty(worktree_path)) {
3095 error = got_error_path(worktree_path,
3096 GOT_ERR_DIR_NOT_EMPTY);
3097 goto done;
3101 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3102 if (error)
3103 goto done;
3105 error = got_ref_open(&head_ref, repo, branch_name, 0);
3106 if (error != NULL)
3107 goto done;
3109 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3110 GOT_WORKTREE_GOT_DIR, repo);
3111 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3112 goto done;
3114 error = got_worktree_open(&worktree, worktree_path,
3115 GOT_WORKTREE_GOT_DIR);
3116 if (error != NULL)
3117 goto done;
3119 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3120 path_prefix);
3121 if (error != NULL)
3122 goto done;
3123 if (!same_path_prefix) {
3124 error = got_error(GOT_ERR_PATH_PREFIX);
3125 goto done;
3128 if (commit_id_str) {
3129 struct got_reflist_head refs;
3130 TAILQ_INIT(&refs);
3131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3132 NULL);
3133 if (error)
3134 goto done;
3136 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3137 repo, worktree);
3138 if (error != NULL)
3139 goto done;
3140 if (keyword_idstr != NULL) {
3141 free(commit_id_str);
3142 commit_id_str = keyword_idstr;
3145 error = got_repo_match_object_id(&commit_id, NULL,
3146 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3147 got_ref_list_free(&refs);
3148 if (error)
3149 goto done;
3150 error = check_linear_ancestry(commit_id,
3151 got_worktree_get_base_commit_id(worktree), 0, repo);
3152 if (error != NULL) {
3153 if (error->code == GOT_ERR_ANCESTRY) {
3154 error = checkout_ancestry_error(
3155 head_ref, commit_id_str);
3157 goto done;
3159 error = check_same_branch(commit_id, head_ref, repo);
3160 if (error) {
3161 if (error->code == GOT_ERR_ANCESTRY) {
3162 error = checkout_ancestry_error(
3163 head_ref, commit_id_str);
3165 goto done;
3167 error = got_worktree_set_base_commit_id(worktree, repo,
3168 commit_id);
3169 if (error)
3170 goto done;
3171 /* Expand potentially abbreviated commit ID string. */
3172 free(commit_id_str);
3173 error = got_object_id_str(&commit_id_str, commit_id);
3174 if (error)
3175 goto done;
3176 } else {
3177 commit_id = got_object_id_dup(
3178 got_worktree_get_base_commit_id(worktree));
3179 if (commit_id == NULL) {
3180 error = got_error_from_errno("got_object_id_dup");
3181 goto done;
3183 error = got_object_id_str(&commit_id_str, commit_id);
3184 if (error)
3185 goto done;
3188 error = got_pathlist_append(&paths, "", NULL);
3189 if (error)
3190 goto done;
3191 cpa.worktree_path = worktree_path;
3192 cpa.had_base_commit_ref_error = 0;
3193 cpa.verbosity = verbosity;
3194 error = got_worktree_checkout_files(worktree, &paths, repo,
3195 checkout_progress, &cpa, check_cancelled, NULL);
3196 if (error != NULL)
3197 goto done;
3199 if (got_ref_is_symbolic(head_ref)) {
3200 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3201 if (error)
3202 goto done;
3203 refname = got_ref_get_name(ref);
3204 } else
3205 refname = got_ref_get_name(head_ref);
3206 printf("Checked out %s: %s\n", refname, commit_id_str);
3207 printf("Now shut up and hack\n");
3208 if (cpa.had_base_commit_ref_error)
3209 show_worktree_base_ref_warning();
3210 done:
3211 if (pack_fds) {
3212 const struct got_error *pack_err =
3213 got_repo_pack_fds_close(pack_fds);
3214 if (error == NULL)
3215 error = pack_err;
3217 if (head_ref)
3218 got_ref_close(head_ref);
3219 if (ref)
3220 got_ref_close(ref);
3221 if (repo) {
3222 const struct got_error *close_err = got_repo_close(repo);
3223 if (error == NULL)
3224 error = close_err;
3226 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3227 free(commit_id_str);
3228 free(commit_id);
3229 free(repo_path);
3230 free(worktree_path);
3231 free(cwd);
3232 return error;
3235 struct got_update_progress_arg {
3236 int did_something;
3237 int conflicts;
3238 int obstructed;
3239 int not_updated;
3240 int missing;
3241 int not_deleted;
3242 int unversioned;
3243 int verbosity;
3246 static void
3247 print_update_progress_stats(struct got_update_progress_arg *upa)
3249 if (!upa->did_something)
3250 return;
3252 if (upa->conflicts > 0)
3253 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3254 if (upa->obstructed > 0)
3255 printf("File paths obstructed by a non-regular file: %d\n",
3256 upa->obstructed);
3257 if (upa->not_updated > 0)
3258 printf("Files not updated because of existing merge "
3259 "conflicts: %d\n", upa->not_updated);
3263 * The meaning of some status codes differs between merge-style operations and
3264 * update operations. For example, the ! status code means "file was missing"
3265 * if changes were merged into the work tree, and "missing file was restored"
3266 * if the work tree was updated. This function should be used by any operation
3267 * which merges changes into the work tree without updating the work tree.
3269 static void
3270 print_merge_progress_stats(struct got_update_progress_arg *upa)
3272 if (!upa->did_something)
3273 return;
3275 if (upa->conflicts > 0)
3276 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3277 if (upa->obstructed > 0)
3278 printf("File paths obstructed by a non-regular file: %d\n",
3279 upa->obstructed);
3280 if (upa->missing > 0)
3281 printf("Files which had incoming changes but could not be "
3282 "found in the work tree: %d\n", upa->missing);
3283 if (upa->not_deleted > 0)
3284 printf("Files not deleted due to differences in deleted "
3285 "content: %d\n", upa->not_deleted);
3286 if (upa->unversioned > 0)
3287 printf("Files not merged because an unversioned file was "
3288 "found in the work tree: %d\n", upa->unversioned);
3291 __dead static void
3292 usage_update(void)
3294 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3295 "[path ...]\n", getprogname());
3296 exit(1);
3299 static const struct got_error *
3300 update_progress(void *arg, unsigned char status, const char *path)
3302 struct got_update_progress_arg *upa = arg;
3304 if (status == GOT_STATUS_EXISTS ||
3305 status == GOT_STATUS_BASE_REF_ERR)
3306 return NULL;
3308 upa->did_something = 1;
3310 /* Base commit bump happens silently. */
3311 if (status == GOT_STATUS_BUMP_BASE)
3312 return NULL;
3314 if (status == GOT_STATUS_CONFLICT)
3315 upa->conflicts++;
3316 if (status == GOT_STATUS_OBSTRUCTED)
3317 upa->obstructed++;
3318 if (status == GOT_STATUS_CANNOT_UPDATE)
3319 upa->not_updated++;
3320 if (status == GOT_STATUS_MISSING)
3321 upa->missing++;
3322 if (status == GOT_STATUS_CANNOT_DELETE)
3323 upa->not_deleted++;
3324 if (status == GOT_STATUS_UNVERSIONED)
3325 upa->unversioned++;
3327 while (path[0] == '/')
3328 path++;
3329 if (upa->verbosity >= 0)
3330 printf("%c %s\n", status, path);
3332 return NULL;
3335 static const struct got_error *
3336 switch_head_ref(struct got_reference *head_ref,
3337 struct got_object_id *commit_id, struct got_worktree *worktree,
3338 struct got_repository *repo)
3340 const struct got_error *err = NULL;
3341 char *base_id_str;
3342 int ref_has_moved = 0;
3344 /* Trivial case: switching between two different references. */
3345 if (strcmp(got_ref_get_name(head_ref),
3346 got_worktree_get_head_ref_name(worktree)) != 0) {
3347 printf("Switching work tree from %s to %s\n",
3348 got_worktree_get_head_ref_name(worktree),
3349 got_ref_get_name(head_ref));
3350 return got_worktree_set_head_ref(worktree, head_ref);
3353 err = check_linear_ancestry(commit_id,
3354 got_worktree_get_base_commit_id(worktree), 0, repo);
3355 if (err) {
3356 if (err->code != GOT_ERR_ANCESTRY)
3357 return err;
3358 ref_has_moved = 1;
3360 if (!ref_has_moved)
3361 return NULL;
3363 /* Switching to a rebased branch with the same reference name. */
3364 err = got_object_id_str(&base_id_str,
3365 got_worktree_get_base_commit_id(worktree));
3366 if (err)
3367 return err;
3368 printf("Reference %s now points at a different branch\n",
3369 got_worktree_get_head_ref_name(worktree));
3370 printf("Switching work tree from %s to %s\n", base_id_str,
3371 got_worktree_get_head_ref_name(worktree));
3372 return NULL;
3375 static const struct got_error *
3376 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3378 const struct got_error *err;
3379 int in_progress;
3381 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3382 if (err)
3383 return err;
3384 if (in_progress)
3385 return got_error(GOT_ERR_REBASING);
3387 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3388 if (err)
3389 return err;
3390 if (in_progress)
3391 return got_error(GOT_ERR_HISTEDIT_BUSY);
3393 return NULL;
3396 static const struct got_error *
3397 check_merge_in_progress(struct got_worktree *worktree,
3398 struct got_repository *repo)
3400 const struct got_error *err;
3401 int in_progress;
3403 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3404 if (err)
3405 return err;
3406 if (in_progress)
3407 return got_error(GOT_ERR_MERGE_BUSY);
3409 return NULL;
3412 static const struct got_error *
3413 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3414 char *argv[], struct got_worktree *worktree)
3416 const struct got_error *err = NULL;
3417 char *path;
3418 struct got_pathlist_entry *new;
3419 int i;
3421 if (argc == 0) {
3422 path = strdup("");
3423 if (path == NULL)
3424 return got_error_from_errno("strdup");
3425 return got_pathlist_append(paths, path, NULL);
3428 for (i = 0; i < argc; i++) {
3429 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3430 if (err)
3431 break;
3432 err = got_pathlist_insert(&new, paths, path, NULL);
3433 if (err || new == NULL /* duplicate */) {
3434 free(path);
3435 if (err)
3436 break;
3440 return err;
3443 static const struct got_error *
3444 wrap_not_worktree_error(const struct got_error *orig_err,
3445 const char *cmdname, const char *path)
3447 const struct got_error *err;
3448 struct got_repository *repo;
3449 static char msg[512];
3450 int *pack_fds = NULL;
3452 err = got_repo_pack_fds_open(&pack_fds);
3453 if (err)
3454 return err;
3456 err = got_repo_open(&repo, path, NULL, pack_fds);
3457 if (err)
3458 return orig_err;
3460 snprintf(msg, sizeof(msg),
3461 "'got %s' needs a work tree in addition to a git repository\n"
3462 "Work trees can be checked out from this Git repository with "
3463 "'got checkout'.\n"
3464 "The got(1) manual page contains more information.", cmdname);
3465 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3466 if (repo) {
3467 const struct got_error *close_err = got_repo_close(repo);
3468 if (err == NULL)
3469 err = close_err;
3471 if (pack_fds) {
3472 const struct got_error *pack_err =
3473 got_repo_pack_fds_close(pack_fds);
3474 if (err == NULL)
3475 err = pack_err;
3477 return err;
3480 static const struct got_error *
3481 cmd_update(int argc, char *argv[])
3483 const struct got_error *error = NULL;
3484 struct got_repository *repo = NULL;
3485 struct got_worktree *worktree = NULL;
3486 char *worktree_path = NULL;
3487 struct got_object_id *commit_id = NULL;
3488 char *commit_id_str = NULL;
3489 const char *branch_name = NULL;
3490 struct got_reference *head_ref = NULL;
3491 struct got_pathlist_head paths;
3492 struct got_pathlist_entry *pe;
3493 int ch, verbosity = 0;
3494 struct got_update_progress_arg upa;
3495 int *pack_fds = NULL;
3497 TAILQ_INIT(&paths);
3499 #ifndef PROFILE
3500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3501 "unveil", NULL) == -1)
3502 err(1, "pledge");
3503 #endif
3505 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3506 switch (ch) {
3507 case 'b':
3508 branch_name = optarg;
3509 break;
3510 case 'c':
3511 commit_id_str = strdup(optarg);
3512 if (commit_id_str == NULL)
3513 return got_error_from_errno("strdup");
3514 break;
3515 case 'q':
3516 verbosity = -1;
3517 break;
3518 default:
3519 usage_update();
3520 /* NOTREACHED */
3524 argc -= optind;
3525 argv += optind;
3527 worktree_path = getcwd(NULL, 0);
3528 if (worktree_path == NULL) {
3529 error = got_error_from_errno("getcwd");
3530 goto done;
3533 error = got_repo_pack_fds_open(&pack_fds);
3534 if (error != NULL)
3535 goto done;
3537 error = got_worktree_open(&worktree, worktree_path,
3538 GOT_WORKTREE_GOT_DIR);
3539 if (error) {
3540 if (error->code == GOT_ERR_NOT_WORKTREE)
3541 error = wrap_not_worktree_error(error, "update",
3542 worktree_path);
3543 goto done;
3546 error = check_rebase_or_histedit_in_progress(worktree);
3547 if (error)
3548 goto done;
3550 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3551 NULL, pack_fds);
3552 if (error != NULL)
3553 goto done;
3555 error = apply_unveil(got_repo_get_path(repo), 0,
3556 got_worktree_get_root_path(worktree));
3557 if (error)
3558 goto done;
3560 error = check_merge_in_progress(worktree, repo);
3561 if (error)
3562 goto done;
3564 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3565 if (error)
3566 goto done;
3568 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3569 got_worktree_get_head_ref_name(worktree), 0);
3570 if (error != NULL)
3571 goto done;
3572 if (commit_id_str == NULL) {
3573 error = got_ref_resolve(&commit_id, repo, head_ref);
3574 if (error != NULL)
3575 goto done;
3576 error = got_object_id_str(&commit_id_str, commit_id);
3577 if (error != NULL)
3578 goto done;
3579 } else {
3580 struct got_reflist_head refs;
3581 char *keyword_idstr = NULL;
3583 TAILQ_INIT(&refs);
3585 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3586 NULL);
3587 if (error)
3588 goto done;
3590 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3591 repo, worktree);
3592 if (error != NULL)
3593 goto done;
3594 if (keyword_idstr != NULL) {
3595 free(commit_id_str);
3596 commit_id_str = keyword_idstr;
3599 error = got_repo_match_object_id(&commit_id, NULL,
3600 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3601 got_ref_list_free(&refs);
3602 free(commit_id_str);
3603 commit_id_str = NULL;
3604 if (error)
3605 goto done;
3606 error = got_object_id_str(&commit_id_str, commit_id);
3607 if (error)
3608 goto done;
3611 if (branch_name) {
3612 struct got_object_id *head_commit_id;
3613 TAILQ_FOREACH(pe, &paths, entry) {
3614 if (pe->path_len == 0)
3615 continue;
3616 error = got_error_msg(GOT_ERR_BAD_PATH,
3617 "switching between branches requires that "
3618 "the entire work tree gets updated");
3619 goto done;
3621 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3622 if (error)
3623 goto done;
3624 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3625 repo);
3626 free(head_commit_id);
3627 if (error != NULL)
3628 goto done;
3629 error = check_same_branch(commit_id, head_ref, repo);
3630 if (error)
3631 goto done;
3632 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3633 if (error)
3634 goto done;
3635 } else {
3636 error = check_linear_ancestry(commit_id,
3637 got_worktree_get_base_commit_id(worktree), 0, repo);
3638 if (error != NULL) {
3639 if (error->code == GOT_ERR_ANCESTRY)
3640 error = got_error(GOT_ERR_BRANCH_MOVED);
3641 goto done;
3643 error = check_same_branch(commit_id, head_ref, repo);
3644 if (error)
3645 goto done;
3648 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3649 commit_id) != 0) {
3650 error = got_worktree_set_base_commit_id(worktree, repo,
3651 commit_id);
3652 if (error)
3653 goto done;
3656 memset(&upa, 0, sizeof(upa));
3657 upa.verbosity = verbosity;
3658 error = got_worktree_checkout_files(worktree, &paths, repo,
3659 update_progress, &upa, check_cancelled, NULL);
3660 if (error != NULL)
3661 goto done;
3663 if (upa.did_something) {
3664 printf("Updated to %s: %s\n",
3665 got_worktree_get_head_ref_name(worktree), commit_id_str);
3666 } else
3667 printf("Already up-to-date\n");
3669 print_update_progress_stats(&upa);
3670 done:
3671 if (pack_fds) {
3672 const struct got_error *pack_err =
3673 got_repo_pack_fds_close(pack_fds);
3674 if (error == NULL)
3675 error = pack_err;
3677 if (repo) {
3678 const struct got_error *close_err = got_repo_close(repo);
3679 if (error == NULL)
3680 error = close_err;
3682 if (head_ref != NULL)
3683 got_ref_close(head_ref);
3684 free(worktree_path);
3685 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3686 free(commit_id);
3687 free(commit_id_str);
3688 return error;
3691 static const struct got_error *
3692 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3693 const char *path, int diff_context, int ignore_whitespace,
3694 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3695 struct got_repository *repo, FILE *outfile)
3697 const struct got_error *err = NULL;
3698 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3699 FILE *f1 = NULL, *f2 = NULL;
3700 int fd1 = -1, fd2 = -1;
3702 fd1 = got_opentempfd();
3703 if (fd1 == -1)
3704 return got_error_from_errno("got_opentempfd");
3705 fd2 = got_opentempfd();
3706 if (fd2 == -1) {
3707 err = got_error_from_errno("got_opentempfd");
3708 goto done;
3711 if (blob_id1) {
3712 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3713 fd1);
3714 if (err)
3715 goto done;
3718 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3719 if (err)
3720 goto done;
3722 f1 = got_opentemp();
3723 if (f1 == NULL) {
3724 err = got_error_from_errno("got_opentemp");
3725 goto done;
3727 f2 = got_opentemp();
3728 if (f2 == NULL) {
3729 err = got_error_from_errno("got_opentemp");
3730 goto done;
3733 while (path[0] == '/')
3734 path++;
3735 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3736 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3737 force_text_diff, dsa, outfile);
3738 done:
3739 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3740 err = got_error_from_errno("close");
3741 if (blob1)
3742 got_object_blob_close(blob1);
3743 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3744 err = got_error_from_errno("close");
3745 if (blob2)
3746 got_object_blob_close(blob2);
3747 if (f1 && fclose(f1) == EOF && err == NULL)
3748 err = got_error_from_errno("fclose");
3749 if (f2 && fclose(f2) == EOF && err == NULL)
3750 err = got_error_from_errno("fclose");
3751 return err;
3754 static const struct got_error *
3755 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3756 const char *path, int diff_context, int ignore_whitespace,
3757 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3758 struct got_repository *repo, FILE *outfile)
3760 const struct got_error *err = NULL;
3761 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3762 struct got_diff_blob_output_unidiff_arg arg;
3763 FILE *f1 = NULL, *f2 = NULL;
3764 int fd1 = -1, fd2 = -1;
3766 if (tree_id1) {
3767 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3768 if (err)
3769 goto done;
3770 fd1 = got_opentempfd();
3771 if (fd1 == -1) {
3772 err = got_error_from_errno("got_opentempfd");
3773 goto done;
3777 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3778 if (err)
3779 goto done;
3781 f1 = got_opentemp();
3782 if (f1 == NULL) {
3783 err = got_error_from_errno("got_opentemp");
3784 goto done;
3787 f2 = got_opentemp();
3788 if (f2 == NULL) {
3789 err = got_error_from_errno("got_opentemp");
3790 goto done;
3792 fd2 = got_opentempfd();
3793 if (fd2 == -1) {
3794 err = got_error_from_errno("got_opentempfd");
3795 goto done;
3797 arg.diff_context = diff_context;
3798 arg.ignore_whitespace = ignore_whitespace;
3799 arg.force_text_diff = force_text_diff;
3800 arg.diffstat = dsa;
3801 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3802 arg.outfile = outfile;
3803 arg.lines = NULL;
3804 arg.nlines = 0;
3805 while (path[0] == '/')
3806 path++;
3807 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3808 got_diff_blob_output_unidiff, &arg, 1);
3809 done:
3810 if (tree1)
3811 got_object_tree_close(tree1);
3812 if (tree2)
3813 got_object_tree_close(tree2);
3814 if (f1 && fclose(f1) == EOF && err == NULL)
3815 err = got_error_from_errno("fclose");
3816 if (f2 && fclose(f2) == EOF && err == NULL)
3817 err = got_error_from_errno("fclose");
3818 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3819 err = got_error_from_errno("close");
3820 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3821 err = got_error_from_errno("close");
3822 return err;
3825 static const struct got_error *
3826 get_changed_paths(struct got_pathlist_head *paths,
3827 struct got_commit_object *commit, struct got_repository *repo,
3828 struct got_diffstat_cb_arg *dsa)
3830 const struct got_error *err = NULL;
3831 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3832 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3833 struct got_object_qid *qid;
3834 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3835 FILE *f1 = NULL, *f2 = NULL;
3836 int fd1 = -1, fd2 = -1;
3838 if (dsa) {
3839 cb = got_diff_tree_compute_diffstat;
3841 f1 = got_opentemp();
3842 if (f1 == NULL) {
3843 err = got_error_from_errno("got_opentemp");
3844 goto done;
3846 f2 = got_opentemp();
3847 if (f2 == NULL) {
3848 err = got_error_from_errno("got_opentemp");
3849 goto done;
3851 fd1 = got_opentempfd();
3852 if (fd1 == -1) {
3853 err = got_error_from_errno("got_opentempfd");
3854 goto done;
3856 fd2 = got_opentempfd();
3857 if (fd2 == -1) {
3858 err = got_error_from_errno("got_opentempfd");
3859 goto done;
3863 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3864 if (qid != NULL) {
3865 struct got_commit_object *pcommit;
3866 err = got_object_open_as_commit(&pcommit, repo,
3867 &qid->id);
3868 if (err)
3869 return err;
3871 tree_id1 = got_object_id_dup(
3872 got_object_commit_get_tree_id(pcommit));
3873 if (tree_id1 == NULL) {
3874 got_object_commit_close(pcommit);
3875 return got_error_from_errno("got_object_id_dup");
3877 got_object_commit_close(pcommit);
3881 if (tree_id1) {
3882 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3883 if (err)
3884 goto done;
3887 tree_id2 = got_object_commit_get_tree_id(commit);
3888 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3889 if (err)
3890 goto done;
3892 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3893 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3894 done:
3895 if (tree1)
3896 got_object_tree_close(tree1);
3897 if (tree2)
3898 got_object_tree_close(tree2);
3899 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3900 err = got_error_from_errno("close");
3901 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3902 err = got_error_from_errno("close");
3903 if (f1 && fclose(f1) == EOF && err == NULL)
3904 err = got_error_from_errno("fclose");
3905 if (f2 && fclose(f2) == EOF && err == NULL)
3906 err = got_error_from_errno("fclose");
3907 free(tree_id1);
3908 return err;
3911 static const struct got_error *
3912 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3913 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3914 struct got_repository *repo, FILE *outfile)
3916 const struct got_error *err = NULL;
3917 struct got_commit_object *pcommit = NULL;
3918 char *id_str1 = NULL, *id_str2 = NULL;
3919 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3920 struct got_object_qid *qid;
3922 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3923 if (qid != NULL) {
3924 err = got_object_open_as_commit(&pcommit, repo,
3925 &qid->id);
3926 if (err)
3927 return err;
3928 err = got_object_id_str(&id_str1, &qid->id);
3929 if (err)
3930 goto done;
3933 err = got_object_id_str(&id_str2, id);
3934 if (err)
3935 goto done;
3937 if (path && path[0] != '\0') {
3938 int obj_type;
3939 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3940 if (err)
3941 goto done;
3942 if (pcommit) {
3943 err = got_object_id_by_path(&obj_id1, repo,
3944 pcommit, path);
3945 if (err) {
3946 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3947 free(obj_id2);
3948 goto done;
3952 err = got_object_get_type(&obj_type, repo, obj_id2);
3953 if (err) {
3954 free(obj_id2);
3955 goto done;
3957 fprintf(outfile,
3958 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3959 fprintf(outfile, "commit - %s\n",
3960 id_str1 ? id_str1 : "/dev/null");
3961 fprintf(outfile, "commit + %s\n", id_str2);
3962 switch (obj_type) {
3963 case GOT_OBJ_TYPE_BLOB:
3964 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3965 0, 0, dsa, repo, outfile);
3966 break;
3967 case GOT_OBJ_TYPE_TREE:
3968 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3969 0, 0, dsa, repo, outfile);
3970 break;
3971 default:
3972 err = got_error(GOT_ERR_OBJ_TYPE);
3973 break;
3975 free(obj_id1);
3976 free(obj_id2);
3977 } else {
3978 obj_id2 = got_object_commit_get_tree_id(commit);
3979 if (pcommit)
3980 obj_id1 = got_object_commit_get_tree_id(pcommit);
3981 fprintf(outfile,
3982 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3983 fprintf(outfile, "commit - %s\n",
3984 id_str1 ? id_str1 : "/dev/null");
3985 fprintf(outfile, "commit + %s\n", id_str2);
3986 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3987 dsa, repo, outfile);
3989 done:
3990 free(id_str1);
3991 free(id_str2);
3992 if (pcommit)
3993 got_object_commit_close(pcommit);
3994 return err;
3997 static char *
3998 get_datestr(time_t *time, char *datebuf)
4000 struct tm mytm, *tm;
4001 char *p, *s;
4003 tm = gmtime_r(time, &mytm);
4004 if (tm == NULL)
4005 return NULL;
4006 s = asctime_r(tm, datebuf);
4007 if (s == NULL)
4008 return NULL;
4009 p = strchr(s, '\n');
4010 if (p)
4011 *p = '\0';
4012 return s;
4015 static const struct got_error *
4016 match_commit(int *have_match, struct got_object_id *id,
4017 struct got_commit_object *commit, regex_t *regex)
4019 const struct got_error *err = NULL;
4020 regmatch_t regmatch;
4021 char *id_str = NULL, *logmsg = NULL;
4023 *have_match = 0;
4025 err = got_object_id_str(&id_str, id);
4026 if (err)
4027 return err;
4029 err = got_object_commit_get_logmsg(&logmsg, commit);
4030 if (err)
4031 goto done;
4033 if (regexec(regex, got_object_commit_get_author(commit), 1,
4034 &regmatch, 0) == 0 ||
4035 regexec(regex, got_object_commit_get_committer(commit), 1,
4036 &regmatch, 0) == 0 ||
4037 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4038 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4039 *have_match = 1;
4040 done:
4041 free(id_str);
4042 free(logmsg);
4043 return err;
4046 static void
4047 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4048 regex_t *regex)
4050 regmatch_t regmatch;
4051 struct got_pathlist_entry *pe;
4053 *have_match = 0;
4055 TAILQ_FOREACH(pe, changed_paths, entry) {
4056 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4057 *have_match = 1;
4058 break;
4063 static const struct got_error *
4064 match_patch(int *have_match, struct got_commit_object *commit,
4065 struct got_object_id *id, const char *path, int diff_context,
4066 struct got_repository *repo, regex_t *regex, FILE *f)
4068 const struct got_error *err = NULL;
4069 char *line = NULL;
4070 size_t linesize = 0;
4071 regmatch_t regmatch;
4073 *have_match = 0;
4075 err = got_opentemp_truncate(f);
4076 if (err)
4077 return err;
4079 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4080 if (err)
4081 goto done;
4083 if (fseeko(f, 0L, SEEK_SET) == -1) {
4084 err = got_error_from_errno("fseeko");
4085 goto done;
4088 while (getline(&line, &linesize, f) != -1) {
4089 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4090 *have_match = 1;
4091 break;
4094 done:
4095 free(line);
4096 return err;
4099 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4101 static const struct got_error*
4102 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4103 struct got_object_id *id, struct got_repository *repo,
4104 int local_only)
4106 static const struct got_error *err = NULL;
4107 struct got_reflist_entry *re;
4108 char *s;
4109 const char *name;
4111 *refs_str = NULL;
4113 TAILQ_FOREACH(re, refs, entry) {
4114 struct got_tag_object *tag = NULL;
4115 struct got_object_id *ref_id;
4116 int cmp;
4118 name = got_ref_get_name(re->ref);
4119 if (strcmp(name, GOT_REF_HEAD) == 0)
4120 continue;
4121 if (strncmp(name, "refs/", 5) == 0)
4122 name += 5;
4123 if (strncmp(name, "got/", 4) == 0)
4124 continue;
4125 if (strncmp(name, "heads/", 6) == 0)
4126 name += 6;
4127 if (strncmp(name, "remotes/", 8) == 0) {
4128 if (local_only)
4129 continue;
4130 name += 8;
4131 s = strstr(name, "/" GOT_REF_HEAD);
4132 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4133 continue;
4135 err = got_ref_resolve(&ref_id, repo, re->ref);
4136 if (err)
4137 break;
4138 if (strncmp(name, "tags/", 5) == 0) {
4139 err = got_object_open_as_tag(&tag, repo, ref_id);
4140 if (err) {
4141 if (err->code != GOT_ERR_OBJ_TYPE) {
4142 free(ref_id);
4143 break;
4145 /* Ref points at something other than a tag. */
4146 err = NULL;
4147 tag = NULL;
4150 cmp = got_object_id_cmp(tag ?
4151 got_object_tag_get_object_id(tag) : ref_id, id);
4152 free(ref_id);
4153 if (tag)
4154 got_object_tag_close(tag);
4155 if (cmp != 0)
4156 continue;
4157 s = *refs_str;
4158 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4159 s ? ", " : "", name) == -1) {
4160 err = got_error_from_errno("asprintf");
4161 free(s);
4162 *refs_str = NULL;
4163 break;
4165 free(s);
4168 return err;
4171 static const struct got_error *
4172 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4173 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4175 const struct got_error *err = NULL;
4176 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4177 char *comma, *s, *nl;
4178 struct got_reflist_head *refs;
4179 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4180 struct tm tm;
4181 time_t committer_time;
4183 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4184 if (refs) {
4185 err = build_refs_str(&ref_str, refs, id, repo, 1);
4186 if (err)
4187 return err;
4189 /* Display the first matching ref only. */
4190 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4191 *comma = '\0';
4194 if (ref_str == NULL) {
4195 err = got_object_id_str(&id_str, id);
4196 if (err)
4197 return err;
4200 committer_time = got_object_commit_get_committer_time(commit);
4201 if (gmtime_r(&committer_time, &tm) == NULL) {
4202 err = got_error_from_errno("gmtime_r");
4203 goto done;
4205 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4206 err = got_error(GOT_ERR_NO_SPACE);
4207 goto done;
4210 err = got_object_commit_get_logmsg(&logmsg0, commit);
4211 if (err)
4212 goto done;
4214 s = logmsg0;
4215 while (isspace((unsigned char)s[0]))
4216 s++;
4218 nl = strchr(s, '\n');
4219 if (nl) {
4220 *nl = '\0';
4223 if (ref_str)
4224 printf("%s%-7s %s\n", datebuf, ref_str, s);
4225 else
4226 printf("%s%.7s %s\n", datebuf, id_str, s);
4228 if (fflush(stdout) != 0 && err == NULL)
4229 err = got_error_from_errno("fflush");
4230 done:
4231 free(id_str);
4232 free(ref_str);
4233 free(logmsg0);
4234 return err;
4237 static const struct got_error *
4238 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4240 struct got_pathlist_entry *pe;
4242 if (header != NULL)
4243 printf("%s\n", header);
4245 TAILQ_FOREACH(pe, dsa->paths, entry) {
4246 struct got_diff_changed_path *cp = pe->data;
4247 int pad = dsa->max_path_len - pe->path_len + 1;
4249 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4250 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4252 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4253 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4254 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4256 if (fflush(stdout) != 0)
4257 return got_error_from_errno("fflush");
4259 return NULL;
4262 static const struct got_error *
4263 printfile(FILE *f)
4265 char buf[8192];
4266 size_t r;
4268 if (fseeko(f, 0L, SEEK_SET) == -1)
4269 return got_error_from_errno("fseek");
4271 for (;;) {
4272 r = fread(buf, 1, sizeof(buf), f);
4273 if (r == 0) {
4274 if (ferror(f))
4275 return got_error_from_errno("fread");
4276 if (feof(f))
4277 break;
4279 if (fwrite(buf, 1, r, stdout) != r)
4280 return got_ferror(stdout, GOT_ERR_IO);
4283 return NULL;
4286 static const struct got_error *
4287 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4288 struct got_repository *repo, const char *path,
4289 struct got_pathlist_head *changed_paths,
4290 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4291 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4292 const char *prefix)
4294 const struct got_error *err = NULL;
4295 FILE *f = NULL;
4296 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4297 char datebuf[26];
4298 time_t committer_time;
4299 const char *author, *committer;
4300 char *refs_str = NULL;
4302 err = got_object_id_str(&id_str, id);
4303 if (err)
4304 return err;
4306 if (custom_refs_str == NULL) {
4307 struct got_reflist_head *refs;
4308 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4309 if (refs) {
4310 err = build_refs_str(&refs_str, refs, id, repo, 0);
4311 if (err)
4312 goto done;
4316 printf(GOT_COMMIT_SEP_STR);
4317 if (custom_refs_str)
4318 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4319 custom_refs_str);
4320 else
4321 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4322 refs_str ? " (" : "", refs_str ? refs_str : "",
4323 refs_str ? ")" : "");
4324 free(id_str);
4325 id_str = NULL;
4326 free(refs_str);
4327 refs_str = NULL;
4328 printf("from: %s\n", got_object_commit_get_author(commit));
4329 author = got_object_commit_get_author(commit);
4330 committer = got_object_commit_get_committer(commit);
4331 if (strcmp(author, committer) != 0)
4332 printf("via: %s\n", committer);
4333 committer_time = got_object_commit_get_committer_time(commit);
4334 datestr = get_datestr(&committer_time, datebuf);
4335 if (datestr)
4336 printf("date: %s UTC\n", datestr);
4337 if (got_object_commit_get_nparents(commit) > 1) {
4338 const struct got_object_id_queue *parent_ids;
4339 struct got_object_qid *qid;
4340 int n = 1;
4341 parent_ids = got_object_commit_get_parent_ids(commit);
4342 STAILQ_FOREACH(qid, parent_ids, entry) {
4343 err = got_object_id_str(&id_str, &qid->id);
4344 if (err)
4345 goto done;
4346 printf("parent %d: %s\n", n++, id_str);
4347 free(id_str);
4348 id_str = NULL;
4352 err = got_object_commit_get_logmsg(&logmsg0, commit);
4353 if (err)
4354 goto done;
4356 logmsg = logmsg0;
4357 do {
4358 line = strsep(&logmsg, "\n");
4359 if (line)
4360 printf(" %s\n", line);
4361 } while (line);
4362 free(logmsg0);
4364 if (changed_paths && diffstat == NULL) {
4365 struct got_pathlist_entry *pe;
4367 TAILQ_FOREACH(pe, changed_paths, entry) {
4368 struct got_diff_changed_path *cp = pe->data;
4370 printf(" %c %s\n", cp->status, pe->path);
4372 printf("\n");
4374 if (show_patch) {
4375 if (diffstat) {
4376 f = got_opentemp();
4377 if (f == NULL) {
4378 err = got_error_from_errno("got_opentemp");
4379 goto done;
4383 err = print_patch(commit, id, path, diff_context, diffstat,
4384 repo, diffstat == NULL ? stdout : f);
4385 if (err)
4386 goto done;
4388 if (diffstat) {
4389 err = print_diffstat(diffstat, NULL);
4390 if (err)
4391 goto done;
4392 if (show_patch) {
4393 err = printfile(f);
4394 if (err)
4395 goto done;
4398 if (show_patch)
4399 printf("\n");
4401 if (fflush(stdout) != 0 && err == NULL)
4402 err = got_error_from_errno("fflush");
4403 done:
4404 if (f && fclose(f) == EOF && err == NULL)
4405 err = got_error_from_errno("fclose");
4406 free(id_str);
4407 free(refs_str);
4408 return err;
4411 static const struct got_error *
4412 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4413 struct got_repository *repo, const char *path, int show_changed_paths,
4414 int show_diffstat, int show_patch, const char *search_pattern,
4415 int diff_context, int limit, int log_branches, int reverse_display_order,
4416 struct got_reflist_object_id_map *refs_idmap, int one_line,
4417 FILE *tmpfile)
4419 const struct got_error *err;
4420 struct got_commit_graph *graph;
4421 regex_t regex;
4422 int have_match;
4423 struct got_object_id_queue reversed_commits;
4424 struct got_object_qid *qid;
4425 struct got_commit_object *commit;
4426 struct got_pathlist_head changed_paths;
4428 STAILQ_INIT(&reversed_commits);
4429 TAILQ_INIT(&changed_paths);
4431 if (search_pattern && regcomp(&regex, search_pattern,
4432 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4433 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4435 err = got_commit_graph_open(&graph, path, !log_branches);
4436 if (err)
4437 return err;
4438 err = got_commit_graph_iter_start(graph, root_id, repo,
4439 check_cancelled, NULL);
4440 if (err)
4441 goto done;
4442 for (;;) {
4443 struct got_object_id id;
4444 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4445 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4447 if (sigint_received || sigpipe_received)
4448 break;
4450 err = got_commit_graph_iter_next(&id, graph, repo,
4451 check_cancelled, NULL);
4452 if (err) {
4453 if (err->code == GOT_ERR_ITER_COMPLETED)
4454 err = NULL;
4455 break;
4458 err = got_object_open_as_commit(&commit, repo, &id);
4459 if (err)
4460 break;
4462 if ((show_changed_paths || (show_diffstat && !show_patch))
4463 && !reverse_display_order) {
4464 err = get_changed_paths(&changed_paths, commit, repo,
4465 show_diffstat ? &dsa : NULL);
4466 if (err)
4467 break;
4470 if (search_pattern) {
4471 err = match_commit(&have_match, &id, commit, &regex);
4472 if (err) {
4473 got_object_commit_close(commit);
4474 break;
4476 if (have_match == 0 && show_changed_paths)
4477 match_changed_paths(&have_match,
4478 &changed_paths, &regex);
4479 if (have_match == 0 && show_patch) {
4480 err = match_patch(&have_match, commit, &id,
4481 path, diff_context, repo, &regex, tmpfile);
4482 if (err)
4483 break;
4485 if (have_match == 0) {
4486 got_object_commit_close(commit);
4487 got_pathlist_free(&changed_paths,
4488 GOT_PATHLIST_FREE_ALL);
4489 continue;
4493 if (reverse_display_order) {
4494 err = got_object_qid_alloc(&qid, &id);
4495 if (err)
4496 break;
4497 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4498 got_object_commit_close(commit);
4499 } else {
4500 if (one_line)
4501 err = print_commit_oneline(commit, &id,
4502 repo, refs_idmap);
4503 else
4504 err = print_commit(commit, &id, repo, path,
4505 (show_changed_paths || show_diffstat) ?
4506 &changed_paths : NULL,
4507 show_diffstat ? &dsa : NULL, show_patch,
4508 diff_context, refs_idmap, NULL, NULL);
4509 got_object_commit_close(commit);
4510 if (err)
4511 break;
4513 if ((limit && --limit == 0) ||
4514 (end_id && got_object_id_cmp(&id, end_id) == 0))
4515 break;
4517 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4519 if (reverse_display_order) {
4520 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4521 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4522 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4524 err = got_object_open_as_commit(&commit, repo,
4525 &qid->id);
4526 if (err)
4527 break;
4528 if (show_changed_paths ||
4529 (show_diffstat && !show_patch)) {
4530 err = get_changed_paths(&changed_paths, commit,
4531 repo, show_diffstat ? &dsa : NULL);
4532 if (err)
4533 break;
4535 if (one_line)
4536 err = print_commit_oneline(commit, &qid->id,
4537 repo, refs_idmap);
4538 else
4539 err = print_commit(commit, &qid->id, repo, path,
4540 (show_changed_paths || show_diffstat) ?
4541 &changed_paths : NULL,
4542 show_diffstat ? &dsa : NULL, show_patch,
4543 diff_context, refs_idmap, NULL, NULL);
4544 got_object_commit_close(commit);
4545 if (err)
4546 break;
4547 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4550 done:
4551 while (!STAILQ_EMPTY(&reversed_commits)) {
4552 qid = STAILQ_FIRST(&reversed_commits);
4553 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4554 got_object_qid_free(qid);
4556 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4557 if (search_pattern)
4558 regfree(&regex);
4559 got_commit_graph_close(graph);
4560 return err;
4563 __dead static void
4564 usage_log(void)
4566 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4567 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4568 "[path]\n", getprogname());
4569 exit(1);
4572 static int
4573 get_default_log_limit(void)
4575 const char *got_default_log_limit;
4576 long long n;
4577 const char *errstr;
4579 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4580 if (got_default_log_limit == NULL)
4581 return 0;
4582 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4583 if (errstr != NULL)
4584 return 0;
4585 return n;
4588 static const struct got_error *
4589 cmd_log(int argc, char *argv[])
4591 const struct got_error *error;
4592 struct got_repository *repo = NULL;
4593 struct got_worktree *worktree = NULL;
4594 struct got_object_id *start_id = NULL, *end_id = NULL;
4595 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4596 char *keyword_idstr = NULL;
4597 const char *start_commit = NULL, *end_commit = NULL;
4598 const char *search_pattern = NULL;
4599 int diff_context = -1, ch;
4600 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4601 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4602 const char *errstr;
4603 struct got_reflist_head refs;
4604 struct got_reflist_object_id_map *refs_idmap = NULL;
4605 FILE *tmpfile = NULL;
4606 int *pack_fds = NULL;
4608 TAILQ_INIT(&refs);
4610 #ifndef PROFILE
4611 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4612 NULL)
4613 == -1)
4614 err(1, "pledge");
4615 #endif
4617 limit = get_default_log_limit();
4619 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4620 switch (ch) {
4621 case 'b':
4622 log_branches = 1;
4623 break;
4624 case 'C':
4625 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4626 &errstr);
4627 if (errstr != NULL)
4628 errx(1, "number of context lines is %s: %s",
4629 errstr, optarg);
4630 break;
4631 case 'c':
4632 start_commit = optarg;
4633 break;
4634 case 'd':
4635 show_diffstat = 1;
4636 break;
4637 case 'l':
4638 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4639 if (errstr != NULL)
4640 errx(1, "number of commits is %s: %s",
4641 errstr, optarg);
4642 break;
4643 case 'P':
4644 show_changed_paths = 1;
4645 break;
4646 case 'p':
4647 show_patch = 1;
4648 break;
4649 case 'R':
4650 reverse_display_order = 1;
4651 break;
4652 case 'r':
4653 repo_path = realpath(optarg, NULL);
4654 if (repo_path == NULL)
4655 return got_error_from_errno2("realpath",
4656 optarg);
4657 got_path_strip_trailing_slashes(repo_path);
4658 break;
4659 case 'S':
4660 search_pattern = optarg;
4661 break;
4662 case 's':
4663 one_line = 1;
4664 break;
4665 case 'x':
4666 end_commit = optarg;
4667 break;
4668 default:
4669 usage_log();
4670 /* NOTREACHED */
4674 argc -= optind;
4675 argv += optind;
4677 if (diff_context == -1)
4678 diff_context = 3;
4679 else if (!show_patch)
4680 errx(1, "-C requires -p");
4682 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4683 errx(1, "cannot use -s with -d, -p or -P");
4685 cwd = getcwd(NULL, 0);
4686 if (cwd == NULL) {
4687 error = got_error_from_errno("getcwd");
4688 goto done;
4691 error = got_repo_pack_fds_open(&pack_fds);
4692 if (error != NULL)
4693 goto done;
4695 if (repo_path == NULL) {
4696 error = got_worktree_open(&worktree, cwd,
4697 GOT_WORKTREE_GOT_DIR);
4698 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4699 goto done;
4700 error = NULL;
4703 if (argc == 1) {
4704 if (worktree) {
4705 error = got_worktree_resolve_path(&path, worktree,
4706 argv[0]);
4707 if (error)
4708 goto done;
4709 } else {
4710 path = strdup(argv[0]);
4711 if (path == NULL) {
4712 error = got_error_from_errno("strdup");
4713 goto done;
4716 } else if (argc != 0)
4717 usage_log();
4719 if (repo_path == NULL) {
4720 repo_path = worktree ?
4721 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4723 if (repo_path == NULL) {
4724 error = got_error_from_errno("strdup");
4725 goto done;
4728 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4729 if (error != NULL)
4730 goto done;
4732 error = apply_unveil(got_repo_get_path(repo), 1,
4733 worktree ? got_worktree_get_root_path(worktree) : NULL);
4734 if (error)
4735 goto done;
4737 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4738 if (error)
4739 goto done;
4741 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4742 if (error)
4743 goto done;
4745 if (start_commit == NULL) {
4746 struct got_reference *head_ref;
4747 struct got_commit_object *commit = NULL;
4748 error = got_ref_open(&head_ref, repo,
4749 worktree ? got_worktree_get_head_ref_name(worktree)
4750 : GOT_REF_HEAD, 0);
4751 if (error != NULL)
4752 goto done;
4753 error = got_ref_resolve(&start_id, repo, head_ref);
4754 got_ref_close(head_ref);
4755 if (error != NULL)
4756 goto done;
4757 error = got_object_open_as_commit(&commit, repo,
4758 start_id);
4759 if (error != NULL)
4760 goto done;
4761 got_object_commit_close(commit);
4762 } else {
4763 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4764 repo, worktree);
4765 if (error != NULL)
4766 goto done;
4767 if (keyword_idstr != NULL)
4768 start_commit = keyword_idstr;
4770 error = got_repo_match_object_id(&start_id, NULL,
4771 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4772 if (error != NULL)
4773 goto done;
4775 if (end_commit != NULL) {
4776 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4777 repo, worktree);
4778 if (error != NULL)
4779 goto done;
4780 if (keyword_idstr != NULL)
4781 end_commit = keyword_idstr;
4783 error = got_repo_match_object_id(&end_id, NULL,
4784 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4785 if (error != NULL)
4786 goto done;
4789 if (worktree) {
4791 * If a path was specified on the command line it was resolved
4792 * to a path in the work tree above. Prepend the work tree's
4793 * path prefix to obtain the corresponding in-repository path.
4795 if (path) {
4796 const char *prefix;
4797 prefix = got_worktree_get_path_prefix(worktree);
4798 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4799 (path[0] != '\0') ? "/" : "", path) == -1) {
4800 error = got_error_from_errno("asprintf");
4801 goto done;
4804 } else
4805 error = got_repo_map_path(&in_repo_path, repo,
4806 path ? path : "");
4807 if (error != NULL)
4808 goto done;
4809 if (in_repo_path) {
4810 free(path);
4811 path = in_repo_path;
4814 if (worktree) {
4815 /* Release work tree lock. */
4816 got_worktree_close(worktree);
4817 worktree = NULL;
4820 if (search_pattern && show_patch) {
4821 tmpfile = got_opentemp();
4822 if (tmpfile == NULL) {
4823 error = got_error_from_errno("got_opentemp");
4824 goto done;
4828 error = print_commits(start_id, end_id, repo, path ? path : "",
4829 show_changed_paths, show_diffstat, show_patch, search_pattern,
4830 diff_context, limit, log_branches, reverse_display_order,
4831 refs_idmap, one_line, tmpfile);
4832 done:
4833 free(path);
4834 free(repo_path);
4835 free(cwd);
4836 free(start_id);
4837 free(end_id);
4838 free(keyword_idstr);
4839 if (worktree)
4840 got_worktree_close(worktree);
4841 if (repo) {
4842 const struct got_error *close_err = got_repo_close(repo);
4843 if (error == NULL)
4844 error = close_err;
4846 if (pack_fds) {
4847 const struct got_error *pack_err =
4848 got_repo_pack_fds_close(pack_fds);
4849 if (error == NULL)
4850 error = pack_err;
4852 if (refs_idmap)
4853 got_reflist_object_id_map_free(refs_idmap);
4854 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4855 error = got_error_from_errno("fclose");
4856 got_ref_list_free(&refs);
4857 return error;
4860 __dead static void
4861 usage_diff(void)
4863 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4864 "[-r repository-path] [object1 object2 | path ...]\n",
4865 getprogname());
4866 exit(1);
4869 struct print_diff_arg {
4870 struct got_repository *repo;
4871 struct got_worktree *worktree;
4872 struct got_diffstat_cb_arg *diffstat;
4873 int diff_context;
4874 const char *id_str;
4875 int header_shown;
4876 int diff_staged;
4877 enum got_diff_algorithm diff_algo;
4878 int ignore_whitespace;
4879 int force_text_diff;
4880 FILE *f1;
4881 FILE *f2;
4882 FILE *outfile;
4886 * Create a file which contains the target path of a symlink so we can feed
4887 * it as content to the diff engine.
4889 static const struct got_error *
4890 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4891 const char *abspath)
4893 const struct got_error *err = NULL;
4894 char target_path[PATH_MAX];
4895 ssize_t target_len, outlen;
4897 *fd = -1;
4899 if (dirfd != -1) {
4900 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4901 if (target_len == -1)
4902 return got_error_from_errno2("readlinkat", abspath);
4903 } else {
4904 target_len = readlink(abspath, target_path, PATH_MAX);
4905 if (target_len == -1)
4906 return got_error_from_errno2("readlink", abspath);
4909 *fd = got_opentempfd();
4910 if (*fd == -1)
4911 return got_error_from_errno("got_opentempfd");
4913 outlen = write(*fd, target_path, target_len);
4914 if (outlen == -1) {
4915 err = got_error_from_errno("got_opentempfd");
4916 goto done;
4919 if (lseek(*fd, 0, SEEK_SET) == -1) {
4920 err = got_error_from_errno2("lseek", abspath);
4921 goto done;
4923 done:
4924 if (err) {
4925 close(*fd);
4926 *fd = -1;
4928 return err;
4931 static const struct got_error *
4932 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4933 const char *path, struct got_object_id *blob_id,
4934 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4935 int dirfd, const char *de_name)
4937 struct print_diff_arg *a = arg;
4938 const struct got_error *err = NULL;
4939 struct got_blob_object *blob1 = NULL;
4940 int fd = -1, fd1 = -1, fd2 = -1;
4941 FILE *f2 = NULL;
4942 char *abspath = NULL, *label1 = NULL;
4943 struct stat sb;
4944 off_t size1 = 0;
4945 int f2_exists = 0;
4947 memset(&sb, 0, sizeof(sb));
4949 if (a->diff_staged) {
4950 if (staged_status != GOT_STATUS_MODIFY &&
4951 staged_status != GOT_STATUS_ADD &&
4952 staged_status != GOT_STATUS_DELETE)
4953 return NULL;
4954 } else {
4955 if (staged_status == GOT_STATUS_DELETE)
4956 return NULL;
4957 if (status == GOT_STATUS_NONEXISTENT)
4958 return got_error_set_errno(ENOENT, path);
4959 if (status != GOT_STATUS_MODIFY &&
4960 status != GOT_STATUS_ADD &&
4961 status != GOT_STATUS_DELETE &&
4962 status != GOT_STATUS_CONFLICT)
4963 return NULL;
4966 err = got_opentemp_truncate(a->f1);
4967 if (err)
4968 return got_error_from_errno("got_opentemp_truncate");
4969 err = got_opentemp_truncate(a->f2);
4970 if (err)
4971 return got_error_from_errno("got_opentemp_truncate");
4973 if (!a->header_shown) {
4974 if (fprintf(a->outfile, "diff %s%s\n",
4975 a->diff_staged ? "-s " : "",
4976 got_worktree_get_root_path(a->worktree)) < 0) {
4977 err = got_error_from_errno("fprintf");
4978 goto done;
4980 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4981 err = got_error_from_errno("fprintf");
4982 goto done;
4984 if (fprintf(a->outfile, "path + %s%s\n",
4985 got_worktree_get_root_path(a->worktree),
4986 a->diff_staged ? " (staged changes)" : "") < 0) {
4987 err = got_error_from_errno("fprintf");
4988 goto done;
4990 a->header_shown = 1;
4993 if (a->diff_staged) {
4994 const char *label1 = NULL, *label2 = NULL;
4995 switch (staged_status) {
4996 case GOT_STATUS_MODIFY:
4997 label1 = path;
4998 label2 = path;
4999 break;
5000 case GOT_STATUS_ADD:
5001 label2 = path;
5002 break;
5003 case GOT_STATUS_DELETE:
5004 label1 = path;
5005 break;
5006 default:
5007 return got_error(GOT_ERR_FILE_STATUS);
5009 fd1 = got_opentempfd();
5010 if (fd1 == -1) {
5011 err = got_error_from_errno("got_opentempfd");
5012 goto done;
5014 fd2 = got_opentempfd();
5015 if (fd2 == -1) {
5016 err = got_error_from_errno("got_opentempfd");
5017 goto done;
5019 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5020 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5021 a->diff_algo, a->diff_context, a->ignore_whitespace,
5022 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5023 goto done;
5026 fd1 = got_opentempfd();
5027 if (fd1 == -1) {
5028 err = got_error_from_errno("got_opentempfd");
5029 goto done;
5032 if (staged_status == GOT_STATUS_ADD ||
5033 staged_status == GOT_STATUS_MODIFY) {
5034 char *id_str;
5035 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5036 8192, fd1);
5037 if (err)
5038 goto done;
5039 err = got_object_id_str(&id_str, staged_blob_id);
5040 if (err)
5041 goto done;
5042 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5043 err = got_error_from_errno("asprintf");
5044 free(id_str);
5045 goto done;
5047 free(id_str);
5048 } else if (status != GOT_STATUS_ADD) {
5049 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5050 fd1);
5051 if (err)
5052 goto done;
5055 if (status != GOT_STATUS_DELETE) {
5056 if (asprintf(&abspath, "%s/%s",
5057 got_worktree_get_root_path(a->worktree), path) == -1) {
5058 err = got_error_from_errno("asprintf");
5059 goto done;
5062 if (dirfd != -1) {
5063 fd = openat(dirfd, de_name,
5064 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5065 if (fd == -1) {
5066 if (!got_err_open_nofollow_on_symlink()) {
5067 err = got_error_from_errno2("openat",
5068 abspath);
5069 goto done;
5071 err = get_symlink_target_file(&fd, dirfd,
5072 de_name, abspath);
5073 if (err)
5074 goto done;
5076 } else {
5077 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5078 if (fd == -1) {
5079 if (!got_err_open_nofollow_on_symlink()) {
5080 err = got_error_from_errno2("open",
5081 abspath);
5082 goto done;
5084 err = get_symlink_target_file(&fd, dirfd,
5085 de_name, abspath);
5086 if (err)
5087 goto done;
5090 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5091 err = got_error_from_errno2("fstatat", abspath);
5092 goto done;
5094 f2 = fdopen(fd, "r");
5095 if (f2 == NULL) {
5096 err = got_error_from_errno2("fdopen", abspath);
5097 goto done;
5099 fd = -1;
5100 f2_exists = 1;
5103 if (blob1) {
5104 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5105 a->f1, blob1);
5106 if (err)
5107 goto done;
5110 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5111 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5112 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5113 done:
5114 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5115 err = got_error_from_errno("close");
5116 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5117 err = got_error_from_errno("close");
5118 if (blob1)
5119 got_object_blob_close(blob1);
5120 if (fd != -1 && close(fd) == -1 && err == NULL)
5121 err = got_error_from_errno("close");
5122 if (f2 && fclose(f2) == EOF && err == NULL)
5123 err = got_error_from_errno("fclose");
5124 free(abspath);
5125 return err;
5128 static const struct got_error *
5129 cmd_diff(int argc, char *argv[])
5131 const struct got_error *error;
5132 struct got_repository *repo = NULL;
5133 struct got_worktree *worktree = NULL;
5134 char *cwd = NULL, *repo_path = NULL;
5135 const char *commit_args[2] = { NULL, NULL };
5136 int ncommit_args = 0;
5137 struct got_object_id *ids[2] = { NULL, NULL };
5138 char *labels[2] = { NULL, NULL };
5139 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5140 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5141 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5142 const char *errstr;
5143 struct got_reflist_head refs;
5144 struct got_pathlist_head diffstat_paths, paths;
5145 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5146 int fd1 = -1, fd2 = -1;
5147 int *pack_fds = NULL;
5148 struct got_diffstat_cb_arg dsa;
5150 memset(&dsa, 0, sizeof(dsa));
5152 TAILQ_INIT(&refs);
5153 TAILQ_INIT(&paths);
5154 TAILQ_INIT(&diffstat_paths);
5156 #ifndef PROFILE
5157 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5158 NULL) == -1)
5159 err(1, "pledge");
5160 #endif
5162 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5163 switch (ch) {
5164 case 'a':
5165 force_text_diff = 1;
5166 break;
5167 case 'C':
5168 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5169 &errstr);
5170 if (errstr != NULL)
5171 errx(1, "number of context lines is %s: %s",
5172 errstr, optarg);
5173 break;
5174 case 'c':
5175 if (ncommit_args >= 2)
5176 errx(1, "too many -c options used");
5177 commit_args[ncommit_args++] = optarg;
5178 break;
5179 case 'd':
5180 show_diffstat = 1;
5181 break;
5182 case 'P':
5183 force_path = 1;
5184 break;
5185 case 'r':
5186 repo_path = realpath(optarg, NULL);
5187 if (repo_path == NULL)
5188 return got_error_from_errno2("realpath",
5189 optarg);
5190 got_path_strip_trailing_slashes(repo_path);
5191 rflag = 1;
5192 break;
5193 case 's':
5194 diff_staged = 1;
5195 break;
5196 case 'w':
5197 ignore_whitespace = 1;
5198 break;
5199 default:
5200 usage_diff();
5201 /* NOTREACHED */
5205 argc -= optind;
5206 argv += optind;
5208 cwd = getcwd(NULL, 0);
5209 if (cwd == NULL) {
5210 error = got_error_from_errno("getcwd");
5211 goto done;
5214 error = got_repo_pack_fds_open(&pack_fds);
5215 if (error != NULL)
5216 goto done;
5218 if (repo_path == NULL) {
5219 error = got_worktree_open(&worktree, cwd,
5220 GOT_WORKTREE_GOT_DIR);
5221 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5222 goto done;
5223 else
5224 error = NULL;
5225 if (worktree) {
5226 repo_path =
5227 strdup(got_worktree_get_repo_path(worktree));
5228 if (repo_path == NULL) {
5229 error = got_error_from_errno("strdup");
5230 goto done;
5232 } else {
5233 repo_path = strdup(cwd);
5234 if (repo_path == NULL) {
5235 error = got_error_from_errno("strdup");
5236 goto done;
5241 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5242 free(repo_path);
5243 if (error != NULL)
5244 goto done;
5246 if (show_diffstat) {
5247 dsa.paths = &diffstat_paths;
5248 dsa.force_text = force_text_diff;
5249 dsa.ignore_ws = ignore_whitespace;
5250 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5253 if (rflag || worktree == NULL || ncommit_args > 0) {
5254 if (force_path) {
5255 error = got_error_msg(GOT_ERR_NOT_IMPL,
5256 "-P option can only be used when diffing "
5257 "a work tree");
5258 goto done;
5260 if (diff_staged) {
5261 error = got_error_msg(GOT_ERR_NOT_IMPL,
5262 "-s option can only be used when diffing "
5263 "a work tree");
5264 goto done;
5268 error = apply_unveil(got_repo_get_path(repo), 1,
5269 worktree ? got_worktree_get_root_path(worktree) : NULL);
5270 if (error)
5271 goto done;
5273 if ((!force_path && argc == 2) || ncommit_args > 0) {
5274 int obj_type = (ncommit_args > 0 ?
5275 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5276 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5277 NULL);
5278 if (error)
5279 goto done;
5280 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5281 const char *arg;
5282 char *keyword_idstr = NULL;
5284 if (ncommit_args > 0)
5285 arg = commit_args[i];
5286 else
5287 arg = argv[i];
5289 error = got_keyword_to_idstr(&keyword_idstr, arg,
5290 repo, worktree);
5291 if (error != NULL)
5292 goto done;
5293 if (keyword_idstr != NULL)
5294 arg = keyword_idstr;
5296 error = got_repo_match_object_id(&ids[i], &labels[i],
5297 arg, obj_type, &refs, repo);
5298 free(keyword_idstr);
5299 if (error) {
5300 if (error->code != GOT_ERR_NOT_REF &&
5301 error->code != GOT_ERR_NO_OBJ)
5302 goto done;
5303 if (ncommit_args > 0)
5304 goto done;
5305 error = NULL;
5306 break;
5311 f1 = got_opentemp();
5312 if (f1 == NULL) {
5313 error = got_error_from_errno("got_opentemp");
5314 goto done;
5317 f2 = got_opentemp();
5318 if (f2 == NULL) {
5319 error = got_error_from_errno("got_opentemp");
5320 goto done;
5323 outfile = got_opentemp();
5324 if (outfile == NULL) {
5325 error = got_error_from_errno("got_opentemp");
5326 goto done;
5329 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5330 struct print_diff_arg arg;
5331 char *id_str;
5333 if (worktree == NULL) {
5334 if (argc == 2 && ids[0] == NULL) {
5335 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5336 goto done;
5337 } else if (argc == 2 && ids[1] == NULL) {
5338 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5339 goto done;
5340 } else if (argc > 0) {
5341 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5342 "%s", "specified paths cannot be resolved");
5343 goto done;
5344 } else {
5345 error = got_error(GOT_ERR_NOT_WORKTREE);
5346 goto done;
5350 error = get_worktree_paths_from_argv(&paths, argc, argv,
5351 worktree);
5352 if (error)
5353 goto done;
5355 error = got_object_id_str(&id_str,
5356 got_worktree_get_base_commit_id(worktree));
5357 if (error)
5358 goto done;
5359 arg.repo = repo;
5360 arg.worktree = worktree;
5361 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5362 arg.diff_context = diff_context;
5363 arg.id_str = id_str;
5364 arg.header_shown = 0;
5365 arg.diff_staged = diff_staged;
5366 arg.ignore_whitespace = ignore_whitespace;
5367 arg.force_text_diff = force_text_diff;
5368 arg.diffstat = show_diffstat ? &dsa : NULL;
5369 arg.f1 = f1;
5370 arg.f2 = f2;
5371 arg.outfile = outfile;
5373 error = got_worktree_status(worktree, &paths, repo, 0,
5374 print_diff, &arg, check_cancelled, NULL);
5375 free(id_str);
5376 if (error)
5377 goto done;
5379 if (show_diffstat && dsa.nfiles > 0) {
5380 char *header;
5382 if (asprintf(&header, "diffstat %s%s",
5383 diff_staged ? "-s " : "",
5384 got_worktree_get_root_path(worktree)) == -1) {
5385 error = got_error_from_errno("asprintf");
5386 goto done;
5389 error = print_diffstat(&dsa, header);
5390 free(header);
5391 if (error)
5392 goto done;
5395 error = printfile(outfile);
5396 goto done;
5399 if (ncommit_args == 1) {
5400 struct got_commit_object *commit;
5401 error = got_object_open_as_commit(&commit, repo, ids[0]);
5402 if (error)
5403 goto done;
5405 labels[1] = labels[0];
5406 ids[1] = ids[0];
5407 if (got_object_commit_get_nparents(commit) > 0) {
5408 const struct got_object_id_queue *pids;
5409 struct got_object_qid *pid;
5410 pids = got_object_commit_get_parent_ids(commit);
5411 pid = STAILQ_FIRST(pids);
5412 ids[0] = got_object_id_dup(&pid->id);
5413 if (ids[0] == NULL) {
5414 error = got_error_from_errno(
5415 "got_object_id_dup");
5416 got_object_commit_close(commit);
5417 goto done;
5419 error = got_object_id_str(&labels[0], ids[0]);
5420 if (error) {
5421 got_object_commit_close(commit);
5422 goto done;
5424 } else {
5425 ids[0] = NULL;
5426 labels[0] = strdup("/dev/null");
5427 if (labels[0] == NULL) {
5428 error = got_error_from_errno("strdup");
5429 got_object_commit_close(commit);
5430 goto done;
5434 got_object_commit_close(commit);
5437 if (ncommit_args == 0 && argc > 2) {
5438 error = got_error_msg(GOT_ERR_BAD_PATH,
5439 "path arguments cannot be used when diffing two objects");
5440 goto done;
5443 if (ids[0]) {
5444 error = got_object_get_type(&type1, repo, ids[0]);
5445 if (error)
5446 goto done;
5449 error = got_object_get_type(&type2, repo, ids[1]);
5450 if (error)
5451 goto done;
5452 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5453 error = got_error(GOT_ERR_OBJ_TYPE);
5454 goto done;
5456 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5457 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5458 "path arguments cannot be used when diffing blobs");
5459 goto done;
5462 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5463 char *in_repo_path;
5464 struct got_pathlist_entry *new;
5465 if (worktree) {
5466 const char *prefix;
5467 char *p;
5468 error = got_worktree_resolve_path(&p, worktree,
5469 argv[i]);
5470 if (error)
5471 goto done;
5472 prefix = got_worktree_get_path_prefix(worktree);
5473 while (prefix[0] == '/')
5474 prefix++;
5475 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5476 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5477 p) == -1) {
5478 error = got_error_from_errno("asprintf");
5479 free(p);
5480 goto done;
5482 free(p);
5483 } else {
5484 char *mapped_path, *s;
5485 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5486 if (error)
5487 goto done;
5488 s = mapped_path;
5489 while (s[0] == '/')
5490 s++;
5491 in_repo_path = strdup(s);
5492 if (in_repo_path == NULL) {
5493 error = got_error_from_errno("asprintf");
5494 free(mapped_path);
5495 goto done;
5497 free(mapped_path);
5500 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5501 if (error || new == NULL /* duplicate */)
5502 free(in_repo_path);
5503 if (error)
5504 goto done;
5507 if (worktree) {
5508 /* Release work tree lock. */
5509 got_worktree_close(worktree);
5510 worktree = NULL;
5513 fd1 = got_opentempfd();
5514 if (fd1 == -1) {
5515 error = got_error_from_errno("got_opentempfd");
5516 goto done;
5519 fd2 = got_opentempfd();
5520 if (fd2 == -1) {
5521 error = got_error_from_errno("got_opentempfd");
5522 goto done;
5525 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5526 case GOT_OBJ_TYPE_BLOB:
5527 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5528 fd1, fd2, ids[0], ids[1], NULL, NULL,
5529 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5530 ignore_whitespace, force_text_diff,
5531 show_diffstat ? &dsa : NULL, repo, outfile);
5532 break;
5533 case GOT_OBJ_TYPE_TREE:
5534 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5535 ids[0], ids[1], &paths, "", "",
5536 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5537 ignore_whitespace, force_text_diff,
5538 show_diffstat ? &dsa : NULL, repo, outfile);
5539 break;
5540 case GOT_OBJ_TYPE_COMMIT:
5541 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5542 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5543 fd1, fd2, ids[0], ids[1], &paths,
5544 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5545 ignore_whitespace, force_text_diff,
5546 show_diffstat ? &dsa : NULL, repo, outfile);
5547 break;
5548 default:
5549 error = got_error(GOT_ERR_OBJ_TYPE);
5551 if (error)
5552 goto done;
5554 if (show_diffstat && dsa.nfiles > 0) {
5555 char *header = NULL;
5557 if (asprintf(&header, "diffstat %s %s",
5558 labels[0], labels[1]) == -1) {
5559 error = got_error_from_errno("asprintf");
5560 goto done;
5563 error = print_diffstat(&dsa, header);
5564 free(header);
5565 if (error)
5566 goto done;
5569 error = printfile(outfile);
5571 done:
5572 free(labels[0]);
5573 free(labels[1]);
5574 free(ids[0]);
5575 free(ids[1]);
5576 if (worktree)
5577 got_worktree_close(worktree);
5578 if (repo) {
5579 const struct got_error *close_err = got_repo_close(repo);
5580 if (error == NULL)
5581 error = close_err;
5583 if (pack_fds) {
5584 const struct got_error *pack_err =
5585 got_repo_pack_fds_close(pack_fds);
5586 if (error == NULL)
5587 error = pack_err;
5589 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5590 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5591 got_ref_list_free(&refs);
5592 if (outfile && fclose(outfile) == EOF && error == NULL)
5593 error = got_error_from_errno("fclose");
5594 if (f1 && fclose(f1) == EOF && error == NULL)
5595 error = got_error_from_errno("fclose");
5596 if (f2 && fclose(f2) == EOF && error == NULL)
5597 error = got_error_from_errno("fclose");
5598 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5599 error = got_error_from_errno("close");
5600 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5601 error = got_error_from_errno("close");
5602 return error;
5605 __dead static void
5606 usage_blame(void)
5608 fprintf(stderr,
5609 "usage: %s blame [-c commit] [-r repository-path] path\n",
5610 getprogname());
5611 exit(1);
5614 struct blame_line {
5615 int annotated;
5616 char *id_str;
5617 char *committer;
5618 char datebuf[11]; /* YYYY-MM-DD + NUL */
5621 struct blame_cb_args {
5622 struct blame_line *lines;
5623 int nlines;
5624 int nlines_prec;
5625 int lineno_cur;
5626 off_t *line_offsets;
5627 FILE *f;
5628 struct got_repository *repo;
5631 static const struct got_error *
5632 blame_cb(void *arg, int nlines, int lineno,
5633 struct got_commit_object *commit, struct got_object_id *id)
5635 const struct got_error *err = NULL;
5636 struct blame_cb_args *a = arg;
5637 struct blame_line *bline;
5638 char *line = NULL;
5639 size_t linesize = 0;
5640 off_t offset;
5641 struct tm tm;
5642 time_t committer_time;
5644 if (nlines != a->nlines ||
5645 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5646 return got_error(GOT_ERR_RANGE);
5648 if (sigint_received)
5649 return got_error(GOT_ERR_ITER_COMPLETED);
5651 if (lineno == -1)
5652 return NULL; /* no change in this commit */
5654 /* Annotate this line. */
5655 bline = &a->lines[lineno - 1];
5656 if (bline->annotated)
5657 return NULL;
5658 err = got_object_id_str(&bline->id_str, id);
5659 if (err)
5660 return err;
5662 bline->committer = strdup(got_object_commit_get_committer(commit));
5663 if (bline->committer == NULL) {
5664 err = got_error_from_errno("strdup");
5665 goto done;
5668 committer_time = got_object_commit_get_committer_time(commit);
5669 if (gmtime_r(&committer_time, &tm) == NULL)
5670 return got_error_from_errno("gmtime_r");
5671 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5672 &tm) == 0) {
5673 err = got_error(GOT_ERR_NO_SPACE);
5674 goto done;
5676 bline->annotated = 1;
5678 /* Print lines annotated so far. */
5679 bline = &a->lines[a->lineno_cur - 1];
5680 if (!bline->annotated)
5681 goto done;
5683 offset = a->line_offsets[a->lineno_cur - 1];
5684 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5685 err = got_error_from_errno("fseeko");
5686 goto done;
5689 while (a->lineno_cur <= a->nlines && bline->annotated) {
5690 char *smallerthan, *at, *nl, *committer;
5691 size_t len;
5693 if (getline(&line, &linesize, a->f) == -1) {
5694 if (ferror(a->f))
5695 err = got_error_from_errno("getline");
5696 break;
5699 committer = bline->committer;
5700 smallerthan = strchr(committer, '<');
5701 if (smallerthan && smallerthan[1] != '\0')
5702 committer = smallerthan + 1;
5703 at = strchr(committer, '@');
5704 if (at)
5705 *at = '\0';
5706 len = strlen(committer);
5707 if (len >= 9)
5708 committer[8] = '\0';
5710 nl = strchr(line, '\n');
5711 if (nl)
5712 *nl = '\0';
5713 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5714 bline->id_str, bline->datebuf, committer, line);
5716 a->lineno_cur++;
5717 bline = &a->lines[a->lineno_cur - 1];
5719 done:
5720 free(line);
5721 return err;
5724 static const struct got_error *
5725 cmd_blame(int argc, char *argv[])
5727 const struct got_error *error;
5728 struct got_repository *repo = NULL;
5729 struct got_worktree *worktree = NULL;
5730 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5731 char *link_target = NULL;
5732 struct got_object_id *obj_id = NULL;
5733 struct got_object_id *commit_id = NULL;
5734 struct got_commit_object *commit = NULL;
5735 struct got_blob_object *blob = NULL;
5736 char *commit_id_str = NULL, *keyword_idstr = NULL;
5737 struct blame_cb_args bca;
5738 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5739 off_t filesize;
5740 int *pack_fds = NULL;
5741 FILE *f1 = NULL, *f2 = NULL;
5743 fd1 = got_opentempfd();
5744 if (fd1 == -1)
5745 return got_error_from_errno("got_opentempfd");
5747 memset(&bca, 0, sizeof(bca));
5749 #ifndef PROFILE
5750 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5751 NULL) == -1)
5752 err(1, "pledge");
5753 #endif
5755 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5756 switch (ch) {
5757 case 'c':
5758 commit_id_str = optarg;
5759 break;
5760 case 'r':
5761 repo_path = realpath(optarg, NULL);
5762 if (repo_path == NULL)
5763 return got_error_from_errno2("realpath",
5764 optarg);
5765 got_path_strip_trailing_slashes(repo_path);
5766 break;
5767 default:
5768 usage_blame();
5769 /* NOTREACHED */
5773 argc -= optind;
5774 argv += optind;
5776 if (argc == 1)
5777 path = argv[0];
5778 else
5779 usage_blame();
5781 cwd = getcwd(NULL, 0);
5782 if (cwd == NULL) {
5783 error = got_error_from_errno("getcwd");
5784 goto done;
5787 error = got_repo_pack_fds_open(&pack_fds);
5788 if (error != NULL)
5789 goto done;
5791 if (repo_path == NULL) {
5792 error = got_worktree_open(&worktree, cwd,
5793 GOT_WORKTREE_GOT_DIR);
5794 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5795 goto done;
5796 else
5797 error = NULL;
5798 if (worktree) {
5799 repo_path =
5800 strdup(got_worktree_get_repo_path(worktree));
5801 if (repo_path == NULL) {
5802 error = got_error_from_errno("strdup");
5803 if (error)
5804 goto done;
5806 } else {
5807 repo_path = strdup(cwd);
5808 if (repo_path == NULL) {
5809 error = got_error_from_errno("strdup");
5810 goto done;
5815 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5816 if (error != NULL)
5817 goto done;
5819 if (worktree) {
5820 const char *prefix = got_worktree_get_path_prefix(worktree);
5821 char *p;
5823 error = got_worktree_resolve_path(&p, worktree, path);
5824 if (error)
5825 goto done;
5826 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5827 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5828 p) == -1) {
5829 error = got_error_from_errno("asprintf");
5830 free(p);
5831 goto done;
5833 free(p);
5834 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5835 } else {
5836 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5837 if (error)
5838 goto done;
5839 error = got_repo_map_path(&in_repo_path, repo, path);
5841 if (error)
5842 goto done;
5844 if (commit_id_str == NULL) {
5845 struct got_reference *head_ref;
5846 error = got_ref_open(&head_ref, repo, worktree ?
5847 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5848 if (error != NULL)
5849 goto done;
5850 error = got_ref_resolve(&commit_id, repo, head_ref);
5851 got_ref_close(head_ref);
5852 if (error != NULL)
5853 goto done;
5854 } else {
5855 struct got_reflist_head refs;
5857 TAILQ_INIT(&refs);
5858 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5859 NULL);
5860 if (error)
5861 goto done;
5863 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5864 repo, worktree);
5865 if (error != NULL)
5866 goto done;
5867 if (keyword_idstr != NULL)
5868 commit_id_str = keyword_idstr;
5870 error = got_repo_match_object_id(&commit_id, NULL,
5871 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5872 got_ref_list_free(&refs);
5873 if (error)
5874 goto done;
5877 if (worktree) {
5878 /* Release work tree lock. */
5879 got_worktree_close(worktree);
5880 worktree = NULL;
5883 error = got_object_open_as_commit(&commit, repo, commit_id);
5884 if (error)
5885 goto done;
5887 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5888 commit, repo);
5889 if (error)
5890 goto done;
5892 error = got_object_id_by_path(&obj_id, repo, commit,
5893 link_target ? link_target : in_repo_path);
5894 if (error)
5895 goto done;
5897 error = got_object_get_type(&obj_type, repo, obj_id);
5898 if (error)
5899 goto done;
5901 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5902 error = got_error_path(link_target ? link_target : in_repo_path,
5903 GOT_ERR_OBJ_TYPE);
5904 goto done;
5907 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5908 if (error)
5909 goto done;
5910 bca.f = got_opentemp();
5911 if (bca.f == NULL) {
5912 error = got_error_from_errno("got_opentemp");
5913 goto done;
5915 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5916 &bca.line_offsets, bca.f, blob);
5917 if (error || bca.nlines == 0)
5918 goto done;
5920 /* Don't include \n at EOF in the blame line count. */
5921 if (bca.line_offsets[bca.nlines - 1] == filesize)
5922 bca.nlines--;
5924 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5925 if (bca.lines == NULL) {
5926 error = got_error_from_errno("calloc");
5927 goto done;
5929 bca.lineno_cur = 1;
5930 bca.nlines_prec = 0;
5931 i = bca.nlines;
5932 while (i > 0) {
5933 i /= 10;
5934 bca.nlines_prec++;
5936 bca.repo = repo;
5938 fd2 = got_opentempfd();
5939 if (fd2 == -1) {
5940 error = got_error_from_errno("got_opentempfd");
5941 goto done;
5943 fd3 = got_opentempfd();
5944 if (fd3 == -1) {
5945 error = got_error_from_errno("got_opentempfd");
5946 goto done;
5948 f1 = got_opentemp();
5949 if (f1 == NULL) {
5950 error = got_error_from_errno("got_opentemp");
5951 goto done;
5953 f2 = got_opentemp();
5954 if (f2 == NULL) {
5955 error = got_error_from_errno("got_opentemp");
5956 goto done;
5958 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5959 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5960 check_cancelled, NULL, fd2, fd3, f1, f2);
5961 done:
5962 free(keyword_idstr);
5963 free(in_repo_path);
5964 free(link_target);
5965 free(repo_path);
5966 free(cwd);
5967 free(commit_id);
5968 free(obj_id);
5969 if (commit)
5970 got_object_commit_close(commit);
5972 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5973 error = got_error_from_errno("close");
5974 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5975 error = got_error_from_errno("close");
5976 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5977 error = got_error_from_errno("close");
5978 if (f1 && fclose(f1) == EOF && error == NULL)
5979 error = got_error_from_errno("fclose");
5980 if (f2 && fclose(f2) == EOF && error == NULL)
5981 error = got_error_from_errno("fclose");
5983 if (blob)
5984 got_object_blob_close(blob);
5985 if (worktree)
5986 got_worktree_close(worktree);
5987 if (repo) {
5988 const struct got_error *close_err = got_repo_close(repo);
5989 if (error == NULL)
5990 error = close_err;
5992 if (pack_fds) {
5993 const struct got_error *pack_err =
5994 got_repo_pack_fds_close(pack_fds);
5995 if (error == NULL)
5996 error = pack_err;
5998 if (bca.lines) {
5999 for (i = 0; i < bca.nlines; i++) {
6000 struct blame_line *bline = &bca.lines[i];
6001 free(bline->id_str);
6002 free(bline->committer);
6004 free(bca.lines);
6006 free(bca.line_offsets);
6007 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6008 error = got_error_from_errno("fclose");
6009 return error;
6012 __dead static void
6013 usage_tree(void)
6015 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6016 "[path]\n", getprogname());
6017 exit(1);
6020 static const struct got_error *
6021 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6022 const char *root_path, struct got_repository *repo)
6024 const struct got_error *err = NULL;
6025 int is_root_path = (strcmp(path, root_path) == 0);
6026 const char *modestr = "";
6027 mode_t mode = got_tree_entry_get_mode(te);
6028 char *link_target = NULL;
6030 path += strlen(root_path);
6031 while (path[0] == '/')
6032 path++;
6034 if (got_object_tree_entry_is_submodule(te))
6035 modestr = "$";
6036 else if (S_ISLNK(mode)) {
6037 int i;
6039 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6040 if (err)
6041 return err;
6042 for (i = 0; link_target[i] != '\0'; i++) {
6043 if (!isprint((unsigned char)link_target[i]))
6044 link_target[i] = '?';
6047 modestr = "@";
6049 else if (S_ISDIR(mode))
6050 modestr = "/";
6051 else if (mode & S_IXUSR)
6052 modestr = "*";
6054 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6055 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6056 link_target ? " -> ": "", link_target ? link_target : "");
6058 free(link_target);
6059 return NULL;
6062 static const struct got_error *
6063 print_tree(const char *path, struct got_commit_object *commit,
6064 int show_ids, int recurse, const char *root_path,
6065 struct got_repository *repo)
6067 const struct got_error *err = NULL;
6068 struct got_object_id *tree_id = NULL;
6069 struct got_tree_object *tree = NULL;
6070 int nentries, i;
6072 err = got_object_id_by_path(&tree_id, repo, commit, path);
6073 if (err)
6074 goto done;
6076 err = got_object_open_as_tree(&tree, repo, tree_id);
6077 if (err)
6078 goto done;
6079 nentries = got_object_tree_get_nentries(tree);
6080 for (i = 0; i < nentries; i++) {
6081 struct got_tree_entry *te;
6082 char *id = NULL;
6084 if (sigint_received || sigpipe_received)
6085 break;
6087 te = got_object_tree_get_entry(tree, i);
6088 if (show_ids) {
6089 char *id_str;
6090 err = got_object_id_str(&id_str,
6091 got_tree_entry_get_id(te));
6092 if (err)
6093 goto done;
6094 if (asprintf(&id, "%s ", id_str) == -1) {
6095 err = got_error_from_errno("asprintf");
6096 free(id_str);
6097 goto done;
6099 free(id_str);
6101 err = print_entry(te, id, path, root_path, repo);
6102 free(id);
6103 if (err)
6104 goto done;
6106 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6107 char *child_path;
6108 if (asprintf(&child_path, "%s%s%s", path,
6109 path[0] == '/' && path[1] == '\0' ? "" : "/",
6110 got_tree_entry_get_name(te)) == -1) {
6111 err = got_error_from_errno("asprintf");
6112 goto done;
6114 err = print_tree(child_path, commit, show_ids, 1,
6115 root_path, repo);
6116 free(child_path);
6117 if (err)
6118 goto done;
6121 done:
6122 if (tree)
6123 got_object_tree_close(tree);
6124 free(tree_id);
6125 return err;
6128 static const struct got_error *
6129 cmd_tree(int argc, char *argv[])
6131 const struct got_error *error;
6132 struct got_repository *repo = NULL;
6133 struct got_worktree *worktree = NULL;
6134 const char *path, *refname = NULL;
6135 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6136 struct got_object_id *commit_id = NULL;
6137 struct got_commit_object *commit = NULL;
6138 char *commit_id_str = NULL, *keyword_idstr = NULL;
6139 int show_ids = 0, recurse = 0;
6140 int ch;
6141 int *pack_fds = NULL;
6143 #ifndef PROFILE
6144 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6145 NULL) == -1)
6146 err(1, "pledge");
6147 #endif
6149 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6150 switch (ch) {
6151 case 'c':
6152 commit_id_str = optarg;
6153 break;
6154 case 'i':
6155 show_ids = 1;
6156 break;
6157 case 'R':
6158 recurse = 1;
6159 break;
6160 case 'r':
6161 repo_path = realpath(optarg, NULL);
6162 if (repo_path == NULL)
6163 return got_error_from_errno2("realpath",
6164 optarg);
6165 got_path_strip_trailing_slashes(repo_path);
6166 break;
6167 default:
6168 usage_tree();
6169 /* NOTREACHED */
6173 argc -= optind;
6174 argv += optind;
6176 if (argc == 1)
6177 path = argv[0];
6178 else if (argc > 1)
6179 usage_tree();
6180 else
6181 path = NULL;
6183 cwd = getcwd(NULL, 0);
6184 if (cwd == NULL) {
6185 error = got_error_from_errno("getcwd");
6186 goto done;
6189 error = got_repo_pack_fds_open(&pack_fds);
6190 if (error != NULL)
6191 goto done;
6193 if (repo_path == NULL) {
6194 error = got_worktree_open(&worktree, cwd,
6195 GOT_WORKTREE_GOT_DIR);
6196 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6197 goto done;
6198 else
6199 error = NULL;
6200 if (worktree) {
6201 repo_path =
6202 strdup(got_worktree_get_repo_path(worktree));
6203 if (repo_path == NULL)
6204 error = got_error_from_errno("strdup");
6205 if (error)
6206 goto done;
6207 } else {
6208 repo_path = strdup(cwd);
6209 if (repo_path == NULL) {
6210 error = got_error_from_errno("strdup");
6211 goto done;
6216 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6217 if (error != NULL)
6218 goto done;
6220 if (worktree) {
6221 const char *prefix = got_worktree_get_path_prefix(worktree);
6222 char *p;
6224 if (path == NULL || got_path_is_root_dir(path))
6225 path = "";
6226 error = got_worktree_resolve_path(&p, worktree, path);
6227 if (error)
6228 goto done;
6229 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6230 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6231 p) == -1) {
6232 error = got_error_from_errno("asprintf");
6233 free(p);
6234 goto done;
6236 free(p);
6237 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6238 if (error)
6239 goto done;
6240 } else {
6241 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6242 if (error)
6243 goto done;
6244 if (path == NULL)
6245 path = "/";
6246 error = got_repo_map_path(&in_repo_path, repo, path);
6247 if (error != NULL)
6248 goto done;
6251 if (commit_id_str == NULL) {
6252 struct got_reference *head_ref;
6253 if (worktree)
6254 refname = got_worktree_get_head_ref_name(worktree);
6255 else
6256 refname = GOT_REF_HEAD;
6257 error = got_ref_open(&head_ref, repo, refname, 0);
6258 if (error != NULL)
6259 goto done;
6260 error = got_ref_resolve(&commit_id, repo, head_ref);
6261 got_ref_close(head_ref);
6262 if (error != NULL)
6263 goto done;
6264 } else {
6265 struct got_reflist_head refs;
6267 TAILQ_INIT(&refs);
6268 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6269 NULL);
6270 if (error)
6271 goto done;
6273 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6274 repo, worktree);
6275 if (error != NULL)
6276 goto done;
6277 if (keyword_idstr != NULL)
6278 commit_id_str = keyword_idstr;
6280 error = got_repo_match_object_id(&commit_id, NULL,
6281 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6282 got_ref_list_free(&refs);
6283 if (error)
6284 goto done;
6287 if (worktree) {
6288 /* Release work tree lock. */
6289 got_worktree_close(worktree);
6290 worktree = NULL;
6293 error = got_object_open_as_commit(&commit, repo, commit_id);
6294 if (error)
6295 goto done;
6297 error = print_tree(in_repo_path, commit, show_ids, recurse,
6298 in_repo_path, repo);
6299 done:
6300 free(keyword_idstr);
6301 free(in_repo_path);
6302 free(repo_path);
6303 free(cwd);
6304 free(commit_id);
6305 if (commit)
6306 got_object_commit_close(commit);
6307 if (worktree)
6308 got_worktree_close(worktree);
6309 if (repo) {
6310 const struct got_error *close_err = got_repo_close(repo);
6311 if (error == NULL)
6312 error = close_err;
6314 if (pack_fds) {
6315 const struct got_error *pack_err =
6316 got_repo_pack_fds_close(pack_fds);
6317 if (error == NULL)
6318 error = pack_err;
6320 return error;
6323 __dead static void
6324 usage_status(void)
6326 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6327 "[-s status-codes] [path ...]\n", getprogname());
6328 exit(1);
6331 struct got_status_arg {
6332 char *status_codes;
6333 int suppress;
6336 static const struct got_error *
6337 print_status(void *arg, unsigned char status, unsigned char staged_status,
6338 const char *path, struct got_object_id *blob_id,
6339 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6340 int dirfd, const char *de_name)
6342 struct got_status_arg *st = arg;
6344 if (status == staged_status && (status == GOT_STATUS_DELETE))
6345 status = GOT_STATUS_NO_CHANGE;
6346 if (st != NULL && st->status_codes) {
6347 size_t ncodes = strlen(st->status_codes);
6348 int i, j = 0;
6350 for (i = 0; i < ncodes ; i++) {
6351 if (st->suppress) {
6352 if (status == st->status_codes[i] ||
6353 staged_status == st->status_codes[i]) {
6354 j++;
6355 continue;
6357 } else {
6358 if (status == st->status_codes[i] ||
6359 staged_status == st->status_codes[i])
6360 break;
6364 if (st->suppress && j == 0)
6365 goto print;
6367 if (i == ncodes)
6368 return NULL;
6370 print:
6371 printf("%c%c %s\n", status, staged_status, path);
6372 return NULL;
6375 static const struct got_error *
6376 cmd_status(int argc, char *argv[])
6378 const struct got_error *error = NULL;
6379 struct got_repository *repo = NULL;
6380 struct got_worktree *worktree = NULL;
6381 struct got_status_arg st;
6382 char *cwd = NULL;
6383 struct got_pathlist_head paths;
6384 int ch, i, no_ignores = 0;
6385 int *pack_fds = NULL;
6387 TAILQ_INIT(&paths);
6389 memset(&st, 0, sizeof(st));
6390 st.status_codes = NULL;
6391 st.suppress = 0;
6393 #ifndef PROFILE
6394 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6395 NULL) == -1)
6396 err(1, "pledge");
6397 #endif
6399 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6400 switch (ch) {
6401 case 'I':
6402 no_ignores = 1;
6403 break;
6404 case 'S':
6405 if (st.status_codes != NULL && st.suppress == 0)
6406 option_conflict('S', 's');
6407 st.suppress = 1;
6408 /* fallthrough */
6409 case 's':
6410 for (i = 0; optarg[i] != '\0'; i++) {
6411 switch (optarg[i]) {
6412 case GOT_STATUS_MODIFY:
6413 case GOT_STATUS_ADD:
6414 case GOT_STATUS_DELETE:
6415 case GOT_STATUS_CONFLICT:
6416 case GOT_STATUS_MISSING:
6417 case GOT_STATUS_OBSTRUCTED:
6418 case GOT_STATUS_UNVERSIONED:
6419 case GOT_STATUS_MODE_CHANGE:
6420 case GOT_STATUS_NONEXISTENT:
6421 break;
6422 default:
6423 errx(1, "invalid status code '%c'",
6424 optarg[i]);
6427 if (ch == 's' && st.suppress)
6428 option_conflict('s', 'S');
6429 st.status_codes = optarg;
6430 break;
6431 default:
6432 usage_status();
6433 /* NOTREACHED */
6437 argc -= optind;
6438 argv += optind;
6440 cwd = getcwd(NULL, 0);
6441 if (cwd == NULL) {
6442 error = got_error_from_errno("getcwd");
6443 goto done;
6446 error = got_repo_pack_fds_open(&pack_fds);
6447 if (error != NULL)
6448 goto done;
6450 error = got_worktree_open(&worktree, cwd,
6451 GOT_WORKTREE_GOT_DIR);
6452 if (error) {
6453 if (error->code == GOT_ERR_NOT_WORKTREE)
6454 error = wrap_not_worktree_error(error, "status", cwd);
6455 goto done;
6458 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6459 NULL, pack_fds);
6460 if (error != NULL)
6461 goto done;
6463 error = apply_unveil(got_repo_get_path(repo), 1,
6464 got_worktree_get_root_path(worktree));
6465 if (error)
6466 goto done;
6468 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6469 if (error)
6470 goto done;
6472 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6473 print_status, &st, check_cancelled, NULL);
6474 done:
6475 if (pack_fds) {
6476 const struct got_error *pack_err =
6477 got_repo_pack_fds_close(pack_fds);
6478 if (error == NULL)
6479 error = pack_err;
6481 if (repo) {
6482 const struct got_error *close_err = got_repo_close(repo);
6483 if (error == NULL)
6484 error = close_err;
6487 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6488 free(cwd);
6489 return error;
6492 __dead static void
6493 usage_ref(void)
6495 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6496 "[-s reference] [name]\n", getprogname());
6497 exit(1);
6500 static const struct got_error *
6501 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6503 static const struct got_error *err = NULL;
6504 struct got_reflist_head refs;
6505 struct got_reflist_entry *re;
6507 TAILQ_INIT(&refs);
6508 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6509 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6510 repo);
6511 if (err)
6512 return err;
6514 TAILQ_FOREACH(re, &refs, entry) {
6515 char *refstr;
6516 refstr = got_ref_to_str(re->ref);
6517 if (refstr == NULL) {
6518 err = got_error_from_errno("got_ref_to_str");
6519 break;
6521 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6522 free(refstr);
6525 got_ref_list_free(&refs);
6526 return err;
6529 static const struct got_error *
6530 delete_ref_by_name(struct got_repository *repo, const char *refname)
6532 const struct got_error *err;
6533 struct got_reference *ref;
6535 err = got_ref_open(&ref, repo, refname, 0);
6536 if (err)
6537 return err;
6539 err = delete_ref(repo, ref);
6540 got_ref_close(ref);
6541 return err;
6544 static const struct got_error *
6545 add_ref(struct got_repository *repo, const char *refname, const char *target)
6547 const struct got_error *err = NULL;
6548 struct got_object_id *id = NULL;
6549 struct got_reference *ref = NULL;
6550 struct got_reflist_head refs;
6553 * Don't let the user create a reference name with a leading '-'.
6554 * While technically a valid reference name, this case is usually
6555 * an unintended typo.
6557 if (refname[0] == '-')
6558 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6560 TAILQ_INIT(&refs);
6561 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6562 if (err)
6563 goto done;
6564 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6565 &refs, repo);
6566 got_ref_list_free(&refs);
6567 if (err)
6568 goto done;
6570 err = got_ref_alloc(&ref, refname, id);
6571 if (err)
6572 goto done;
6574 err = got_ref_write(ref, repo);
6575 done:
6576 if (ref)
6577 got_ref_close(ref);
6578 free(id);
6579 return err;
6582 static const struct got_error *
6583 add_symref(struct got_repository *repo, const char *refname, const char *target)
6585 const struct got_error *err = NULL;
6586 struct got_reference *ref = NULL;
6587 struct got_reference *target_ref = NULL;
6590 * Don't let the user create a reference name with a leading '-'.
6591 * While technically a valid reference name, this case is usually
6592 * an unintended typo.
6594 if (refname[0] == '-')
6595 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6597 err = got_ref_open(&target_ref, repo, target, 0);
6598 if (err)
6599 return err;
6601 err = got_ref_alloc_symref(&ref, refname, target_ref);
6602 if (err)
6603 goto done;
6605 err = got_ref_write(ref, repo);
6606 done:
6607 if (target_ref)
6608 got_ref_close(target_ref);
6609 if (ref)
6610 got_ref_close(ref);
6611 return err;
6614 static const struct got_error *
6615 cmd_ref(int argc, char *argv[])
6617 const struct got_error *error = NULL;
6618 struct got_repository *repo = NULL;
6619 struct got_worktree *worktree = NULL;
6620 char *cwd = NULL, *repo_path = NULL;
6621 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6622 const char *obj_arg = NULL, *symref_target= NULL;
6623 char *refname = NULL, *keyword_idstr = NULL;
6624 int *pack_fds = NULL;
6626 #ifndef PROFILE
6627 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6628 "sendfd unveil", NULL) == -1)
6629 err(1, "pledge");
6630 #endif
6632 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6633 switch (ch) {
6634 case 'c':
6635 obj_arg = optarg;
6636 break;
6637 case 'd':
6638 do_delete = 1;
6639 break;
6640 case 'l':
6641 do_list = 1;
6642 break;
6643 case 'r':
6644 repo_path = realpath(optarg, NULL);
6645 if (repo_path == NULL)
6646 return got_error_from_errno2("realpath",
6647 optarg);
6648 got_path_strip_trailing_slashes(repo_path);
6649 break;
6650 case 's':
6651 symref_target = optarg;
6652 break;
6653 case 't':
6654 sort_by_time = 1;
6655 break;
6656 default:
6657 usage_ref();
6658 /* NOTREACHED */
6662 if (obj_arg && do_list)
6663 option_conflict('c', 'l');
6664 if (obj_arg && do_delete)
6665 option_conflict('c', 'd');
6666 if (obj_arg && symref_target)
6667 option_conflict('c', 's');
6668 if (symref_target && do_delete)
6669 option_conflict('s', 'd');
6670 if (symref_target && do_list)
6671 option_conflict('s', 'l');
6672 if (do_delete && do_list)
6673 option_conflict('d', 'l');
6674 if (sort_by_time && !do_list)
6675 errx(1, "-t option requires -l option");
6677 argc -= optind;
6678 argv += optind;
6680 if (do_list) {
6681 if (argc != 0 && argc != 1)
6682 usage_ref();
6683 if (argc == 1) {
6684 refname = strdup(argv[0]);
6685 if (refname == NULL) {
6686 error = got_error_from_errno("strdup");
6687 goto done;
6690 } else {
6691 if (argc != 1)
6692 usage_ref();
6693 refname = strdup(argv[0]);
6694 if (refname == NULL) {
6695 error = got_error_from_errno("strdup");
6696 goto done;
6700 if (refname)
6701 got_path_strip_trailing_slashes(refname);
6703 cwd = getcwd(NULL, 0);
6704 if (cwd == NULL) {
6705 error = got_error_from_errno("getcwd");
6706 goto done;
6709 error = got_repo_pack_fds_open(&pack_fds);
6710 if (error != NULL)
6711 goto done;
6713 if (repo_path == NULL) {
6714 error = got_worktree_open(&worktree, cwd,
6715 GOT_WORKTREE_GOT_DIR);
6716 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6717 goto done;
6718 else
6719 error = NULL;
6720 if (worktree) {
6721 repo_path =
6722 strdup(got_worktree_get_repo_path(worktree));
6723 if (repo_path == NULL)
6724 error = got_error_from_errno("strdup");
6725 if (error)
6726 goto done;
6727 } else {
6728 repo_path = strdup(cwd);
6729 if (repo_path == NULL) {
6730 error = got_error_from_errno("strdup");
6731 goto done;
6736 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6737 if (error != NULL)
6738 goto done;
6740 #ifndef PROFILE
6741 if (do_list) {
6742 /* Remove "cpath" promise. */
6743 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6744 NULL) == -1)
6745 err(1, "pledge");
6747 #endif
6749 error = apply_unveil(got_repo_get_path(repo), do_list,
6750 worktree ? got_worktree_get_root_path(worktree) : NULL);
6751 if (error)
6752 goto done;
6754 if (do_list)
6755 error = list_refs(repo, refname, sort_by_time);
6756 else if (do_delete)
6757 error = delete_ref_by_name(repo, refname);
6758 else if (symref_target)
6759 error = add_symref(repo, refname, symref_target);
6760 else {
6761 if (obj_arg == NULL)
6762 usage_ref();
6764 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6765 repo, worktree);
6766 if (error != NULL)
6767 goto done;
6768 if (keyword_idstr != NULL)
6769 obj_arg = keyword_idstr;
6771 error = add_ref(repo, refname, obj_arg);
6773 done:
6774 free(refname);
6775 if (repo) {
6776 const struct got_error *close_err = got_repo_close(repo);
6777 if (error == NULL)
6778 error = close_err;
6780 if (worktree)
6781 got_worktree_close(worktree);
6782 if (pack_fds) {
6783 const struct got_error *pack_err =
6784 got_repo_pack_fds_close(pack_fds);
6785 if (error == NULL)
6786 error = pack_err;
6788 free(cwd);
6789 free(repo_path);
6790 free(keyword_idstr);
6791 return error;
6794 __dead static void
6795 usage_branch(void)
6797 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6798 "[-r repository-path] [name]\n", getprogname());
6799 exit(1);
6802 static const struct got_error *
6803 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6804 struct got_reference *ref)
6806 const struct got_error *err = NULL;
6807 const char *refname;
6808 char *refstr;
6809 char marker = ' ';
6811 refname = got_ref_get_name(ref);
6812 if (worktree && strcmp(refname,
6813 got_worktree_get_head_ref_name(worktree)) == 0) {
6814 err = got_worktree_get_state(&marker, repo, worktree,
6815 check_cancelled, NULL);
6816 if (err != NULL)
6817 return err;
6820 if (strncmp(refname, "refs/heads/", 11) == 0)
6821 refname += 11;
6822 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6823 refname += 18;
6824 if (strncmp(refname, "refs/remotes/", 13) == 0)
6825 refname += 13;
6827 refstr = got_ref_to_str(ref);
6828 if (refstr == NULL)
6829 return got_error_from_errno("got_ref_to_str");
6831 printf("%c %s: %s\n", marker, refname, refstr);
6832 free(refstr);
6833 return NULL;
6836 static const struct got_error *
6837 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6839 const char *refname;
6841 if (worktree == NULL)
6842 return got_error(GOT_ERR_NOT_WORKTREE);
6844 refname = got_worktree_get_head_ref_name(worktree);
6846 if (strncmp(refname, "refs/heads/", 11) == 0)
6847 refname += 11;
6848 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6849 refname += 18;
6851 printf("%s\n", refname);
6853 return NULL;
6856 static const struct got_error *
6857 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6858 int sort_by_time)
6860 static const struct got_error *err = NULL;
6861 struct got_reflist_head refs;
6862 struct got_reflist_entry *re;
6863 struct got_reference *temp_ref = NULL;
6864 int rebase_in_progress, histedit_in_progress;
6866 TAILQ_INIT(&refs);
6868 if (worktree) {
6869 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6870 worktree);
6871 if (err)
6872 return err;
6874 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6875 worktree);
6876 if (err)
6877 return err;
6879 if (rebase_in_progress || histedit_in_progress) {
6880 err = got_ref_open(&temp_ref, repo,
6881 got_worktree_get_head_ref_name(worktree), 0);
6882 if (err)
6883 return err;
6884 list_branch(repo, worktree, temp_ref);
6885 got_ref_close(temp_ref);
6889 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6890 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6891 repo);
6892 if (err)
6893 return err;
6895 TAILQ_FOREACH(re, &refs, entry)
6896 list_branch(repo, worktree, re->ref);
6898 got_ref_list_free(&refs);
6900 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6901 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6902 repo);
6903 if (err)
6904 return err;
6906 TAILQ_FOREACH(re, &refs, entry)
6907 list_branch(repo, worktree, re->ref);
6909 got_ref_list_free(&refs);
6911 return NULL;
6914 static const struct got_error *
6915 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6916 const char *branch_name)
6918 const struct got_error *err = NULL;
6919 struct got_reference *ref = NULL;
6920 char *refname, *remote_refname = NULL;
6922 if (strncmp(branch_name, "refs/", 5) == 0)
6923 branch_name += 5;
6924 if (strncmp(branch_name, "heads/", 6) == 0)
6925 branch_name += 6;
6926 else if (strncmp(branch_name, "remotes/", 8) == 0)
6927 branch_name += 8;
6929 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6930 return got_error_from_errno("asprintf");
6932 if (asprintf(&remote_refname, "refs/remotes/%s",
6933 branch_name) == -1) {
6934 err = got_error_from_errno("asprintf");
6935 goto done;
6938 err = got_ref_open(&ref, repo, refname, 0);
6939 if (err) {
6940 const struct got_error *err2;
6941 if (err->code != GOT_ERR_NOT_REF)
6942 goto done;
6944 * Keep 'err' intact such that if neither branch exists
6945 * we report "refs/heads" rather than "refs/remotes" in
6946 * our error message.
6948 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6949 if (err2)
6950 goto done;
6951 err = NULL;
6954 if (worktree &&
6955 strcmp(got_worktree_get_head_ref_name(worktree),
6956 got_ref_get_name(ref)) == 0) {
6957 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6958 "will not delete this work tree's current branch");
6959 goto done;
6962 err = delete_ref(repo, ref);
6963 done:
6964 if (ref)
6965 got_ref_close(ref);
6966 free(refname);
6967 free(remote_refname);
6968 return err;
6971 static const struct got_error *
6972 add_branch(struct got_repository *repo, const char *branch_name,
6973 struct got_object_id *base_commit_id)
6975 const struct got_error *err = NULL;
6976 struct got_reference *ref = NULL;
6977 char *refname = NULL;
6980 * Don't let the user create a branch name with a leading '-'.
6981 * While technically a valid reference name, this case is usually
6982 * an unintended typo.
6984 if (branch_name[0] == '-')
6985 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6987 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6988 branch_name += 11;
6990 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6991 err = got_error_from_errno("asprintf");
6992 goto done;
6995 err = got_ref_open(&ref, repo, refname, 0);
6996 if (err == NULL) {
6997 err = got_error(GOT_ERR_BRANCH_EXISTS);
6998 goto done;
6999 } else if (err->code != GOT_ERR_NOT_REF)
7000 goto done;
7002 err = got_ref_alloc(&ref, refname, base_commit_id);
7003 if (err)
7004 goto done;
7006 err = got_ref_write(ref, repo);
7007 done:
7008 if (ref)
7009 got_ref_close(ref);
7010 free(refname);
7011 return err;
7014 static const struct got_error *
7015 cmd_branch(int argc, char *argv[])
7017 const struct got_error *error = NULL;
7018 struct got_repository *repo = NULL;
7019 struct got_worktree *worktree = NULL;
7020 char *cwd = NULL, *repo_path = NULL;
7021 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7022 const char *delref = NULL, *commit_id_arg = NULL;
7023 struct got_reference *ref = NULL;
7024 struct got_pathlist_head paths;
7025 struct got_object_id *commit_id = NULL;
7026 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7027 int *pack_fds = NULL;
7029 TAILQ_INIT(&paths);
7031 #ifndef PROFILE
7032 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7033 "sendfd unveil", NULL) == -1)
7034 err(1, "pledge");
7035 #endif
7037 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7038 switch (ch) {
7039 case 'c':
7040 commit_id_arg = optarg;
7041 break;
7042 case 'd':
7043 delref = optarg;
7044 break;
7045 case 'l':
7046 do_list = 1;
7047 break;
7048 case 'n':
7049 do_update = 0;
7050 break;
7051 case 'r':
7052 repo_path = realpath(optarg, NULL);
7053 if (repo_path == NULL)
7054 return got_error_from_errno2("realpath",
7055 optarg);
7056 got_path_strip_trailing_slashes(repo_path);
7057 break;
7058 case 't':
7059 sort_by_time = 1;
7060 break;
7061 default:
7062 usage_branch();
7063 /* NOTREACHED */
7067 if (do_list && delref)
7068 option_conflict('l', 'd');
7069 if (sort_by_time && !do_list)
7070 errx(1, "-t option requires -l option");
7072 argc -= optind;
7073 argv += optind;
7075 if (!do_list && !delref && argc == 0)
7076 do_show = 1;
7078 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7079 errx(1, "-c option can only be used when creating a branch");
7081 if (do_list || delref) {
7082 if (argc > 0)
7083 usage_branch();
7084 } else if (!do_show && argc != 1)
7085 usage_branch();
7087 cwd = getcwd(NULL, 0);
7088 if (cwd == NULL) {
7089 error = got_error_from_errno("getcwd");
7090 goto done;
7093 error = got_repo_pack_fds_open(&pack_fds);
7094 if (error != NULL)
7095 goto done;
7097 if (repo_path == NULL) {
7098 error = got_worktree_open(&worktree, cwd,
7099 GOT_WORKTREE_GOT_DIR);
7100 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7101 goto done;
7102 else
7103 error = NULL;
7104 if (worktree) {
7105 repo_path =
7106 strdup(got_worktree_get_repo_path(worktree));
7107 if (repo_path == NULL)
7108 error = got_error_from_errno("strdup");
7109 if (error)
7110 goto done;
7111 } else {
7112 repo_path = strdup(cwd);
7113 if (repo_path == NULL) {
7114 error = got_error_from_errno("strdup");
7115 goto done;
7120 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7121 if (error != NULL)
7122 goto done;
7124 #ifndef PROFILE
7125 if (do_list || do_show) {
7126 /* Remove "cpath" promise. */
7127 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7128 NULL) == -1)
7129 err(1, "pledge");
7131 #endif
7133 error = apply_unveil(got_repo_get_path(repo), do_list,
7134 worktree ? got_worktree_get_root_path(worktree) : NULL);
7135 if (error)
7136 goto done;
7138 if (do_show)
7139 error = show_current_branch(repo, worktree);
7140 else if (do_list)
7141 error = list_branches(repo, worktree, sort_by_time);
7142 else if (delref)
7143 error = delete_branch(repo, worktree, delref);
7144 else {
7145 struct got_reflist_head refs;
7146 TAILQ_INIT(&refs);
7147 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7148 NULL);
7149 if (error)
7150 goto done;
7151 if (commit_id_arg == NULL)
7152 commit_id_arg = worktree ?
7153 got_worktree_get_head_ref_name(worktree) :
7154 GOT_REF_HEAD;
7155 else {
7156 error = got_keyword_to_idstr(&keyword_idstr,
7157 commit_id_arg, repo, worktree);
7158 if (error != NULL)
7159 goto done;
7160 if (keyword_idstr != NULL)
7161 commit_id_arg = keyword_idstr;
7163 error = got_repo_match_object_id(&commit_id, NULL,
7164 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7165 got_ref_list_free(&refs);
7166 if (error)
7167 goto done;
7168 error = add_branch(repo, argv[0], commit_id);
7169 if (error)
7170 goto done;
7171 if (worktree && do_update) {
7172 struct got_update_progress_arg upa;
7173 char *branch_refname = NULL;
7175 error = got_object_id_str(&commit_id_str, commit_id);
7176 if (error)
7177 goto done;
7178 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7179 worktree);
7180 if (error)
7181 goto done;
7182 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7183 == -1) {
7184 error = got_error_from_errno("asprintf");
7185 goto done;
7187 error = got_ref_open(&ref, repo, branch_refname, 0);
7188 free(branch_refname);
7189 if (error)
7190 goto done;
7191 error = switch_head_ref(ref, commit_id, worktree,
7192 repo);
7193 if (error)
7194 goto done;
7195 error = got_worktree_set_base_commit_id(worktree, repo,
7196 commit_id);
7197 if (error)
7198 goto done;
7199 memset(&upa, 0, sizeof(upa));
7200 error = got_worktree_checkout_files(worktree, &paths,
7201 repo, update_progress, &upa, check_cancelled,
7202 NULL);
7203 if (error)
7204 goto done;
7205 if (upa.did_something) {
7206 printf("Updated to %s: %s\n",
7207 got_worktree_get_head_ref_name(worktree),
7208 commit_id_str);
7210 print_update_progress_stats(&upa);
7213 done:
7214 free(keyword_idstr);
7215 if (ref)
7216 got_ref_close(ref);
7217 if (repo) {
7218 const struct got_error *close_err = got_repo_close(repo);
7219 if (error == NULL)
7220 error = close_err;
7222 if (worktree)
7223 got_worktree_close(worktree);
7224 if (pack_fds) {
7225 const struct got_error *pack_err =
7226 got_repo_pack_fds_close(pack_fds);
7227 if (error == NULL)
7228 error = pack_err;
7230 free(cwd);
7231 free(repo_path);
7232 free(commit_id);
7233 free(commit_id_str);
7234 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7235 return error;
7239 __dead static void
7240 usage_tag(void)
7242 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7243 "[-r repository-path] [-s signer-id] name\n", getprogname());
7244 exit(1);
7247 #if 0
7248 static const struct got_error *
7249 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7251 const struct got_error *err = NULL;
7252 struct got_reflist_entry *re, *se, *new;
7253 struct got_object_id *re_id, *se_id;
7254 struct got_tag_object *re_tag, *se_tag;
7255 time_t re_time, se_time;
7257 STAILQ_FOREACH(re, tags, entry) {
7258 se = STAILQ_FIRST(sorted);
7259 if (se == NULL) {
7260 err = got_reflist_entry_dup(&new, re);
7261 if (err)
7262 return err;
7263 STAILQ_INSERT_HEAD(sorted, new, entry);
7264 continue;
7265 } else {
7266 err = got_ref_resolve(&re_id, repo, re->ref);
7267 if (err)
7268 break;
7269 err = got_object_open_as_tag(&re_tag, repo, re_id);
7270 free(re_id);
7271 if (err)
7272 break;
7273 re_time = got_object_tag_get_tagger_time(re_tag);
7274 got_object_tag_close(re_tag);
7277 while (se) {
7278 err = got_ref_resolve(&se_id, repo, re->ref);
7279 if (err)
7280 break;
7281 err = got_object_open_as_tag(&se_tag, repo, se_id);
7282 free(se_id);
7283 if (err)
7284 break;
7285 se_time = got_object_tag_get_tagger_time(se_tag);
7286 got_object_tag_close(se_tag);
7288 if (se_time > re_time) {
7289 err = got_reflist_entry_dup(&new, re);
7290 if (err)
7291 return err;
7292 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7293 break;
7295 se = STAILQ_NEXT(se, entry);
7296 continue;
7299 done:
7300 return err;
7302 #endif
7304 static const struct got_error *
7305 get_tag_refname(char **refname, const char *tag_name)
7307 const struct got_error *err;
7309 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7310 *refname = strdup(tag_name);
7311 if (*refname == NULL)
7312 return got_error_from_errno("strdup");
7313 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7314 err = got_error_from_errno("asprintf");
7315 *refname = NULL;
7316 return err;
7319 return NULL;
7322 static const struct got_error *
7323 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7324 const char *allowed_signers, const char *revoked_signers, int verbosity)
7326 static const struct got_error *err = NULL;
7327 struct got_reflist_head refs;
7328 struct got_reflist_entry *re;
7329 char *wanted_refname = NULL;
7330 int bad_sigs = 0;
7332 TAILQ_INIT(&refs);
7334 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7335 if (err)
7336 return err;
7338 if (tag_name) {
7339 struct got_reference *ref;
7340 err = get_tag_refname(&wanted_refname, tag_name);
7341 if (err)
7342 goto done;
7343 /* Wanted tag reference should exist. */
7344 err = got_ref_open(&ref, repo, wanted_refname, 0);
7345 if (err)
7346 goto done;
7347 got_ref_close(ref);
7350 TAILQ_FOREACH(re, &refs, entry) {
7351 const char *refname;
7352 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7353 char datebuf[26];
7354 const char *tagger, *ssh_sig = NULL;
7355 char *sig_msg = NULL;
7356 time_t tagger_time;
7357 struct got_object_id *id;
7358 struct got_tag_object *tag;
7359 struct got_commit_object *commit = NULL;
7361 refname = got_ref_get_name(re->ref);
7362 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7363 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7364 continue;
7365 refname += 10;
7366 refstr = got_ref_to_str(re->ref);
7367 if (refstr == NULL) {
7368 err = got_error_from_errno("got_ref_to_str");
7369 break;
7372 err = got_ref_resolve(&id, repo, re->ref);
7373 if (err)
7374 break;
7375 err = got_object_open_as_tag(&tag, repo, id);
7376 if (err) {
7377 if (err->code != GOT_ERR_OBJ_TYPE) {
7378 free(id);
7379 break;
7381 /* "lightweight" tag */
7382 err = got_object_open_as_commit(&commit, repo, id);
7383 if (err) {
7384 free(id);
7385 break;
7387 tagger = got_object_commit_get_committer(commit);
7388 tagger_time =
7389 got_object_commit_get_committer_time(commit);
7390 err = got_object_id_str(&id_str, id);
7391 free(id);
7392 if (err)
7393 break;
7394 } else {
7395 free(id);
7396 tagger = got_object_tag_get_tagger(tag);
7397 tagger_time = got_object_tag_get_tagger_time(tag);
7398 err = got_object_id_str(&id_str,
7399 got_object_tag_get_object_id(tag));
7400 if (err)
7401 break;
7404 if (tag && verify_tags) {
7405 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7406 got_object_tag_get_message(tag));
7407 if (ssh_sig && allowed_signers == NULL) {
7408 err = got_error_msg(
7409 GOT_ERR_VERIFY_TAG_SIGNATURE,
7410 "SSH signature verification requires "
7411 "setting allowed_signers in "
7412 "got.conf(5)");
7413 break;
7417 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7418 free(refstr);
7419 printf("from: %s\n", tagger);
7420 datestr = get_datestr(&tagger_time, datebuf);
7421 if (datestr)
7422 printf("date: %s UTC\n", datestr);
7423 if (commit)
7424 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7425 else {
7426 switch (got_object_tag_get_object_type(tag)) {
7427 case GOT_OBJ_TYPE_BLOB:
7428 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7429 id_str);
7430 break;
7431 case GOT_OBJ_TYPE_TREE:
7432 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7433 id_str);
7434 break;
7435 case GOT_OBJ_TYPE_COMMIT:
7436 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7437 id_str);
7438 break;
7439 case GOT_OBJ_TYPE_TAG:
7440 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7441 id_str);
7442 break;
7443 default:
7444 break;
7447 free(id_str);
7449 if (ssh_sig) {
7450 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7451 allowed_signers, revoked_signers, verbosity);
7452 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7453 bad_sigs = 1;
7454 else if (err)
7455 break;
7456 printf("signature: %s", sig_msg);
7457 free(sig_msg);
7458 sig_msg = NULL;
7461 if (commit) {
7462 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7463 if (err)
7464 break;
7465 got_object_commit_close(commit);
7466 } else {
7467 tagmsg0 = strdup(got_object_tag_get_message(tag));
7468 got_object_tag_close(tag);
7469 if (tagmsg0 == NULL) {
7470 err = got_error_from_errno("strdup");
7471 break;
7475 tagmsg = tagmsg0;
7476 do {
7477 line = strsep(&tagmsg, "\n");
7478 if (line)
7479 printf(" %s\n", line);
7480 } while (line);
7481 free(tagmsg0);
7483 done:
7484 got_ref_list_free(&refs);
7485 free(wanted_refname);
7487 if (err == NULL && bad_sigs)
7488 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7489 return err;
7492 static const struct got_error *
7493 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7494 const char *tag_name, const char *repo_path)
7496 const struct got_error *err = NULL;
7497 char *template = NULL, *initial_content = NULL;
7498 char *editor = NULL;
7499 int initial_content_len;
7500 int fd = -1;
7502 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7503 err = got_error_from_errno("asprintf");
7504 goto done;
7507 initial_content_len = asprintf(&initial_content,
7508 "\n# tagging commit %s as %s\n",
7509 commit_id_str, tag_name);
7510 if (initial_content_len == -1) {
7511 err = got_error_from_errno("asprintf");
7512 goto done;
7515 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7516 if (err)
7517 goto done;
7519 if (write(fd, initial_content, initial_content_len) == -1) {
7520 err = got_error_from_errno2("write", *tagmsg_path);
7521 goto done;
7523 if (close(fd) == -1) {
7524 err = got_error_from_errno2("close", *tagmsg_path);
7525 goto done;
7527 fd = -1;
7529 err = get_editor(&editor);
7530 if (err)
7531 goto done;
7532 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7533 initial_content_len, 1);
7534 done:
7535 free(initial_content);
7536 free(template);
7537 free(editor);
7539 if (fd != -1 && close(fd) == -1 && err == NULL)
7540 err = got_error_from_errno2("close", *tagmsg_path);
7542 if (err) {
7543 free(*tagmsg);
7544 *tagmsg = NULL;
7546 return err;
7549 static const struct got_error *
7550 add_tag(struct got_repository *repo, const char *tagger,
7551 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7552 const char *signer_id, int verbosity)
7554 const struct got_error *err = NULL;
7555 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7556 char *label = NULL, *commit_id_str = NULL;
7557 struct got_reference *ref = NULL;
7558 char *refname = NULL, *tagmsg = NULL;
7559 char *tagmsg_path = NULL, *tag_id_str = NULL;
7560 int preserve_tagmsg = 0;
7561 struct got_reflist_head refs;
7563 TAILQ_INIT(&refs);
7566 * Don't let the user create a tag name with a leading '-'.
7567 * While technically a valid reference name, this case is usually
7568 * an unintended typo.
7570 if (tag_name[0] == '-')
7571 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7573 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7574 if (err)
7575 goto done;
7577 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7578 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7579 if (err)
7580 goto done;
7582 err = got_object_id_str(&commit_id_str, commit_id);
7583 if (err)
7584 goto done;
7586 err = get_tag_refname(&refname, tag_name);
7587 if (err)
7588 goto done;
7589 if (strncmp("refs/tags/", tag_name, 10) == 0)
7590 tag_name += 10;
7592 err = got_ref_open(&ref, repo, refname, 0);
7593 if (err == NULL) {
7594 err = got_error(GOT_ERR_TAG_EXISTS);
7595 goto done;
7596 } else if (err->code != GOT_ERR_NOT_REF)
7597 goto done;
7599 if (tagmsg_arg == NULL) {
7600 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7601 tag_name, got_repo_get_path(repo));
7602 if (err) {
7603 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7604 tagmsg_path != NULL)
7605 preserve_tagmsg = 1;
7606 goto done;
7608 /* Editor is done; we can now apply unveil(2) */
7609 err = got_sigs_apply_unveil();
7610 if (err)
7611 goto done;
7612 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7613 if (err)
7614 goto done;
7617 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7618 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7619 verbosity);
7620 if (err) {
7621 if (tagmsg_path)
7622 preserve_tagmsg = 1;
7623 goto done;
7626 err = got_ref_alloc(&ref, refname, tag_id);
7627 if (err) {
7628 if (tagmsg_path)
7629 preserve_tagmsg = 1;
7630 goto done;
7633 err = got_ref_write(ref, repo);
7634 if (err) {
7635 if (tagmsg_path)
7636 preserve_tagmsg = 1;
7637 goto done;
7640 err = got_object_id_str(&tag_id_str, tag_id);
7641 if (err) {
7642 if (tagmsg_path)
7643 preserve_tagmsg = 1;
7644 goto done;
7646 printf("Created tag %s\n", tag_id_str);
7647 done:
7648 if (preserve_tagmsg) {
7649 fprintf(stderr, "%s: tag message preserved in %s\n",
7650 getprogname(), tagmsg_path);
7651 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7652 err = got_error_from_errno2("unlink", tagmsg_path);
7653 free(tag_id_str);
7654 if (ref)
7655 got_ref_close(ref);
7656 free(commit_id);
7657 free(commit_id_str);
7658 free(refname);
7659 free(tagmsg);
7660 free(tagmsg_path);
7661 got_ref_list_free(&refs);
7662 return err;
7665 static const struct got_error *
7666 cmd_tag(int argc, char *argv[])
7668 const struct got_error *error = NULL;
7669 struct got_repository *repo = NULL;
7670 struct got_worktree *worktree = NULL;
7671 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7672 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7673 char *allowed_signers = NULL, *revoked_signers = NULL;
7674 const char *signer_id = NULL;
7675 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7676 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7677 int *pack_fds = NULL;
7679 #ifndef PROFILE
7680 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7681 "sendfd unveil", NULL) == -1)
7682 err(1, "pledge");
7683 #endif
7685 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7686 switch (ch) {
7687 case 'c':
7688 commit_id_arg = optarg;
7689 break;
7690 case 'l':
7691 do_list = 1;
7692 break;
7693 case 'm':
7694 tagmsg = optarg;
7695 break;
7696 case 'r':
7697 repo_path = realpath(optarg, NULL);
7698 if (repo_path == NULL) {
7699 error = got_error_from_errno2("realpath",
7700 optarg);
7701 goto done;
7703 got_path_strip_trailing_slashes(repo_path);
7704 break;
7705 case 's':
7706 signer_id = optarg;
7707 break;
7708 case 'V':
7709 verify_tags = 1;
7710 break;
7711 case 'v':
7712 if (verbosity < 0)
7713 verbosity = 0;
7714 else if (verbosity < 3)
7715 verbosity++;
7716 break;
7717 default:
7718 usage_tag();
7719 /* NOTREACHED */
7723 argc -= optind;
7724 argv += optind;
7726 if (do_list || verify_tags) {
7727 if (commit_id_arg != NULL)
7728 errx(1,
7729 "-c option can only be used when creating a tag");
7730 if (tagmsg) {
7731 if (do_list)
7732 option_conflict('l', 'm');
7733 else
7734 option_conflict('V', 'm');
7736 if (signer_id) {
7737 if (do_list)
7738 option_conflict('l', 's');
7739 else
7740 option_conflict('V', 's');
7742 if (argc > 1)
7743 usage_tag();
7744 } else if (argc != 1)
7745 usage_tag();
7747 if (argc == 1)
7748 tag_name = argv[0];
7750 cwd = getcwd(NULL, 0);
7751 if (cwd == NULL) {
7752 error = got_error_from_errno("getcwd");
7753 goto done;
7756 error = got_repo_pack_fds_open(&pack_fds);
7757 if (error != NULL)
7758 goto done;
7760 if (repo_path == NULL) {
7761 error = got_worktree_open(&worktree, cwd,
7762 GOT_WORKTREE_GOT_DIR);
7763 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7764 goto done;
7765 else
7766 error = NULL;
7767 if (worktree) {
7768 repo_path =
7769 strdup(got_worktree_get_repo_path(worktree));
7770 if (repo_path == NULL)
7771 error = got_error_from_errno("strdup");
7772 if (error)
7773 goto done;
7774 } else {
7775 repo_path = strdup(cwd);
7776 if (repo_path == NULL) {
7777 error = got_error_from_errno("strdup");
7778 goto done;
7783 if (do_list || verify_tags) {
7784 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7785 if (error != NULL)
7786 goto done;
7787 error = get_allowed_signers(&allowed_signers, repo, worktree);
7788 if (error)
7789 goto done;
7790 error = get_revoked_signers(&revoked_signers, repo, worktree);
7791 if (error)
7792 goto done;
7793 if (worktree) {
7794 /* Release work tree lock. */
7795 got_worktree_close(worktree);
7796 worktree = NULL;
7800 * Remove "cpath" promise unless needed for signature tmpfile
7801 * creation.
7803 if (verify_tags)
7804 got_sigs_apply_unveil();
7805 else {
7806 #ifndef PROFILE
7807 if (pledge("stdio rpath wpath flock proc exec sendfd "
7808 "unveil", NULL) == -1)
7809 err(1, "pledge");
7810 #endif
7812 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7813 if (error)
7814 goto done;
7815 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7816 revoked_signers, verbosity);
7817 } else {
7818 error = get_gitconfig_path(&gitconfig_path);
7819 if (error)
7820 goto done;
7821 error = got_repo_open(&repo, repo_path, gitconfig_path,
7822 pack_fds);
7823 if (error != NULL)
7824 goto done;
7826 error = get_author(&tagger, repo, worktree);
7827 if (error)
7828 goto done;
7829 if (signer_id == NULL)
7830 signer_id = get_signer_id(repo, worktree);
7832 if (tagmsg) {
7833 if (signer_id) {
7834 error = got_sigs_apply_unveil();
7835 if (error)
7836 goto done;
7838 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7839 if (error)
7840 goto done;
7843 if (commit_id_arg == NULL) {
7844 struct got_reference *head_ref;
7845 struct got_object_id *commit_id;
7846 error = got_ref_open(&head_ref, repo,
7847 worktree ? got_worktree_get_head_ref_name(worktree)
7848 : GOT_REF_HEAD, 0);
7849 if (error)
7850 goto done;
7851 error = got_ref_resolve(&commit_id, repo, head_ref);
7852 got_ref_close(head_ref);
7853 if (error)
7854 goto done;
7855 error = got_object_id_str(&commit_id_str, commit_id);
7856 free(commit_id);
7857 if (error)
7858 goto done;
7859 } else {
7860 error = got_keyword_to_idstr(&keyword_idstr,
7861 commit_id_arg, repo, worktree);
7862 if (error != NULL)
7863 goto done;
7864 commit_id_str = keyword_idstr;
7867 if (worktree) {
7868 /* Release work tree lock. */
7869 got_worktree_close(worktree);
7870 worktree = NULL;
7873 error = add_tag(repo, tagger, tag_name,
7874 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7875 signer_id, verbosity);
7877 done:
7878 if (repo) {
7879 const struct got_error *close_err = got_repo_close(repo);
7880 if (error == NULL)
7881 error = close_err;
7883 if (worktree)
7884 got_worktree_close(worktree);
7885 if (pack_fds) {
7886 const struct got_error *pack_err =
7887 got_repo_pack_fds_close(pack_fds);
7888 if (error == NULL)
7889 error = pack_err;
7891 free(cwd);
7892 free(repo_path);
7893 free(gitconfig_path);
7894 free(commit_id_str);
7895 free(tagger);
7896 free(allowed_signers);
7897 free(revoked_signers);
7898 return error;
7901 __dead static void
7902 usage_add(void)
7904 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7905 exit(1);
7908 static const struct got_error *
7909 add_progress(void *arg, unsigned char status, const char *path)
7911 while (path[0] == '/')
7912 path++;
7913 printf("%c %s\n", status, path);
7914 return NULL;
7917 static const struct got_error *
7918 cmd_add(int argc, char *argv[])
7920 const struct got_error *error = NULL;
7921 struct got_repository *repo = NULL;
7922 struct got_worktree *worktree = NULL;
7923 char *cwd = NULL;
7924 struct got_pathlist_head paths;
7925 struct got_pathlist_entry *pe;
7926 int ch, can_recurse = 0, no_ignores = 0;
7927 int *pack_fds = NULL;
7929 TAILQ_INIT(&paths);
7931 #ifndef PROFILE
7932 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7933 NULL) == -1)
7934 err(1, "pledge");
7935 #endif
7937 while ((ch = getopt(argc, argv, "IR")) != -1) {
7938 switch (ch) {
7939 case 'I':
7940 no_ignores = 1;
7941 break;
7942 case 'R':
7943 can_recurse = 1;
7944 break;
7945 default:
7946 usage_add();
7947 /* NOTREACHED */
7951 argc -= optind;
7952 argv += optind;
7954 if (argc < 1)
7955 usage_add();
7957 cwd = getcwd(NULL, 0);
7958 if (cwd == NULL) {
7959 error = got_error_from_errno("getcwd");
7960 goto done;
7963 error = got_repo_pack_fds_open(&pack_fds);
7964 if (error != NULL)
7965 goto done;
7967 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7968 if (error) {
7969 if (error->code == GOT_ERR_NOT_WORKTREE)
7970 error = wrap_not_worktree_error(error, "add", cwd);
7971 goto done;
7974 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7975 NULL, pack_fds);
7976 if (error != NULL)
7977 goto done;
7979 error = apply_unveil(got_repo_get_path(repo), 1,
7980 got_worktree_get_root_path(worktree));
7981 if (error)
7982 goto done;
7984 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7985 if (error)
7986 goto done;
7988 if (!can_recurse) {
7989 char *ondisk_path;
7990 struct stat sb;
7991 TAILQ_FOREACH(pe, &paths, entry) {
7992 if (asprintf(&ondisk_path, "%s/%s",
7993 got_worktree_get_root_path(worktree),
7994 pe->path) == -1) {
7995 error = got_error_from_errno("asprintf");
7996 goto done;
7998 if (lstat(ondisk_path, &sb) == -1) {
7999 if (errno == ENOENT) {
8000 free(ondisk_path);
8001 continue;
8003 error = got_error_from_errno2("lstat",
8004 ondisk_path);
8005 free(ondisk_path);
8006 goto done;
8008 free(ondisk_path);
8009 if (S_ISDIR(sb.st_mode)) {
8010 error = got_error_msg(GOT_ERR_BAD_PATH,
8011 "adding directories requires -R option");
8012 goto done;
8017 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8018 NULL, repo, no_ignores);
8019 done:
8020 if (repo) {
8021 const struct got_error *close_err = got_repo_close(repo);
8022 if (error == NULL)
8023 error = close_err;
8025 if (worktree)
8026 got_worktree_close(worktree);
8027 if (pack_fds) {
8028 const struct got_error *pack_err =
8029 got_repo_pack_fds_close(pack_fds);
8030 if (error == NULL)
8031 error = pack_err;
8033 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8034 free(cwd);
8035 return error;
8038 __dead static void
8039 usage_remove(void)
8041 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8042 getprogname());
8043 exit(1);
8046 static const struct got_error *
8047 print_remove_status(void *arg, unsigned char status,
8048 unsigned char staged_status, const char *path)
8050 while (path[0] == '/')
8051 path++;
8052 if (status == GOT_STATUS_NONEXISTENT)
8053 return NULL;
8054 if (status == staged_status && (status == GOT_STATUS_DELETE))
8055 status = GOT_STATUS_NO_CHANGE;
8056 printf("%c%c %s\n", status, staged_status, path);
8057 return NULL;
8060 static const struct got_error *
8061 cmd_remove(int argc, char *argv[])
8063 const struct got_error *error = NULL;
8064 struct got_worktree *worktree = NULL;
8065 struct got_repository *repo = NULL;
8066 const char *status_codes = NULL;
8067 char *cwd = NULL;
8068 struct got_pathlist_head paths;
8069 struct got_pathlist_entry *pe;
8070 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8071 int ignore_missing_paths = 0;
8072 int *pack_fds = NULL;
8074 TAILQ_INIT(&paths);
8076 #ifndef PROFILE
8077 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8078 NULL) == -1)
8079 err(1, "pledge");
8080 #endif
8082 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8083 switch (ch) {
8084 case 'f':
8085 delete_local_mods = 1;
8086 ignore_missing_paths = 1;
8087 break;
8088 case 'k':
8089 keep_on_disk = 1;
8090 break;
8091 case 'R':
8092 can_recurse = 1;
8093 break;
8094 case 's':
8095 for (i = 0; optarg[i] != '\0'; i++) {
8096 switch (optarg[i]) {
8097 case GOT_STATUS_MODIFY:
8098 delete_local_mods = 1;
8099 break;
8100 case GOT_STATUS_MISSING:
8101 ignore_missing_paths = 1;
8102 break;
8103 default:
8104 errx(1, "invalid status code '%c'",
8105 optarg[i]);
8108 status_codes = optarg;
8109 break;
8110 default:
8111 usage_remove();
8112 /* NOTREACHED */
8116 argc -= optind;
8117 argv += optind;
8119 if (argc < 1)
8120 usage_remove();
8122 cwd = getcwd(NULL, 0);
8123 if (cwd == NULL) {
8124 error = got_error_from_errno("getcwd");
8125 goto done;
8128 error = got_repo_pack_fds_open(&pack_fds);
8129 if (error != NULL)
8130 goto done;
8132 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8133 if (error) {
8134 if (error->code == GOT_ERR_NOT_WORKTREE)
8135 error = wrap_not_worktree_error(error, "remove", cwd);
8136 goto done;
8139 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8140 NULL, pack_fds);
8141 if (error)
8142 goto done;
8144 error = apply_unveil(got_repo_get_path(repo), 1,
8145 got_worktree_get_root_path(worktree));
8146 if (error)
8147 goto done;
8149 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8150 if (error)
8151 goto done;
8153 if (!can_recurse) {
8154 char *ondisk_path;
8155 struct stat sb;
8156 TAILQ_FOREACH(pe, &paths, entry) {
8157 if (asprintf(&ondisk_path, "%s/%s",
8158 got_worktree_get_root_path(worktree),
8159 pe->path) == -1) {
8160 error = got_error_from_errno("asprintf");
8161 goto done;
8163 if (lstat(ondisk_path, &sb) == -1) {
8164 if (errno == ENOENT) {
8165 free(ondisk_path);
8166 continue;
8168 error = got_error_from_errno2("lstat",
8169 ondisk_path);
8170 free(ondisk_path);
8171 goto done;
8173 free(ondisk_path);
8174 if (S_ISDIR(sb.st_mode)) {
8175 error = got_error_msg(GOT_ERR_BAD_PATH,
8176 "removing directories requires -R option");
8177 goto done;
8182 error = got_worktree_schedule_delete(worktree, &paths,
8183 delete_local_mods, status_codes, print_remove_status, NULL,
8184 repo, keep_on_disk, ignore_missing_paths);
8185 done:
8186 if (repo) {
8187 const struct got_error *close_err = got_repo_close(repo);
8188 if (error == NULL)
8189 error = close_err;
8191 if (worktree)
8192 got_worktree_close(worktree);
8193 if (pack_fds) {
8194 const struct got_error *pack_err =
8195 got_repo_pack_fds_close(pack_fds);
8196 if (error == NULL)
8197 error = pack_err;
8199 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8200 free(cwd);
8201 return error;
8204 __dead static void
8205 usage_patch(void)
8207 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8208 "[patchfile]\n", getprogname());
8209 exit(1);
8212 static const struct got_error *
8213 patch_from_stdin(int *patchfd)
8215 const struct got_error *err = NULL;
8216 ssize_t r;
8217 char buf[BUFSIZ];
8218 sig_t sighup, sigint, sigquit;
8220 *patchfd = got_opentempfd();
8221 if (*patchfd == -1)
8222 return got_error_from_errno("got_opentempfd");
8224 sighup = signal(SIGHUP, SIG_DFL);
8225 sigint = signal(SIGINT, SIG_DFL);
8226 sigquit = signal(SIGQUIT, SIG_DFL);
8228 for (;;) {
8229 r = read(0, buf, sizeof(buf));
8230 if (r == -1) {
8231 err = got_error_from_errno("read");
8232 break;
8234 if (r == 0)
8235 break;
8236 if (write(*patchfd, buf, r) == -1) {
8237 err = got_error_from_errno("write");
8238 break;
8242 signal(SIGHUP, sighup);
8243 signal(SIGINT, sigint);
8244 signal(SIGQUIT, sigquit);
8246 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8247 err = got_error_from_errno("lseek");
8249 if (err != NULL) {
8250 close(*patchfd);
8251 *patchfd = -1;
8254 return err;
8257 struct got_patch_progress_arg {
8258 int did_something;
8259 int conflicts;
8260 int rejects;
8263 static const struct got_error *
8264 patch_progress(void *arg, const char *old, const char *new,
8265 unsigned char status, const struct got_error *error, int old_from,
8266 int old_lines, int new_from, int new_lines, int offset,
8267 int ws_mangled, const struct got_error *hunk_err)
8269 const char *path = new == NULL ? old : new;
8270 struct got_patch_progress_arg *a = arg;
8272 while (*path == '/')
8273 path++;
8275 if (status != GOT_STATUS_NO_CHANGE &&
8276 status != 0 /* per-hunk progress */) {
8277 printf("%c %s\n", status, path);
8278 a->did_something = 1;
8281 if (hunk_err == NULL) {
8282 if (status == GOT_STATUS_CANNOT_UPDATE)
8283 a->rejects++;
8284 else if (status == GOT_STATUS_CONFLICT)
8285 a->conflicts++;
8288 if (error != NULL)
8289 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8291 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8292 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8293 old_lines, new_from, new_lines);
8294 if (hunk_err != NULL)
8295 printf("%s\n", hunk_err->msg);
8296 else if (offset != 0)
8297 printf("applied with offset %d\n", offset);
8298 else
8299 printf("hunk contains mangled whitespace\n");
8302 return NULL;
8305 static void
8306 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8308 if (!ppa->did_something)
8309 return;
8311 if (ppa->conflicts > 0)
8312 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8314 if (ppa->rejects > 0) {
8315 printf("Files where patch failed to apply: %d\n",
8316 ppa->rejects);
8320 static const struct got_error *
8321 cmd_patch(int argc, char *argv[])
8323 const struct got_error *error = NULL, *close_error = NULL;
8324 struct got_worktree *worktree = NULL;
8325 struct got_repository *repo = NULL;
8326 struct got_reflist_head refs;
8327 struct got_object_id *commit_id = NULL;
8328 const char *commit_id_str = NULL;
8329 struct stat sb;
8330 const char *errstr;
8331 char *cwd = NULL, *keyword_idstr = NULL;
8332 int ch, nop = 0, strip = -1, reverse = 0;
8333 int patchfd;
8334 int *pack_fds = NULL;
8335 struct got_patch_progress_arg ppa;
8337 TAILQ_INIT(&refs);
8339 #ifndef PROFILE
8340 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8341 "unveil", NULL) == -1)
8342 err(1, "pledge");
8343 #endif
8345 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8346 switch (ch) {
8347 case 'c':
8348 commit_id_str = optarg;
8349 break;
8350 case 'n':
8351 nop = 1;
8352 break;
8353 case 'p':
8354 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8355 if (errstr != NULL)
8356 errx(1, "pathname strip count is %s: %s",
8357 errstr, optarg);
8358 break;
8359 case 'R':
8360 reverse = 1;
8361 break;
8362 default:
8363 usage_patch();
8364 /* NOTREACHED */
8368 argc -= optind;
8369 argv += optind;
8371 if (argc == 0) {
8372 error = patch_from_stdin(&patchfd);
8373 if (error)
8374 return error;
8375 } else if (argc == 1) {
8376 patchfd = open(argv[0], O_RDONLY);
8377 if (patchfd == -1) {
8378 error = got_error_from_errno2("open", argv[0]);
8379 return error;
8381 if (fstat(patchfd, &sb) == -1) {
8382 error = got_error_from_errno2("fstat", argv[0]);
8383 goto done;
8385 if (!S_ISREG(sb.st_mode)) {
8386 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8387 goto done;
8389 } else
8390 usage_patch();
8392 if ((cwd = getcwd(NULL, 0)) == NULL) {
8393 error = got_error_from_errno("getcwd");
8394 goto done;
8397 error = got_repo_pack_fds_open(&pack_fds);
8398 if (error != NULL)
8399 goto done;
8401 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8402 if (error != NULL)
8403 goto done;
8405 const char *repo_path = got_worktree_get_repo_path(worktree);
8406 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8407 if (error != NULL)
8408 goto done;
8410 error = apply_unveil(got_repo_get_path(repo), 0,
8411 got_worktree_get_root_path(worktree));
8412 if (error != NULL)
8413 goto done;
8415 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8416 if (error)
8417 goto done;
8419 if (commit_id_str != NULL) {
8420 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8421 repo, worktree);
8422 if (error != NULL)
8423 goto done;
8425 error = got_repo_match_object_id(&commit_id, NULL,
8426 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8427 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8428 if (error)
8429 goto done;
8432 memset(&ppa, 0, sizeof(ppa));
8433 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8434 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8435 print_patch_progress_stats(&ppa);
8436 done:
8437 got_ref_list_free(&refs);
8438 free(keyword_idstr);
8439 free(commit_id);
8440 if (repo) {
8441 close_error = got_repo_close(repo);
8442 if (error == NULL)
8443 error = close_error;
8445 if (worktree != NULL) {
8446 close_error = got_worktree_close(worktree);
8447 if (error == NULL)
8448 error = close_error;
8450 if (pack_fds) {
8451 const struct got_error *pack_err =
8452 got_repo_pack_fds_close(pack_fds);
8453 if (error == NULL)
8454 error = pack_err;
8456 free(cwd);
8457 return error;
8460 __dead static void
8461 usage_revert(void)
8463 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8464 getprogname());
8465 exit(1);
8468 static const struct got_error *
8469 revert_progress(void *arg, unsigned char status, const char *path)
8471 if (status == GOT_STATUS_UNVERSIONED)
8472 return NULL;
8474 while (path[0] == '/')
8475 path++;
8476 printf("%c %s\n", status, path);
8477 return NULL;
8480 struct choose_patch_arg {
8481 FILE *patch_script_file;
8482 const char *action;
8485 static const struct got_error *
8486 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8487 int nchanges, const char *action)
8489 const struct got_error *err;
8490 char *line = NULL;
8491 size_t linesize = 0;
8492 ssize_t linelen;
8494 switch (status) {
8495 case GOT_STATUS_ADD:
8496 printf("A %s\n%s this addition? [y/n] ", path, action);
8497 break;
8498 case GOT_STATUS_DELETE:
8499 printf("D %s\n%s this deletion? [y/n] ", path, action);
8500 break;
8501 case GOT_STATUS_MODIFY:
8502 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8503 return got_error_from_errno("fseek");
8504 printf(GOT_COMMIT_SEP_STR);
8505 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8506 printf("%s", line);
8507 if (linelen == -1 && ferror(patch_file)) {
8508 err = got_error_from_errno("getline");
8509 free(line);
8510 return err;
8512 free(line);
8513 printf(GOT_COMMIT_SEP_STR);
8514 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8515 path, n, nchanges, action);
8516 break;
8517 default:
8518 return got_error_path(path, GOT_ERR_FILE_STATUS);
8521 fflush(stdout);
8522 return NULL;
8525 static const struct got_error *
8526 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8527 FILE *patch_file, int n, int nchanges)
8529 const struct got_error *err = NULL;
8530 char *line = NULL;
8531 size_t linesize = 0;
8532 ssize_t linelen;
8533 int resp = ' ';
8534 struct choose_patch_arg *a = arg;
8536 *choice = GOT_PATCH_CHOICE_NONE;
8538 if (a->patch_script_file) {
8539 char *nl;
8540 err = show_change(status, path, patch_file, n, nchanges,
8541 a->action);
8542 if (err)
8543 return err;
8544 linelen = getline(&line, &linesize, a->patch_script_file);
8545 if (linelen == -1) {
8546 if (ferror(a->patch_script_file))
8547 return got_error_from_errno("getline");
8548 return NULL;
8550 nl = strchr(line, '\n');
8551 if (nl)
8552 *nl = '\0';
8553 if (strcmp(line, "y") == 0) {
8554 *choice = GOT_PATCH_CHOICE_YES;
8555 printf("y\n");
8556 } else if (strcmp(line, "n") == 0) {
8557 *choice = GOT_PATCH_CHOICE_NO;
8558 printf("n\n");
8559 } else if (strcmp(line, "q") == 0 &&
8560 status == GOT_STATUS_MODIFY) {
8561 *choice = GOT_PATCH_CHOICE_QUIT;
8562 printf("q\n");
8563 } else
8564 printf("invalid response '%s'\n", line);
8565 free(line);
8566 return NULL;
8569 while (resp != 'y' && resp != 'n' && resp != 'q') {
8570 err = show_change(status, path, patch_file, n, nchanges,
8571 a->action);
8572 if (err)
8573 return err;
8574 resp = getchar();
8575 if (resp == '\n')
8576 resp = getchar();
8577 if (status == GOT_STATUS_MODIFY) {
8578 if (resp != 'y' && resp != 'n' && resp != 'q') {
8579 printf("invalid response '%c'\n", resp);
8580 resp = ' ';
8582 } else if (resp != 'y' && resp != 'n') {
8583 printf("invalid response '%c'\n", resp);
8584 resp = ' ';
8588 if (resp == 'y')
8589 *choice = GOT_PATCH_CHOICE_YES;
8590 else if (resp == 'n')
8591 *choice = GOT_PATCH_CHOICE_NO;
8592 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8593 *choice = GOT_PATCH_CHOICE_QUIT;
8595 return NULL;
8598 struct wt_commitable_path_arg {
8599 struct got_pathlist_head *commit_paths;
8600 int *has_changes;
8604 * Shortcut work tree status callback to determine if the set of paths scanned
8605 * has at least one versioned path that is being modified and, if not NULL, is
8606 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8607 * soon as a path is passed with a status that satisfies this criteria.
8609 static const struct got_error *
8610 worktree_has_commitable_path(void *arg, unsigned char status,
8611 unsigned char staged_status, const char *path,
8612 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8613 struct got_object_id *commit_id, int dirfd, const char *de_name)
8615 struct wt_commitable_path_arg *a = arg;
8617 if (status == staged_status && (status == GOT_STATUS_DELETE))
8618 status = GOT_STATUS_NO_CHANGE;
8620 if (!(status == GOT_STATUS_NO_CHANGE ||
8621 status == GOT_STATUS_UNVERSIONED) ||
8622 staged_status != GOT_STATUS_NO_CHANGE) {
8623 if (a->commit_paths != NULL) {
8624 struct got_pathlist_entry *pe;
8626 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8627 if (strncmp(path, pe->path,
8628 pe->path_len) == 0) {
8629 *a->has_changes = 1;
8630 break;
8633 } else
8634 *a->has_changes = 1;
8636 if (*a->has_changes)
8637 return got_error(GOT_ERR_FILE_MODIFIED);
8640 return NULL;
8644 * Check that the changeset of the commit identified by id is
8645 * comprised of at least one modified path that is being committed.
8647 static const struct got_error *
8648 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8649 struct got_object_id *id, struct got_worktree *worktree,
8650 struct got_repository *repo)
8652 const struct got_error *err;
8653 struct got_pathlist_head paths;
8654 struct got_commit_object *commit = NULL, *pcommit = NULL;
8655 struct got_tree_object *tree = NULL, *ptree = NULL;
8656 struct got_object_qid *pid;
8658 TAILQ_INIT(&paths);
8660 err = got_object_open_as_commit(&commit, repo, id);
8661 if (err)
8662 goto done;
8664 err = got_object_open_as_tree(&tree, repo,
8665 got_object_commit_get_tree_id(commit));
8666 if (err)
8667 goto done;
8669 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8670 if (pid != NULL) {
8671 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8672 if (err)
8673 goto done;
8675 err = got_object_open_as_tree(&ptree, repo,
8676 got_object_commit_get_tree_id(pcommit));
8677 if (err)
8678 goto done;
8681 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8682 got_diff_tree_collect_changed_paths, &paths, 0);
8683 if (err)
8684 goto done;
8686 err = got_worktree_status(worktree, &paths, repo, 0,
8687 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8688 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8690 * At least one changed path in the referenced commit is
8691 * modified in the work tree, that's all we need to know!
8693 err = NULL;
8696 done:
8697 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8698 if (commit)
8699 got_object_commit_close(commit);
8700 if (pcommit)
8701 got_object_commit_close(pcommit);
8702 if (tree)
8703 got_object_tree_close(tree);
8704 if (ptree)
8705 got_object_tree_close(ptree);
8706 return err;
8710 * Remove any "logmsg" reference comprised entirely of paths that have
8711 * been reverted in this work tree. If any path in the logmsg ref changeset
8712 * remains in a changed state in the worktree, do not remove the reference.
8714 static const struct got_error *
8715 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8717 const struct got_error *err;
8718 struct got_reflist_head refs;
8719 struct got_reflist_entry *re;
8720 struct got_commit_object *commit = NULL;
8721 struct got_object_id *commit_id = NULL;
8722 struct wt_commitable_path_arg wcpa;
8723 char *uuidstr = NULL;
8725 TAILQ_INIT(&refs);
8727 err = got_worktree_get_uuid(&uuidstr, worktree);
8728 if (err)
8729 goto done;
8731 err = got_ref_list(&refs, repo, "refs/got/worktree",
8732 got_ref_cmp_by_name, repo);
8733 if (err)
8734 goto done;
8736 TAILQ_FOREACH(re, &refs, entry) {
8737 const char *refname;
8738 int has_changes = 0;
8740 refname = got_ref_get_name(re->ref);
8742 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8743 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8744 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8745 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8746 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8747 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8748 else
8749 continue;
8751 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8752 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8753 else
8754 continue;
8756 err = got_repo_match_object_id(&commit_id, NULL, refname,
8757 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8758 if (err)
8759 goto done;
8761 err = got_object_open_as_commit(&commit, repo, commit_id);
8762 if (err)
8763 goto done;
8765 wcpa.commit_paths = NULL;
8766 wcpa.has_changes = &has_changes;
8768 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8769 worktree, repo);
8770 if (err)
8771 goto done;
8773 if (!has_changes) {
8774 err = got_ref_delete(re->ref, repo);
8775 if (err)
8776 goto done;
8779 got_object_commit_close(commit);
8780 commit = NULL;
8781 free(commit_id);
8782 commit_id = NULL;
8785 done:
8786 free(uuidstr);
8787 free(commit_id);
8788 got_ref_list_free(&refs);
8789 if (commit)
8790 got_object_commit_close(commit);
8791 return err;
8794 static const struct got_error *
8795 cmd_revert(int argc, char *argv[])
8797 const struct got_error *error = NULL;
8798 struct got_worktree *worktree = NULL;
8799 struct got_repository *repo = NULL;
8800 char *cwd = NULL, *path = NULL;
8801 struct got_pathlist_head paths;
8802 struct got_pathlist_entry *pe;
8803 int ch, can_recurse = 0, pflag = 0;
8804 FILE *patch_script_file = NULL;
8805 const char *patch_script_path = NULL;
8806 struct choose_patch_arg cpa;
8807 int *pack_fds = NULL;
8809 TAILQ_INIT(&paths);
8811 #ifndef PROFILE
8812 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8813 "unveil", NULL) == -1)
8814 err(1, "pledge");
8815 #endif
8817 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8818 switch (ch) {
8819 case 'F':
8820 patch_script_path = optarg;
8821 break;
8822 case 'p':
8823 pflag = 1;
8824 break;
8825 case 'R':
8826 can_recurse = 1;
8827 break;
8828 default:
8829 usage_revert();
8830 /* NOTREACHED */
8834 argc -= optind;
8835 argv += optind;
8837 if (argc < 1)
8838 usage_revert();
8839 if (patch_script_path && !pflag)
8840 errx(1, "-F option can only be used together with -p option");
8842 cwd = getcwd(NULL, 0);
8843 if (cwd == NULL) {
8844 error = got_error_from_errno("getcwd");
8845 goto done;
8848 error = got_repo_pack_fds_open(&pack_fds);
8849 if (error != NULL)
8850 goto done;
8852 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8853 if (error) {
8854 if (error->code == GOT_ERR_NOT_WORKTREE)
8855 error = wrap_not_worktree_error(error, "revert", cwd);
8856 goto done;
8859 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8860 NULL, pack_fds);
8861 if (error != NULL)
8862 goto done;
8864 if (patch_script_path) {
8865 patch_script_file = fopen(patch_script_path, "re");
8866 if (patch_script_file == NULL) {
8867 error = got_error_from_errno2("fopen",
8868 patch_script_path);
8869 goto done;
8874 * XXX "c" perm needed on repo dir to delete merge references.
8876 error = apply_unveil(got_repo_get_path(repo), 0,
8877 got_worktree_get_root_path(worktree));
8878 if (error)
8879 goto done;
8881 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8882 if (error)
8883 goto done;
8885 if (!can_recurse) {
8886 char *ondisk_path;
8887 struct stat sb;
8888 TAILQ_FOREACH(pe, &paths, entry) {
8889 if (asprintf(&ondisk_path, "%s/%s",
8890 got_worktree_get_root_path(worktree),
8891 pe->path) == -1) {
8892 error = got_error_from_errno("asprintf");
8893 goto done;
8895 if (lstat(ondisk_path, &sb) == -1) {
8896 if (errno == ENOENT) {
8897 free(ondisk_path);
8898 continue;
8900 error = got_error_from_errno2("lstat",
8901 ondisk_path);
8902 free(ondisk_path);
8903 goto done;
8905 free(ondisk_path);
8906 if (S_ISDIR(sb.st_mode)) {
8907 error = got_error_msg(GOT_ERR_BAD_PATH,
8908 "reverting directories requires -R option");
8909 goto done;
8914 cpa.patch_script_file = patch_script_file;
8915 cpa.action = "revert";
8916 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8917 pflag ? choose_patch : NULL, &cpa, repo);
8919 error = rm_logmsg_ref(worktree, repo);
8920 done:
8921 if (patch_script_file && fclose(patch_script_file) == EOF &&
8922 error == NULL)
8923 error = got_error_from_errno2("fclose", patch_script_path);
8924 if (repo) {
8925 const struct got_error *close_err = got_repo_close(repo);
8926 if (error == NULL)
8927 error = close_err;
8929 if (worktree)
8930 got_worktree_close(worktree);
8931 if (pack_fds) {
8932 const struct got_error *pack_err =
8933 got_repo_pack_fds_close(pack_fds);
8934 if (error == NULL)
8935 error = pack_err;
8937 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8938 free(path);
8939 free(cwd);
8940 return error;
8943 __dead static void
8944 usage_commit(void)
8946 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8947 "[-m message] [path ...]\n", getprogname());
8948 exit(1);
8951 struct collect_commit_logmsg_arg {
8952 const char *cmdline_log;
8953 const char *prepared_log;
8954 const char *merged_log;
8955 int non_interactive;
8956 const char *editor;
8957 const char *worktree_path;
8958 const char *branch_name;
8959 const char *repo_path;
8960 char *logmsg_path;
8964 static const struct got_error *
8965 read_prepared_logmsg(char **logmsg, const char *path)
8967 const struct got_error *err = NULL;
8968 FILE *f = NULL;
8969 struct stat sb;
8970 size_t r;
8972 *logmsg = NULL;
8973 memset(&sb, 0, sizeof(sb));
8975 f = fopen(path, "re");
8976 if (f == NULL)
8977 return got_error_from_errno2("fopen", path);
8979 if (fstat(fileno(f), &sb) == -1) {
8980 err = got_error_from_errno2("fstat", path);
8981 goto done;
8983 if (sb.st_size == 0) {
8984 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8985 goto done;
8988 *logmsg = malloc(sb.st_size + 1);
8989 if (*logmsg == NULL) {
8990 err = got_error_from_errno("malloc");
8991 goto done;
8994 r = fread(*logmsg, 1, sb.st_size, f);
8995 if (r != sb.st_size) {
8996 if (ferror(f))
8997 err = got_error_from_errno2("fread", path);
8998 else
8999 err = got_error(GOT_ERR_IO);
9000 goto done;
9002 (*logmsg)[sb.st_size] = '\0';
9003 done:
9004 if (fclose(f) == EOF && err == NULL)
9005 err = got_error_from_errno2("fclose", path);
9006 if (err) {
9007 free(*logmsg);
9008 *logmsg = NULL;
9010 return err;
9013 static const struct got_error *
9014 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9015 const char *diff_path, char **logmsg, void *arg)
9017 char *initial_content = NULL;
9018 struct got_pathlist_entry *pe;
9019 const struct got_error *err = NULL;
9020 char *template = NULL;
9021 char *prepared_msg = NULL, *merged_msg = NULL;
9022 struct collect_commit_logmsg_arg *a = arg;
9023 int initial_content_len;
9024 int fd = -1;
9025 size_t len;
9027 /* if a message was specified on the command line, just use it */
9028 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9029 len = strlen(a->cmdline_log) + 1;
9030 *logmsg = malloc(len + 1);
9031 if (*logmsg == NULL)
9032 return got_error_from_errno("malloc");
9033 strlcpy(*logmsg, a->cmdline_log, len);
9034 return NULL;
9035 } else if (a->prepared_log != NULL && a->non_interactive)
9036 return read_prepared_logmsg(logmsg, a->prepared_log);
9038 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9039 return got_error_from_errno("asprintf");
9041 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9042 if (err)
9043 goto done;
9045 if (a->prepared_log) {
9046 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9047 if (err)
9048 goto done;
9049 } else if (a->merged_log) {
9050 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9051 if (err)
9052 goto done;
9055 initial_content_len = asprintf(&initial_content,
9056 "%s%s\n# changes to be committed on branch %s:\n",
9057 prepared_msg ? prepared_msg : "",
9058 merged_msg ? merged_msg : "", a->branch_name);
9059 if (initial_content_len == -1) {
9060 err = got_error_from_errno("asprintf");
9061 goto done;
9064 if (write(fd, initial_content, initial_content_len) == -1) {
9065 err = got_error_from_errno2("write", a->logmsg_path);
9066 goto done;
9069 TAILQ_FOREACH(pe, commitable_paths, entry) {
9070 struct got_commitable *ct = pe->data;
9071 dprintf(fd, "# %c %s\n",
9072 got_commitable_get_status(ct),
9073 got_commitable_get_path(ct));
9076 if (diff_path) {
9077 dprintf(fd, "# detailed changes can be viewed in %s\n",
9078 diff_path);
9081 if (close(fd) == -1) {
9082 err = got_error_from_errno2("close", a->logmsg_path);
9083 goto done;
9085 fd = -1;
9087 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9088 initial_content_len, a->prepared_log ? 0 : 1);
9089 done:
9090 free(initial_content);
9091 free(template);
9092 free(prepared_msg);
9093 free(merged_msg);
9095 if (fd != -1 && close(fd) == -1 && err == NULL)
9096 err = got_error_from_errno2("close", a->logmsg_path);
9098 /* Editor is done; we can now apply unveil(2) */
9099 if (err == NULL)
9100 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9101 if (err) {
9102 free(*logmsg);
9103 *logmsg = NULL;
9105 return err;
9108 static const struct got_error *
9109 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9110 const char *type, int has_content)
9112 const struct got_error *err = NULL;
9113 char *logmsg = NULL;
9115 err = got_object_commit_get_logmsg(&logmsg, commit);
9116 if (err)
9117 return err;
9119 if (fprintf(f, "%s# log message of %s commit %s:%s",
9120 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9121 err = got_ferror(f, GOT_ERR_IO);
9123 free(logmsg);
9124 return err;
9128 * Lookup "logmsg" references of backed-out and cherrypicked commits
9129 * belonging to the current work tree. If found, and the worktree has
9130 * at least one modified file that was changed in the referenced commit,
9131 * add its log message to a new temporary file at *logmsg_path.
9132 * Add all refs found to matched_refs to be scheduled for removal on
9133 * successful commit.
9135 static const struct got_error *
9136 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9137 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9138 struct got_repository *repo)
9140 const struct got_error *err;
9141 struct got_commit_object *commit = NULL;
9142 struct got_object_id *id = NULL;
9143 struct got_reflist_head refs;
9144 struct got_reflist_entry *re, *re_match;
9145 FILE *f = NULL;
9146 char *uuidstr = NULL;
9147 int added_logmsg = 0;
9149 TAILQ_INIT(&refs);
9151 *logmsg_path = NULL;
9153 err = got_worktree_get_uuid(&uuidstr, worktree);
9154 if (err)
9155 goto done;
9157 err = got_ref_list(&refs, repo, "refs/got/worktree",
9158 got_ref_cmp_by_name, repo);
9159 if (err)
9160 goto done;
9162 TAILQ_FOREACH(re, &refs, entry) {
9163 const char *refname, *type;
9164 struct wt_commitable_path_arg wcpa;
9165 int add_logmsg = 0;
9167 refname = got_ref_get_name(re->ref);
9169 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9170 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9171 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9172 type = "cherrypicked";
9173 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9174 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9175 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9176 type = "backed-out";
9177 } else
9178 continue;
9180 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9181 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9182 else
9183 continue;
9185 err = got_repo_match_object_id(&id, NULL, refname,
9186 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9187 if (err)
9188 goto done;
9190 err = got_object_open_as_commit(&commit, repo, id);
9191 if (err)
9192 goto done;
9194 wcpa.commit_paths = paths;
9195 wcpa.has_changes = &add_logmsg;
9197 err = commit_path_changed_in_worktree(&wcpa, id,
9198 worktree, repo);
9199 if (err)
9200 goto done;
9202 if (add_logmsg) {
9203 if (f == NULL) {
9204 err = got_opentemp_named(logmsg_path, &f,
9205 "got-commit-logmsg", "");
9206 if (err)
9207 goto done;
9209 err = cat_logmsg(f, commit, refname, type,
9210 added_logmsg);
9211 if (err)
9212 goto done;
9213 if (!added_logmsg)
9214 ++added_logmsg;
9216 err = got_reflist_entry_dup(&re_match, re);
9217 if (err)
9218 goto done;
9219 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9222 got_object_commit_close(commit);
9223 commit = NULL;
9224 free(id);
9225 id = NULL;
9228 done:
9229 free(id);
9230 free(uuidstr);
9231 got_ref_list_free(&refs);
9232 if (commit)
9233 got_object_commit_close(commit);
9234 if (f && fclose(f) == EOF && err == NULL)
9235 err = got_error_from_errno("fclose");
9236 if (!added_logmsg) {
9237 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9238 err = got_error_from_errno2("unlink", *logmsg_path);
9239 *logmsg_path = NULL;
9241 return err;
9244 static const struct got_error *
9245 cmd_commit(int argc, char *argv[])
9247 const struct got_error *error = NULL;
9248 struct got_worktree *worktree = NULL;
9249 struct got_repository *repo = NULL;
9250 char *cwd = NULL, *id_str = NULL;
9251 struct got_object_id *id = NULL;
9252 const char *logmsg = NULL;
9253 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9254 struct collect_commit_logmsg_arg cl_arg;
9255 const char *author = NULL;
9256 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9257 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9258 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9259 int show_diff = 1, commit_conflicts = 0;
9260 struct got_pathlist_head paths;
9261 struct got_reflist_head refs;
9262 struct got_reflist_entry *re;
9263 int *pack_fds = NULL;
9265 TAILQ_INIT(&refs);
9266 TAILQ_INIT(&paths);
9267 cl_arg.logmsg_path = NULL;
9269 #ifndef PROFILE
9270 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9271 "unveil", NULL) == -1)
9272 err(1, "pledge");
9273 #endif
9275 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9276 switch (ch) {
9277 case 'A':
9278 author = optarg;
9279 error = valid_author(author);
9280 if (error)
9281 return error;
9282 break;
9283 case 'C':
9284 commit_conflicts = 1;
9285 break;
9286 case 'F':
9287 if (logmsg != NULL)
9288 option_conflict('F', 'm');
9289 prepared_logmsg = realpath(optarg, NULL);
9290 if (prepared_logmsg == NULL)
9291 return got_error_from_errno2("realpath",
9292 optarg);
9293 break;
9294 case 'm':
9295 if (prepared_logmsg)
9296 option_conflict('m', 'F');
9297 logmsg = optarg;
9298 break;
9299 case 'N':
9300 non_interactive = 1;
9301 break;
9302 case 'n':
9303 show_diff = 0;
9304 break;
9305 case 'S':
9306 allow_bad_symlinks = 1;
9307 break;
9308 default:
9309 usage_commit();
9310 /* NOTREACHED */
9314 argc -= optind;
9315 argv += optind;
9317 cwd = getcwd(NULL, 0);
9318 if (cwd == NULL) {
9319 error = got_error_from_errno("getcwd");
9320 goto done;
9323 error = got_repo_pack_fds_open(&pack_fds);
9324 if (error != NULL)
9325 goto done;
9327 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9328 if (error) {
9329 if (error->code == GOT_ERR_NOT_WORKTREE)
9330 error = wrap_not_worktree_error(error, "commit", cwd);
9331 goto done;
9334 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9335 if (error)
9336 goto done;
9337 if (rebase_in_progress) {
9338 error = got_error(GOT_ERR_REBASING);
9339 goto done;
9342 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9343 worktree);
9344 if (error)
9345 goto done;
9347 error = get_gitconfig_path(&gitconfig_path);
9348 if (error)
9349 goto done;
9350 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9351 gitconfig_path, pack_fds);
9352 if (error != NULL)
9353 goto done;
9355 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9356 if (error)
9357 goto done;
9358 if (merge_in_progress) {
9359 error = got_error(GOT_ERR_MERGE_BUSY);
9360 goto done;
9363 error = get_author(&committer, repo, worktree);
9364 if (error)
9365 goto done;
9367 if (author == NULL)
9368 author = committer;
9371 * unveil(2) traverses exec(2); if an editor is used we have
9372 * to apply unveil after the log message has been written.
9374 if (logmsg == NULL || strlen(logmsg) == 0)
9375 error = get_editor(&editor);
9376 else
9377 error = apply_unveil(got_repo_get_path(repo), 0,
9378 got_worktree_get_root_path(worktree));
9379 if (error)
9380 goto done;
9382 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9383 if (error)
9384 goto done;
9386 if (prepared_logmsg == NULL) {
9387 error = lookup_logmsg_ref(&merged_logmsg,
9388 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9389 if (error)
9390 goto done;
9393 cl_arg.editor = editor;
9394 cl_arg.cmdline_log = logmsg;
9395 cl_arg.prepared_log = prepared_logmsg;
9396 cl_arg.merged_log = merged_logmsg;
9397 cl_arg.non_interactive = non_interactive;
9398 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9399 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9400 if (!histedit_in_progress) {
9401 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9402 error = got_error(GOT_ERR_COMMIT_BRANCH);
9403 goto done;
9405 cl_arg.branch_name += 11;
9407 cl_arg.repo_path = got_repo_get_path(repo);
9408 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9409 allow_bad_symlinks, show_diff, commit_conflicts,
9410 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9411 if (error) {
9412 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9413 cl_arg.logmsg_path != NULL)
9414 preserve_logmsg = 1;
9415 goto done;
9418 error = got_object_id_str(&id_str, id);
9419 if (error)
9420 goto done;
9421 printf("Created commit %s\n", id_str);
9423 TAILQ_FOREACH(re, &refs, entry) {
9424 error = got_ref_delete(re->ref, repo);
9425 if (error)
9426 goto done;
9429 done:
9430 if (preserve_logmsg) {
9431 fprintf(stderr, "%s: log message preserved in %s\n",
9432 getprogname(), cl_arg.logmsg_path);
9433 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9434 error == NULL)
9435 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9436 free(cl_arg.logmsg_path);
9437 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9438 error = got_error_from_errno2("unlink", merged_logmsg);
9439 free(merged_logmsg);
9440 if (repo) {
9441 const struct got_error *close_err = got_repo_close(repo);
9442 if (error == NULL)
9443 error = close_err;
9445 if (worktree)
9446 got_worktree_close(worktree);
9447 if (pack_fds) {
9448 const struct got_error *pack_err =
9449 got_repo_pack_fds_close(pack_fds);
9450 if (error == NULL)
9451 error = pack_err;
9453 got_ref_list_free(&refs);
9454 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9455 free(cwd);
9456 free(id_str);
9457 free(gitconfig_path);
9458 free(editor);
9459 free(committer);
9460 free(prepared_logmsg);
9461 return error;
9464 __dead static void
9465 usage_send(void)
9467 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9468 "[-r repository-path] [-t tag] [remote-repository]\n",
9469 getprogname());
9470 exit(1);
9473 static void
9474 print_load_info(int print_colored, int print_found, int print_trees,
9475 int ncolored, int nfound, int ntrees)
9477 if (print_colored) {
9478 printf("%d commit%s colored", ncolored,
9479 ncolored == 1 ? "" : "s");
9481 if (print_found) {
9482 printf("%s%d object%s found",
9483 ncolored > 0 ? "; " : "",
9484 nfound, nfound == 1 ? "" : "s");
9486 if (print_trees) {
9487 printf("; %d tree%s scanned", ntrees,
9488 ntrees == 1 ? "" : "s");
9492 struct got_send_progress_arg {
9493 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9494 int verbosity;
9495 int last_ncolored;
9496 int last_nfound;
9497 int last_ntrees;
9498 int loading_done;
9499 int last_ncommits;
9500 int last_nobj_total;
9501 int last_p_deltify;
9502 int last_p_written;
9503 int last_p_sent;
9504 int printed_something;
9505 int sent_something;
9506 struct got_pathlist_head *delete_branches;
9509 static const struct got_error *
9510 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9511 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9512 int nobj_written, off_t bytes_sent, const char *refname,
9513 const char *errmsg, int success)
9515 struct got_send_progress_arg *a = arg;
9516 char scaled_packsize[FMT_SCALED_STRSIZE];
9517 char scaled_sent[FMT_SCALED_STRSIZE];
9518 int p_deltify = 0, p_written = 0, p_sent = 0;
9519 int print_colored = 0, print_found = 0, print_trees = 0;
9520 int print_searching = 0, print_total = 0;
9521 int print_deltify = 0, print_written = 0, print_sent = 0;
9523 if (a->verbosity < 0)
9524 return NULL;
9526 if (refname) {
9527 const char *status = success ? "accepted" : "rejected";
9529 if (success) {
9530 struct got_pathlist_entry *pe;
9531 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9532 const char *branchname = pe->path;
9533 if (got_path_cmp(branchname, refname,
9534 strlen(branchname), strlen(refname)) == 0) {
9535 status = "deleted";
9536 a->sent_something = 1;
9537 break;
9542 if (a->printed_something)
9543 putchar('\n');
9544 printf("Server has %s %s", status, refname);
9545 if (errmsg)
9546 printf(": %s", errmsg);
9547 a->printed_something = 1;
9548 return NULL;
9551 if (a->last_ncolored != ncolored) {
9552 print_colored = 1;
9553 a->last_ncolored = ncolored;
9556 if (a->last_nfound != nfound) {
9557 print_colored = 1;
9558 print_found = 1;
9559 a->last_nfound = nfound;
9562 if (a->last_ntrees != ntrees) {
9563 print_colored = 1;
9564 print_found = 1;
9565 print_trees = 1;
9566 a->last_ntrees = ntrees;
9569 if ((print_colored || print_found || print_trees) &&
9570 !a->loading_done) {
9571 printf("\r");
9572 print_load_info(print_colored, print_found, print_trees,
9573 ncolored, nfound, ntrees);
9574 a->printed_something = 1;
9575 fflush(stdout);
9576 return NULL;
9577 } else if (!a->loading_done) {
9578 printf("\r");
9579 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9580 printf("\n");
9581 a->loading_done = 1;
9584 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9585 return got_error_from_errno("fmt_scaled");
9586 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9587 return got_error_from_errno("fmt_scaled");
9589 if (a->last_ncommits != ncommits) {
9590 print_searching = 1;
9591 a->last_ncommits = ncommits;
9594 if (a->last_nobj_total != nobj_total) {
9595 print_searching = 1;
9596 print_total = 1;
9597 a->last_nobj_total = nobj_total;
9600 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9601 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9602 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9603 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9604 return got_error(GOT_ERR_NO_SPACE);
9607 if (nobj_deltify > 0 || nobj_written > 0) {
9608 if (nobj_deltify > 0) {
9609 p_deltify = (nobj_deltify * 100) / nobj_total;
9610 if (p_deltify != a->last_p_deltify) {
9611 a->last_p_deltify = p_deltify;
9612 print_searching = 1;
9613 print_total = 1;
9614 print_deltify = 1;
9617 if (nobj_written > 0) {
9618 p_written = (nobj_written * 100) / nobj_total;
9619 if (p_written != a->last_p_written) {
9620 a->last_p_written = p_written;
9621 print_searching = 1;
9622 print_total = 1;
9623 print_deltify = 1;
9624 print_written = 1;
9629 if (bytes_sent > 0) {
9630 p_sent = (bytes_sent * 100) / packfile_size;
9631 if (p_sent != a->last_p_sent) {
9632 a->last_p_sent = p_sent;
9633 print_searching = 1;
9634 print_total = 1;
9635 print_deltify = 1;
9636 print_written = 1;
9637 print_sent = 1;
9639 a->sent_something = 1;
9642 if (print_searching || print_total || print_deltify || print_written ||
9643 print_sent)
9644 printf("\r");
9645 if (print_searching)
9646 printf("packing %d reference%s", ncommits,
9647 ncommits == 1 ? "" : "s");
9648 if (print_total)
9649 printf("; %d object%s", nobj_total,
9650 nobj_total == 1 ? "" : "s");
9651 if (print_deltify)
9652 printf("; deltify: %d%%", p_deltify);
9653 if (print_sent)
9654 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9655 scaled_packsize, p_sent);
9656 else if (print_written)
9657 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9658 scaled_packsize, p_written);
9659 if (print_searching || print_total || print_deltify ||
9660 print_written || print_sent) {
9661 a->printed_something = 1;
9662 fflush(stdout);
9664 return NULL;
9667 static const struct got_error *
9668 cmd_send(int argc, char *argv[])
9670 const struct got_error *error = NULL;
9671 char *cwd = NULL, *repo_path = NULL;
9672 const char *remote_name;
9673 char *proto = NULL, *host = NULL, *port = NULL;
9674 char *repo_name = NULL, *server_path = NULL;
9675 const struct got_remote_repo *remotes, *remote = NULL;
9676 int nremotes, nbranches = 0, ndelete_branches = 0;
9677 struct got_repository *repo = NULL;
9678 struct got_worktree *worktree = NULL;
9679 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9680 struct got_pathlist_head branches;
9681 struct got_pathlist_head tags;
9682 struct got_reflist_head all_branches;
9683 struct got_reflist_head all_tags;
9684 struct got_pathlist_head delete_args;
9685 struct got_pathlist_head delete_branches;
9686 struct got_reflist_entry *re;
9687 struct got_pathlist_entry *pe;
9688 int i, ch, sendfd = -1, sendstatus;
9689 pid_t sendpid = -1;
9690 struct got_send_progress_arg spa;
9691 int verbosity = 0, overwrite_refs = 0;
9692 int send_all_branches = 0, send_all_tags = 0;
9693 struct got_reference *ref = NULL;
9694 int *pack_fds = NULL;
9696 TAILQ_INIT(&branches);
9697 TAILQ_INIT(&tags);
9698 TAILQ_INIT(&all_branches);
9699 TAILQ_INIT(&all_tags);
9700 TAILQ_INIT(&delete_args);
9701 TAILQ_INIT(&delete_branches);
9703 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9704 switch (ch) {
9705 case 'a':
9706 send_all_branches = 1;
9707 break;
9708 case 'b':
9709 error = got_pathlist_append(&branches, optarg, NULL);
9710 if (error)
9711 return error;
9712 nbranches++;
9713 break;
9714 case 'd':
9715 error = got_pathlist_append(&delete_args, optarg, NULL);
9716 if (error)
9717 return error;
9718 break;
9719 case 'f':
9720 overwrite_refs = 1;
9721 break;
9722 case 'q':
9723 verbosity = -1;
9724 break;
9725 case 'r':
9726 repo_path = realpath(optarg, NULL);
9727 if (repo_path == NULL)
9728 return got_error_from_errno2("realpath",
9729 optarg);
9730 got_path_strip_trailing_slashes(repo_path);
9731 break;
9732 case 'T':
9733 send_all_tags = 1;
9734 break;
9735 case 't':
9736 error = got_pathlist_append(&tags, optarg, NULL);
9737 if (error)
9738 return error;
9739 break;
9740 case 'v':
9741 if (verbosity < 0)
9742 verbosity = 0;
9743 else if (verbosity < 3)
9744 verbosity++;
9745 break;
9746 default:
9747 usage_send();
9748 /* NOTREACHED */
9751 argc -= optind;
9752 argv += optind;
9754 if (send_all_branches && !TAILQ_EMPTY(&branches))
9755 option_conflict('a', 'b');
9756 if (send_all_tags && !TAILQ_EMPTY(&tags))
9757 option_conflict('T', 't');
9760 if (argc == 0)
9761 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9762 else if (argc == 1)
9763 remote_name = argv[0];
9764 else
9765 usage_send();
9767 cwd = getcwd(NULL, 0);
9768 if (cwd == NULL) {
9769 error = got_error_from_errno("getcwd");
9770 goto done;
9773 error = got_repo_pack_fds_open(&pack_fds);
9774 if (error != NULL)
9775 goto done;
9777 if (repo_path == NULL) {
9778 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9779 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9780 goto done;
9781 else
9782 error = NULL;
9783 if (worktree) {
9784 repo_path =
9785 strdup(got_worktree_get_repo_path(worktree));
9786 if (repo_path == NULL)
9787 error = got_error_from_errno("strdup");
9788 if (error)
9789 goto done;
9790 } else {
9791 repo_path = strdup(cwd);
9792 if (repo_path == NULL) {
9793 error = got_error_from_errno("strdup");
9794 goto done;
9799 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9800 if (error)
9801 goto done;
9803 if (worktree) {
9804 worktree_conf = got_worktree_get_gotconfig(worktree);
9805 if (worktree_conf) {
9806 got_gotconfig_get_remotes(&nremotes, &remotes,
9807 worktree_conf);
9808 for (i = 0; i < nremotes; i++) {
9809 if (strcmp(remotes[i].name, remote_name) == 0) {
9810 remote = &remotes[i];
9811 break;
9816 if (remote == NULL) {
9817 repo_conf = got_repo_get_gotconfig(repo);
9818 if (repo_conf) {
9819 got_gotconfig_get_remotes(&nremotes, &remotes,
9820 repo_conf);
9821 for (i = 0; i < nremotes; i++) {
9822 if (strcmp(remotes[i].name, remote_name) == 0) {
9823 remote = &remotes[i];
9824 break;
9829 if (remote == NULL) {
9830 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9831 for (i = 0; i < nremotes; i++) {
9832 if (strcmp(remotes[i].name, remote_name) == 0) {
9833 remote = &remotes[i];
9834 break;
9838 if (remote == NULL) {
9839 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9840 goto done;
9843 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9844 &repo_name, remote->send_url);
9845 if (error)
9846 goto done;
9848 if (strcmp(proto, "git") == 0) {
9849 #ifndef PROFILE
9850 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9851 "sendfd dns inet unveil", NULL) == -1)
9852 err(1, "pledge");
9853 #endif
9854 } else if (strcmp(proto, "git+ssh") == 0 ||
9855 strcmp(proto, "ssh") == 0) {
9856 #ifndef PROFILE
9857 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9858 "sendfd unveil", NULL) == -1)
9859 err(1, "pledge");
9860 #endif
9861 } else if (strcmp(proto, "http") == 0 ||
9862 strcmp(proto, "git+http") == 0) {
9863 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9864 goto done;
9865 } else {
9866 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9867 goto done;
9870 error = got_dial_apply_unveil(proto);
9871 if (error)
9872 goto done;
9874 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9875 if (error)
9876 goto done;
9878 if (send_all_branches) {
9879 error = got_ref_list(&all_branches, repo, "refs/heads",
9880 got_ref_cmp_by_name, NULL);
9881 if (error)
9882 goto done;
9883 TAILQ_FOREACH(re, &all_branches, entry) {
9884 const char *branchname = got_ref_get_name(re->ref);
9885 error = got_pathlist_append(&branches,
9886 branchname, NULL);
9887 if (error)
9888 goto done;
9889 nbranches++;
9891 } else if (nbranches == 0) {
9892 for (i = 0; i < remote->nsend_branches; i++) {
9893 error = got_pathlist_append(&branches,
9894 remote->send_branches[i], NULL);
9895 if (error)
9896 goto done;
9900 if (send_all_tags) {
9901 error = got_ref_list(&all_tags, repo, "refs/tags",
9902 got_ref_cmp_by_name, NULL);
9903 if (error)
9904 goto done;
9905 TAILQ_FOREACH(re, &all_tags, entry) {
9906 const char *tagname = got_ref_get_name(re->ref);
9907 error = got_pathlist_append(&tags,
9908 tagname, NULL);
9909 if (error)
9910 goto done;
9915 * To prevent accidents only branches in refs/heads/ can be deleted
9916 * with 'got send -d'.
9917 * Deleting anything else requires local repository access or Git.
9919 TAILQ_FOREACH(pe, &delete_args, entry) {
9920 const char *branchname = pe->path;
9921 char *s;
9922 struct got_pathlist_entry *new;
9923 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9924 s = strdup(branchname);
9925 if (s == NULL) {
9926 error = got_error_from_errno("strdup");
9927 goto done;
9929 } else {
9930 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9931 error = got_error_from_errno("asprintf");
9932 goto done;
9935 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9936 if (error || new == NULL /* duplicate */)
9937 free(s);
9938 if (error)
9939 goto done;
9940 ndelete_branches++;
9943 if (nbranches == 0 && ndelete_branches == 0) {
9944 struct got_reference *head_ref;
9945 if (worktree)
9946 error = got_ref_open(&head_ref, repo,
9947 got_worktree_get_head_ref_name(worktree), 0);
9948 else
9949 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9950 if (error)
9951 goto done;
9952 if (got_ref_is_symbolic(head_ref)) {
9953 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9954 got_ref_close(head_ref);
9955 if (error)
9956 goto done;
9957 } else
9958 ref = head_ref;
9959 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9960 NULL);
9961 if (error)
9962 goto done;
9963 nbranches++;
9966 if (verbosity >= 0) {
9967 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9968 remote->name, proto, host,
9969 port ? ":" : "", port ? port : "",
9970 *server_path == '/' ? "" : "/", server_path);
9973 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9974 server_path, verbosity);
9975 if (error)
9976 goto done;
9978 memset(&spa, 0, sizeof(spa));
9979 spa.last_scaled_packsize[0] = '\0';
9980 spa.last_p_deltify = -1;
9981 spa.last_p_written = -1;
9982 spa.verbosity = verbosity;
9983 spa.delete_branches = &delete_branches;
9984 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9985 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9986 check_cancelled, NULL);
9987 if (spa.printed_something)
9988 putchar('\n');
9989 if (error)
9990 goto done;
9991 if (!spa.sent_something && verbosity >= 0)
9992 printf("Already up-to-date\n");
9993 done:
9994 if (sendpid > 0) {
9995 if (kill(sendpid, SIGTERM) == -1)
9996 error = got_error_from_errno("kill");
9997 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9998 error = got_error_from_errno("waitpid");
10000 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10001 error = got_error_from_errno("close");
10002 if (repo) {
10003 const struct got_error *close_err = got_repo_close(repo);
10004 if (error == NULL)
10005 error = close_err;
10007 if (worktree)
10008 got_worktree_close(worktree);
10009 if (pack_fds) {
10010 const struct got_error *pack_err =
10011 got_repo_pack_fds_close(pack_fds);
10012 if (error == NULL)
10013 error = pack_err;
10015 if (ref)
10016 got_ref_close(ref);
10017 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10018 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10019 got_ref_list_free(&all_branches);
10020 got_ref_list_free(&all_tags);
10021 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10022 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10023 free(cwd);
10024 free(repo_path);
10025 free(proto);
10026 free(host);
10027 free(port);
10028 free(server_path);
10029 free(repo_name);
10030 return error;
10034 * Print and if delete is set delete all ref_prefix references.
10035 * If wanted_ref is not NULL, only print or delete this reference.
10037 static const struct got_error *
10038 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10039 const char *wanted_ref, int delete, struct got_worktree *worktree,
10040 struct got_repository *repo)
10042 const struct got_error *err;
10043 struct got_pathlist_head paths;
10044 struct got_reflist_head refs;
10045 struct got_reflist_entry *re;
10046 struct got_reflist_object_id_map *refs_idmap = NULL;
10047 struct got_commit_object *commit = NULL;
10048 struct got_object_id *id = NULL;
10049 const char *header_prefix;
10050 char *uuidstr = NULL;
10051 int found = 0;
10053 TAILQ_INIT(&refs);
10054 TAILQ_INIT(&paths);
10056 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10057 if (err)
10058 goto done;
10060 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10061 if (err)
10062 goto done;
10064 if (worktree != NULL) {
10065 err = got_worktree_get_uuid(&uuidstr, worktree);
10066 if (err)
10067 goto done;
10070 if (wanted_ref) {
10071 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10072 wanted_ref += 11;
10075 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10076 header_prefix = "backout";
10077 else
10078 header_prefix = "cherrypick";
10080 TAILQ_FOREACH(re, &refs, entry) {
10081 const char *refname, *wt;
10083 refname = got_ref_get_name(re->ref);
10085 err = check_cancelled(NULL);
10086 if (err)
10087 goto done;
10089 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10090 refname += prefix_len + 1; /* skip '-' delimiter */
10091 else
10092 continue;
10094 wt = refname;
10096 if (worktree == NULL || strncmp(refname, uuidstr,
10097 GOT_WORKTREE_UUID_STRLEN) == 0)
10098 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10099 else
10100 continue;
10102 err = got_repo_match_object_id(&id, NULL, refname,
10103 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10104 if (err)
10105 goto done;
10107 err = got_object_open_as_commit(&commit, repo, id);
10108 if (err)
10109 goto done;
10111 if (wanted_ref)
10112 found = strncmp(wanted_ref, refname,
10113 strlen(wanted_ref)) == 0;
10114 if (wanted_ref && !found) {
10115 struct got_reflist_head *ci_refs;
10117 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10118 id);
10120 if (ci_refs) {
10121 char *refs_str = NULL;
10122 char const *r = NULL;
10124 err = build_refs_str(&refs_str, ci_refs, id,
10125 repo, 1);
10126 if (err)
10127 goto done;
10129 r = refs_str;
10130 while (r) {
10131 if (strncmp(r, wanted_ref,
10132 strlen(wanted_ref)) == 0) {
10133 found = 1;
10134 break;
10136 r = strchr(r, ' ');
10137 if (r)
10138 ++r;
10140 free(refs_str);
10144 if (wanted_ref == NULL || found) {
10145 if (delete) {
10146 err = got_ref_delete(re->ref, repo);
10147 if (err)
10148 goto done;
10149 printf("Deleted: ");
10150 err = print_commit_oneline(commit, id, repo,
10151 refs_idmap);
10152 } else {
10154 * Print paths modified by commit to help
10155 * associate commits with worktree changes.
10157 err = get_changed_paths(&paths, commit,
10158 repo, NULL);
10159 if (err)
10160 goto done;
10162 err = print_commit(commit, id, repo, NULL,
10163 &paths, NULL, 0, 0, refs_idmap, NULL,
10164 header_prefix);
10165 got_pathlist_free(&paths,
10166 GOT_PATHLIST_FREE_ALL);
10168 if (worktree == NULL)
10169 printf("work tree: %.*s\n\n",
10170 GOT_WORKTREE_UUID_STRLEN, wt);
10172 if (err || found)
10173 goto done;
10176 got_object_commit_close(commit);
10177 commit = NULL;
10178 free(id);
10179 id = NULL;
10182 if (wanted_ref != NULL && !found)
10183 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10185 done:
10186 free(id);
10187 free(uuidstr);
10188 got_ref_list_free(&refs);
10189 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10190 if (refs_idmap)
10191 got_reflist_object_id_map_free(refs_idmap);
10192 if (commit)
10193 got_object_commit_close(commit);
10194 return err;
10198 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10199 * identified by id for log messages to prepopulate the editor on commit.
10201 static const struct got_error *
10202 logmsg_ref(struct got_object_id *id, const char *prefix,
10203 struct got_worktree *worktree, struct got_repository *repo)
10205 const struct got_error *err = NULL;
10206 char *idstr, *ref = NULL, *refname = NULL;
10207 int histedit_in_progress;
10208 int rebase_in_progress, merge_in_progress;
10211 * Silenty refuse to create merge reference if any histedit, merge,
10212 * or rebase operation is in progress.
10214 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10215 worktree);
10216 if (err)
10217 return err;
10218 if (histedit_in_progress)
10219 return NULL;
10221 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10222 if (err)
10223 return err;
10224 if (rebase_in_progress)
10225 return NULL;
10227 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10228 repo);
10229 if (err)
10230 return err;
10231 if (merge_in_progress)
10232 return NULL;
10234 err = got_object_id_str(&idstr, id);
10235 if (err)
10236 return err;
10238 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10239 if (err)
10240 goto done;
10242 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10243 err = got_error_from_errno("asprintf");
10244 goto done;
10247 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10248 -1, repo);
10249 done:
10250 free(ref);
10251 free(idstr);
10252 free(refname);
10253 return err;
10256 __dead static void
10257 usage_cherrypick(void)
10259 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10260 getprogname());
10261 exit(1);
10264 static const struct got_error *
10265 cmd_cherrypick(int argc, char *argv[])
10267 const struct got_error *error = NULL;
10268 struct got_worktree *worktree = NULL;
10269 struct got_repository *repo = NULL;
10270 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10271 struct got_object_id *commit_id = NULL;
10272 struct got_commit_object *commit = NULL;
10273 struct got_object_qid *pid;
10274 int ch, list_refs = 0, remove_refs = 0;
10275 struct got_update_progress_arg upa;
10276 int *pack_fds = NULL;
10278 #ifndef PROFILE
10279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10280 "unveil", NULL) == -1)
10281 err(1, "pledge");
10282 #endif
10284 while ((ch = getopt(argc, argv, "lX")) != -1) {
10285 switch (ch) {
10286 case 'l':
10287 list_refs = 1;
10288 break;
10289 case 'X':
10290 remove_refs = 1;
10291 break;
10292 default:
10293 usage_cherrypick();
10294 /* NOTREACHED */
10298 argc -= optind;
10299 argv += optind;
10301 if (list_refs || remove_refs) {
10302 if (argc != 0 && argc != 1)
10303 usage_cherrypick();
10304 } else if (argc != 1)
10305 usage_cherrypick();
10306 if (list_refs && remove_refs)
10307 option_conflict('l', 'X');
10309 cwd = getcwd(NULL, 0);
10310 if (cwd == NULL) {
10311 error = got_error_from_errno("getcwd");
10312 goto done;
10315 error = got_repo_pack_fds_open(&pack_fds);
10316 if (error != NULL)
10317 goto done;
10319 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10320 if (error) {
10321 if (list_refs || remove_refs) {
10322 if (error->code != GOT_ERR_NOT_WORKTREE)
10323 goto done;
10324 } else {
10325 if (error->code == GOT_ERR_NOT_WORKTREE)
10326 error = wrap_not_worktree_error(error,
10327 "cherrypick", cwd);
10328 goto done;
10332 error = got_repo_open(&repo,
10333 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10334 NULL, pack_fds);
10335 if (error != NULL)
10336 goto done;
10338 error = apply_unveil(got_repo_get_path(repo), 0,
10339 worktree ? got_worktree_get_root_path(worktree) : NULL);
10340 if (error)
10341 goto done;
10343 if (list_refs || remove_refs) {
10344 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10345 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10346 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10347 goto done;
10350 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10351 if (error != NULL)
10352 goto done;
10354 error = got_repo_match_object_id(&commit_id, NULL,
10355 keyword_idstr != NULL ? keyword_idstr : argv[0],
10356 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10357 if (error)
10358 goto done;
10359 error = got_object_id_str(&commit_id_str, commit_id);
10360 if (error)
10361 goto done;
10363 error = got_object_open_as_commit(&commit, repo, commit_id);
10364 if (error)
10365 goto done;
10366 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10367 memset(&upa, 0, sizeof(upa));
10368 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10369 commit_id, repo, update_progress, &upa, check_cancelled,
10370 NULL);
10371 if (error != NULL)
10372 goto done;
10374 if (upa.did_something) {
10375 error = logmsg_ref(commit_id,
10376 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10377 if (error)
10378 goto done;
10379 printf("Merged commit %s\n", commit_id_str);
10381 print_merge_progress_stats(&upa);
10382 done:
10383 free(cwd);
10384 free(keyword_idstr);
10385 if (commit)
10386 got_object_commit_close(commit);
10387 free(commit_id_str);
10388 if (worktree)
10389 got_worktree_close(worktree);
10390 if (repo) {
10391 const struct got_error *close_err = got_repo_close(repo);
10392 if (error == NULL)
10393 error = close_err;
10395 if (pack_fds) {
10396 const struct got_error *pack_err =
10397 got_repo_pack_fds_close(pack_fds);
10398 if (error == NULL)
10399 error = pack_err;
10402 return error;
10405 __dead static void
10406 usage_backout(void)
10408 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10409 exit(1);
10412 static const struct got_error *
10413 cmd_backout(int argc, char *argv[])
10415 const struct got_error *error = NULL;
10416 struct got_worktree *worktree = NULL;
10417 struct got_repository *repo = NULL;
10418 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10419 struct got_object_id *commit_id = NULL;
10420 struct got_commit_object *commit = NULL;
10421 struct got_object_qid *pid;
10422 int ch, list_refs = 0, remove_refs = 0;
10423 struct got_update_progress_arg upa;
10424 int *pack_fds = NULL;
10426 #ifndef PROFILE
10427 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10428 "unveil", NULL) == -1)
10429 err(1, "pledge");
10430 #endif
10432 while ((ch = getopt(argc, argv, "lX")) != -1) {
10433 switch (ch) {
10434 case 'l':
10435 list_refs = 1;
10436 break;
10437 case 'X':
10438 remove_refs = 1;
10439 break;
10440 default:
10441 usage_backout();
10442 /* NOTREACHED */
10446 argc -= optind;
10447 argv += optind;
10449 if (list_refs || remove_refs) {
10450 if (argc != 0 && argc != 1)
10451 usage_backout();
10452 } else if (argc != 1)
10453 usage_backout();
10454 if (list_refs && remove_refs)
10455 option_conflict('l', 'X');
10457 cwd = getcwd(NULL, 0);
10458 if (cwd == NULL) {
10459 error = got_error_from_errno("getcwd");
10460 goto done;
10463 error = got_repo_pack_fds_open(&pack_fds);
10464 if (error != NULL)
10465 goto done;
10467 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10468 if (error) {
10469 if (list_refs || remove_refs) {
10470 if (error->code != GOT_ERR_NOT_WORKTREE)
10471 goto done;
10472 } else {
10473 if (error->code == GOT_ERR_NOT_WORKTREE)
10474 error = wrap_not_worktree_error(error,
10475 "backout", cwd);
10476 goto done;
10480 error = got_repo_open(&repo,
10481 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10482 NULL, pack_fds);
10483 if (error != NULL)
10484 goto done;
10486 error = apply_unveil(got_repo_get_path(repo), 0,
10487 worktree ? got_worktree_get_root_path(worktree) : NULL);
10488 if (error)
10489 goto done;
10491 if (list_refs || remove_refs) {
10492 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10493 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10494 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10495 goto done;
10498 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10499 if (error != NULL)
10500 goto done;
10502 error = got_repo_match_object_id(&commit_id, NULL,
10503 keyword_idstr != NULL ? keyword_idstr : argv[0],
10504 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10505 if (error)
10506 goto done;
10507 error = got_object_id_str(&commit_id_str, commit_id);
10508 if (error)
10509 goto done;
10511 error = got_object_open_as_commit(&commit, repo, commit_id);
10512 if (error)
10513 goto done;
10514 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10515 if (pid == NULL) {
10516 error = got_error(GOT_ERR_ROOT_COMMIT);
10517 goto done;
10520 memset(&upa, 0, sizeof(upa));
10521 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10522 repo, update_progress, &upa, check_cancelled, NULL);
10523 if (error != NULL)
10524 goto done;
10526 if (upa.did_something) {
10527 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10528 worktree, repo);
10529 if (error)
10530 goto done;
10531 printf("Backed out commit %s\n", commit_id_str);
10533 print_merge_progress_stats(&upa);
10534 done:
10535 free(cwd);
10536 free(keyword_idstr);
10537 if (commit)
10538 got_object_commit_close(commit);
10539 free(commit_id_str);
10540 if (worktree)
10541 got_worktree_close(worktree);
10542 if (repo) {
10543 const struct got_error *close_err = got_repo_close(repo);
10544 if (error == NULL)
10545 error = close_err;
10547 if (pack_fds) {
10548 const struct got_error *pack_err =
10549 got_repo_pack_fds_close(pack_fds);
10550 if (error == NULL)
10551 error = pack_err;
10553 return error;
10556 __dead static void
10557 usage_rebase(void)
10559 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10560 exit(1);
10563 static void
10564 trim_logmsg(char *logmsg, int limit)
10566 char *nl;
10567 size_t len;
10569 len = strlen(logmsg);
10570 if (len > limit)
10571 len = limit;
10572 logmsg[len] = '\0';
10573 nl = strchr(logmsg, '\n');
10574 if (nl)
10575 *nl = '\0';
10578 static const struct got_error *
10579 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10581 const struct got_error *err;
10582 char *logmsg0 = NULL;
10583 const char *s;
10585 err = got_object_commit_get_logmsg(&logmsg0, commit);
10586 if (err)
10587 return err;
10589 s = logmsg0;
10590 while (isspace((unsigned char)s[0]))
10591 s++;
10593 *logmsg = strdup(s);
10594 if (*logmsg == NULL) {
10595 err = got_error_from_errno("strdup");
10596 goto done;
10599 trim_logmsg(*logmsg, limit);
10600 done:
10601 free(logmsg0);
10602 return err;
10605 static const struct got_error *
10606 show_rebase_merge_conflict(struct got_object_id *id,
10607 struct got_repository *repo)
10609 const struct got_error *err;
10610 struct got_commit_object *commit = NULL;
10611 char *id_str = NULL, *logmsg = NULL;
10613 err = got_object_open_as_commit(&commit, repo, id);
10614 if (err)
10615 return err;
10617 err = got_object_id_str(&id_str, id);
10618 if (err)
10619 goto done;
10621 id_str[12] = '\0';
10623 err = get_short_logmsg(&logmsg, 42, commit);
10624 if (err)
10625 goto done;
10627 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10628 done:
10629 free(id_str);
10630 got_object_commit_close(commit);
10631 free(logmsg);
10632 return err;
10635 static const struct got_error *
10636 show_rebase_progress(struct got_commit_object *commit,
10637 struct got_object_id *old_id, struct got_object_id *new_id)
10639 const struct got_error *err;
10640 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10642 err = got_object_id_str(&old_id_str, old_id);
10643 if (err)
10644 goto done;
10646 if (new_id) {
10647 err = got_object_id_str(&new_id_str, new_id);
10648 if (err)
10649 goto done;
10652 old_id_str[12] = '\0';
10653 if (new_id_str)
10654 new_id_str[12] = '\0';
10656 err = get_short_logmsg(&logmsg, 42, commit);
10657 if (err)
10658 goto done;
10660 printf("%s -> %s: %s\n", old_id_str,
10661 new_id_str ? new_id_str : "no-op change", logmsg);
10662 done:
10663 free(old_id_str);
10664 free(new_id_str);
10665 free(logmsg);
10666 return err;
10669 static const struct got_error *
10670 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10671 struct got_reference *branch, struct got_reference *tmp_branch,
10672 struct got_repository *repo, int create_backup)
10674 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10675 return got_worktree_rebase_complete(worktree, fileindex,
10676 tmp_branch, branch, repo, create_backup);
10679 static const struct got_error *
10680 rebase_commit(struct got_pathlist_head *merged_paths,
10681 struct got_worktree *worktree, struct got_fileindex *fileindex,
10682 struct got_reference *tmp_branch, const char *committer,
10683 struct got_object_id *commit_id, int allow_conflict,
10684 struct got_repository *repo)
10686 const struct got_error *error;
10687 struct got_commit_object *commit;
10688 struct got_object_id *new_commit_id;
10690 error = got_object_open_as_commit(&commit, repo, commit_id);
10691 if (error)
10692 return error;
10694 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10695 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10696 allow_conflict, repo);
10697 if (error) {
10698 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10699 goto done;
10700 error = show_rebase_progress(commit, commit_id, NULL);
10701 } else {
10702 error = show_rebase_progress(commit, commit_id, new_commit_id);
10703 free(new_commit_id);
10705 done:
10706 got_object_commit_close(commit);
10707 return error;
10710 struct check_path_prefix_arg {
10711 const char *path_prefix;
10712 size_t len;
10713 int errcode;
10716 static const struct got_error *
10717 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10718 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10719 struct got_object_id *id1, struct got_object_id *id2,
10720 const char *path1, const char *path2,
10721 mode_t mode1, mode_t mode2, struct got_repository *repo)
10723 struct check_path_prefix_arg *a = arg;
10725 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10726 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10727 return got_error(a->errcode);
10729 return NULL;
10732 static const struct got_error *
10733 check_path_prefix(struct got_object_id *parent_id,
10734 struct got_object_id *commit_id, const char *path_prefix,
10735 int errcode, struct got_repository *repo)
10737 const struct got_error *err;
10738 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10739 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10740 struct check_path_prefix_arg cpp_arg;
10742 if (got_path_is_root_dir(path_prefix))
10743 return NULL;
10745 err = got_object_open_as_commit(&commit, repo, commit_id);
10746 if (err)
10747 goto done;
10749 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10750 if (err)
10751 goto done;
10753 err = got_object_open_as_tree(&tree1, repo,
10754 got_object_commit_get_tree_id(parent_commit));
10755 if (err)
10756 goto done;
10758 err = got_object_open_as_tree(&tree2, repo,
10759 got_object_commit_get_tree_id(commit));
10760 if (err)
10761 goto done;
10763 cpp_arg.path_prefix = path_prefix;
10764 while (cpp_arg.path_prefix[0] == '/')
10765 cpp_arg.path_prefix++;
10766 cpp_arg.len = strlen(cpp_arg.path_prefix);
10767 cpp_arg.errcode = errcode;
10768 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10769 check_path_prefix_in_diff, &cpp_arg, 0);
10770 done:
10771 if (tree1)
10772 got_object_tree_close(tree1);
10773 if (tree2)
10774 got_object_tree_close(tree2);
10775 if (commit)
10776 got_object_commit_close(commit);
10777 if (parent_commit)
10778 got_object_commit_close(parent_commit);
10779 return err;
10782 static const struct got_error *
10783 collect_commits(struct got_object_id_queue *commits,
10784 struct got_object_id *initial_commit_id,
10785 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10786 const char *path_prefix, int path_prefix_errcode,
10787 struct got_repository *repo)
10789 const struct got_error *err = NULL;
10790 struct got_commit_graph *graph = NULL;
10791 struct got_object_id parent_id, commit_id;
10792 struct got_object_qid *qid;
10794 err = got_commit_graph_open(&graph, "/", 1);
10795 if (err)
10796 return err;
10798 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10799 check_cancelled, NULL);
10800 if (err)
10801 goto done;
10803 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10804 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10805 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10806 check_cancelled, NULL);
10807 if (err) {
10808 if (err->code == GOT_ERR_ITER_COMPLETED) {
10809 err = got_error_msg(GOT_ERR_ANCESTRY,
10810 "ran out of commits to rebase before "
10811 "youngest common ancestor commit has "
10812 "been reached?!?");
10814 goto done;
10815 } else {
10816 err = check_path_prefix(&parent_id, &commit_id,
10817 path_prefix, path_prefix_errcode, repo);
10818 if (err)
10819 goto done;
10821 err = got_object_qid_alloc(&qid, &commit_id);
10822 if (err)
10823 goto done;
10824 STAILQ_INSERT_HEAD(commits, qid, entry);
10826 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10829 done:
10830 got_commit_graph_close(graph);
10831 return err;
10834 static const struct got_error *
10835 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10837 const struct got_error *err = NULL;
10838 time_t committer_time;
10839 struct tm tm;
10840 char datebuf[11]; /* YYYY-MM-DD + NUL */
10841 char *author0 = NULL, *author, *smallerthan;
10842 char *logmsg0 = NULL, *logmsg, *newline;
10844 committer_time = got_object_commit_get_committer_time(commit);
10845 if (gmtime_r(&committer_time, &tm) == NULL)
10846 return got_error_from_errno("gmtime_r");
10847 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10848 return got_error(GOT_ERR_NO_SPACE);
10850 author0 = strdup(got_object_commit_get_author(commit));
10851 if (author0 == NULL)
10852 return got_error_from_errno("strdup");
10853 author = author0;
10854 smallerthan = strchr(author, '<');
10855 if (smallerthan && smallerthan[1] != '\0')
10856 author = smallerthan + 1;
10857 author[strcspn(author, "@>")] = '\0';
10859 err = got_object_commit_get_logmsg(&logmsg0, commit);
10860 if (err)
10861 goto done;
10862 logmsg = logmsg0;
10863 while (*logmsg == '\n')
10864 logmsg++;
10865 newline = strchr(logmsg, '\n');
10866 if (newline)
10867 *newline = '\0';
10869 if (asprintf(brief_str, "%s %s %s",
10870 datebuf, author, logmsg) == -1)
10871 err = got_error_from_errno("asprintf");
10872 done:
10873 free(author0);
10874 free(logmsg0);
10875 return err;
10878 static const struct got_error *
10879 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10880 struct got_repository *repo)
10882 const struct got_error *err;
10883 char *id_str;
10885 err = got_object_id_str(&id_str, id);
10886 if (err)
10887 return err;
10889 err = got_ref_delete(ref, repo);
10890 if (err)
10891 goto done;
10893 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10894 done:
10895 free(id_str);
10896 return err;
10899 static const struct got_error *
10900 print_backup_ref(const char *branch_name, const char *new_id_str,
10901 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10902 struct got_reflist_object_id_map *refs_idmap,
10903 struct got_repository *repo)
10905 const struct got_error *err = NULL;
10906 struct got_reflist_head *refs;
10907 char *refs_str = NULL;
10908 struct got_object_id *new_commit_id = NULL;
10909 struct got_commit_object *new_commit = NULL;
10910 char *new_commit_brief_str = NULL;
10911 struct got_object_id *yca_id = NULL;
10912 struct got_commit_object *yca_commit = NULL;
10913 char *yca_id_str = NULL, *yca_brief_str = NULL;
10914 char *custom_refs_str;
10916 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10917 return got_error_from_errno("asprintf");
10919 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10920 0, 0, refs_idmap, custom_refs_str, NULL);
10921 if (err)
10922 goto done;
10924 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10925 if (err)
10926 goto done;
10928 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10929 if (refs) {
10930 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10931 if (err)
10932 goto done;
10935 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10936 if (err)
10937 goto done;
10939 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10940 if (err)
10941 goto done;
10943 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10944 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10945 if (err)
10946 goto done;
10948 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10949 refs_str ? " (" : "", refs_str ? refs_str : "",
10950 refs_str ? ")" : "", new_commit_brief_str);
10951 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10952 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10953 free(refs_str);
10954 refs_str = NULL;
10956 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10957 if (err)
10958 goto done;
10960 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10961 if (err)
10962 goto done;
10964 err = got_object_id_str(&yca_id_str, yca_id);
10965 if (err)
10966 goto done;
10968 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10969 if (refs) {
10970 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10971 if (err)
10972 goto done;
10974 printf("history forked at %s%s%s%s\n %s\n",
10975 yca_id_str,
10976 refs_str ? " (" : "", refs_str ? refs_str : "",
10977 refs_str ? ")" : "", yca_brief_str);
10979 done:
10980 free(custom_refs_str);
10981 free(new_commit_id);
10982 free(refs_str);
10983 free(yca_id);
10984 free(yca_id_str);
10985 free(yca_brief_str);
10986 if (new_commit)
10987 got_object_commit_close(new_commit);
10988 if (yca_commit)
10989 got_object_commit_close(yca_commit);
10991 return err;
10994 static const struct got_error *
10995 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10996 struct got_repository *repo)
10998 const struct got_error *err;
10999 struct got_reflist_head refs;
11000 struct got_reflist_entry *re;
11001 char *uuidstr = NULL;
11002 static char msg[160];
11004 TAILQ_INIT(&refs);
11006 err = got_worktree_get_uuid(&uuidstr, worktree);
11007 if (err)
11008 goto done;
11010 err = got_ref_list(&refs, repo, "refs/got/worktree",
11011 got_ref_cmp_by_name, repo);
11012 if (err)
11013 goto done;
11015 TAILQ_FOREACH(re, &refs, entry) {
11016 const char *cmd, *refname, *type;
11018 refname = got_ref_get_name(re->ref);
11020 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11021 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11022 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11023 cmd = "cherrypick";
11024 type = "cherrypicked";
11025 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11026 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11027 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11028 cmd = "backout";
11029 type = "backed-out";
11030 } else
11031 continue;
11033 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11034 continue;
11036 snprintf(msg, sizeof(msg),
11037 "work tree has references created by %s commits which "
11038 "must be removed with 'got %s -X' before running the %s "
11039 "command", type, cmd, caller);
11040 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11041 goto done;
11044 done:
11045 free(uuidstr);
11046 got_ref_list_free(&refs);
11047 return err;
11050 static const struct got_error *
11051 process_backup_refs(const char *backup_ref_prefix,
11052 const char *wanted_branch_name,
11053 int delete, struct got_repository *repo)
11055 const struct got_error *err;
11056 struct got_reflist_head refs, backup_refs;
11057 struct got_reflist_entry *re;
11058 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11059 struct got_object_id *old_commit_id = NULL;
11060 char *branch_name = NULL;
11061 struct got_commit_object *old_commit = NULL;
11062 struct got_reflist_object_id_map *refs_idmap = NULL;
11063 int wanted_branch_found = 0;
11065 TAILQ_INIT(&refs);
11066 TAILQ_INIT(&backup_refs);
11068 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11069 if (err)
11070 return err;
11072 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11073 if (err)
11074 goto done;
11076 if (wanted_branch_name) {
11077 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11078 wanted_branch_name += 11;
11081 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11082 got_ref_cmp_by_commit_timestamp_descending, repo);
11083 if (err)
11084 goto done;
11086 TAILQ_FOREACH(re, &backup_refs, entry) {
11087 const char *refname = got_ref_get_name(re->ref);
11088 char *slash;
11090 err = check_cancelled(NULL);
11091 if (err)
11092 break;
11094 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11095 if (err)
11096 break;
11098 err = got_object_open_as_commit(&old_commit, repo,
11099 old_commit_id);
11100 if (err)
11101 break;
11103 if (strncmp(backup_ref_prefix, refname,
11104 backup_ref_prefix_len) == 0)
11105 refname += backup_ref_prefix_len;
11107 while (refname[0] == '/')
11108 refname++;
11110 branch_name = strdup(refname);
11111 if (branch_name == NULL) {
11112 err = got_error_from_errno("strdup");
11113 break;
11115 slash = strrchr(branch_name, '/');
11116 if (slash) {
11117 *slash = '\0';
11118 refname += strlen(branch_name) + 1;
11121 if (wanted_branch_name == NULL ||
11122 strcmp(wanted_branch_name, branch_name) == 0) {
11123 wanted_branch_found = 1;
11124 if (delete) {
11125 err = delete_backup_ref(re->ref,
11126 old_commit_id, repo);
11127 } else {
11128 err = print_backup_ref(branch_name, refname,
11129 old_commit_id, old_commit, refs_idmap,
11130 repo);
11132 if (err)
11133 break;
11136 free(old_commit_id);
11137 old_commit_id = NULL;
11138 free(branch_name);
11139 branch_name = NULL;
11140 got_object_commit_close(old_commit);
11141 old_commit = NULL;
11144 if (wanted_branch_name && !wanted_branch_found) {
11145 err = got_error_fmt(GOT_ERR_NOT_REF,
11146 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11148 done:
11149 if (refs_idmap)
11150 got_reflist_object_id_map_free(refs_idmap);
11151 got_ref_list_free(&refs);
11152 got_ref_list_free(&backup_refs);
11153 free(old_commit_id);
11154 free(branch_name);
11155 if (old_commit)
11156 got_object_commit_close(old_commit);
11157 return err;
11160 static const struct got_error *
11161 abort_progress(void *arg, unsigned char status, const char *path)
11164 * Unversioned files should not clutter progress output when
11165 * an operation is aborted.
11167 if (status == GOT_STATUS_UNVERSIONED)
11168 return NULL;
11170 return update_progress(arg, status, path);
11173 static const struct got_error *
11174 cmd_rebase(int argc, char *argv[])
11176 const struct got_error *error = NULL;
11177 struct got_worktree *worktree = NULL;
11178 struct got_repository *repo = NULL;
11179 struct got_fileindex *fileindex = NULL;
11180 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11181 struct got_reference *branch = NULL;
11182 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11183 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11184 struct got_object_id *resume_commit_id = NULL;
11185 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11186 struct got_object_id *head_commit_id = NULL;
11187 struct got_reference *head_ref = NULL;
11188 struct got_commit_object *commit = NULL;
11189 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11190 int histedit_in_progress = 0, merge_in_progress = 0;
11191 int create_backup = 1, list_backups = 0, delete_backups = 0;
11192 int allow_conflict = 0;
11193 struct got_object_id_queue commits;
11194 struct got_pathlist_head merged_paths;
11195 const struct got_object_id_queue *parent_ids;
11196 struct got_object_qid *qid, *pid;
11197 struct got_update_progress_arg upa;
11198 int *pack_fds = NULL;
11200 STAILQ_INIT(&commits);
11201 TAILQ_INIT(&merged_paths);
11202 memset(&upa, 0, sizeof(upa));
11204 #ifndef PROFILE
11205 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11206 "unveil", NULL) == -1)
11207 err(1, "pledge");
11208 #endif
11210 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11211 switch (ch) {
11212 case 'a':
11213 abort_rebase = 1;
11214 break;
11215 case 'C':
11216 allow_conflict = 1;
11217 break;
11218 case 'c':
11219 continue_rebase = 1;
11220 break;
11221 case 'l':
11222 list_backups = 1;
11223 break;
11224 case 'X':
11225 delete_backups = 1;
11226 break;
11227 default:
11228 usage_rebase();
11229 /* NOTREACHED */
11233 argc -= optind;
11234 argv += optind;
11236 if (list_backups) {
11237 if (abort_rebase)
11238 option_conflict('l', 'a');
11239 if (allow_conflict)
11240 option_conflict('l', 'C');
11241 if (continue_rebase)
11242 option_conflict('l', 'c');
11243 if (delete_backups)
11244 option_conflict('l', 'X');
11245 if (argc != 0 && argc != 1)
11246 usage_rebase();
11247 } else if (delete_backups) {
11248 if (abort_rebase)
11249 option_conflict('X', 'a');
11250 if (allow_conflict)
11251 option_conflict('X', 'C');
11252 if (continue_rebase)
11253 option_conflict('X', 'c');
11254 if (list_backups)
11255 option_conflict('l', 'X');
11256 if (argc != 0 && argc != 1)
11257 usage_rebase();
11258 } else if (allow_conflict) {
11259 if (abort_rebase)
11260 option_conflict('C', 'a');
11261 if (!continue_rebase)
11262 errx(1, "-C option requires -c");
11263 } else {
11264 if (abort_rebase && continue_rebase)
11265 usage_rebase();
11266 else if (abort_rebase || continue_rebase) {
11267 if (argc != 0)
11268 usage_rebase();
11269 } else if (argc != 1)
11270 usage_rebase();
11273 cwd = getcwd(NULL, 0);
11274 if (cwd == NULL) {
11275 error = got_error_from_errno("getcwd");
11276 goto done;
11279 error = got_repo_pack_fds_open(&pack_fds);
11280 if (error != NULL)
11281 goto done;
11283 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11284 if (error) {
11285 if (list_backups || delete_backups) {
11286 if (error->code != GOT_ERR_NOT_WORKTREE)
11287 goto done;
11288 } else {
11289 if (error->code == GOT_ERR_NOT_WORKTREE)
11290 error = wrap_not_worktree_error(error,
11291 "rebase", cwd);
11292 goto done;
11296 error = get_gitconfig_path(&gitconfig_path);
11297 if (error)
11298 goto done;
11299 error = got_repo_open(&repo,
11300 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11301 gitconfig_path, pack_fds);
11302 if (error != NULL)
11303 goto done;
11305 if (worktree != NULL && !list_backups && !delete_backups) {
11306 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11307 if (error)
11308 goto done;
11311 error = get_author(&committer, repo, worktree);
11312 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11313 goto done;
11315 error = apply_unveil(got_repo_get_path(repo), 0,
11316 worktree ? got_worktree_get_root_path(worktree) : NULL);
11317 if (error)
11318 goto done;
11320 if (list_backups || delete_backups) {
11321 error = process_backup_refs(
11322 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11323 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11324 goto done; /* nothing else to do */
11327 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11328 worktree);
11329 if (error)
11330 goto done;
11331 if (histedit_in_progress) {
11332 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11333 goto done;
11336 error = got_worktree_merge_in_progress(&merge_in_progress,
11337 worktree, repo);
11338 if (error)
11339 goto done;
11340 if (merge_in_progress) {
11341 error = got_error(GOT_ERR_MERGE_BUSY);
11342 goto done;
11345 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11346 if (error)
11347 goto done;
11349 if (abort_rebase) {
11350 if (!rebase_in_progress) {
11351 error = got_error(GOT_ERR_NOT_REBASING);
11352 goto done;
11354 error = got_worktree_rebase_continue(&resume_commit_id,
11355 &new_base_branch, &tmp_branch, &branch, &fileindex,
11356 worktree, repo);
11357 if (error)
11358 goto done;
11359 printf("Switching work tree to %s\n",
11360 got_ref_get_symref_target(new_base_branch));
11361 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11362 new_base_branch, abort_progress, &upa);
11363 if (error)
11364 goto done;
11365 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11366 print_merge_progress_stats(&upa);
11367 goto done; /* nothing else to do */
11370 if (continue_rebase) {
11371 if (!rebase_in_progress) {
11372 error = got_error(GOT_ERR_NOT_REBASING);
11373 goto done;
11375 error = got_worktree_rebase_continue(&resume_commit_id,
11376 &new_base_branch, &tmp_branch, &branch, &fileindex,
11377 worktree, repo);
11378 if (error)
11379 goto done;
11381 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11382 committer, resume_commit_id, allow_conflict, repo);
11383 if (error)
11384 goto done;
11386 yca_id = got_object_id_dup(resume_commit_id);
11387 if (yca_id == NULL) {
11388 error = got_error_from_errno("got_object_id_dup");
11389 goto done;
11391 } else {
11392 error = got_ref_open(&branch, repo, argv[0], 0);
11393 if (error != NULL)
11394 goto done;
11395 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11396 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11397 "will not rebase a branch which lives outside "
11398 "the \"refs/heads/\" reference namespace");
11399 goto done;
11403 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11404 if (error)
11405 goto done;
11407 if (!continue_rebase) {
11408 struct got_object_id *base_commit_id;
11410 error = got_ref_open(&head_ref, repo,
11411 got_worktree_get_head_ref_name(worktree), 0);
11412 if (error)
11413 goto done;
11414 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11415 if (error)
11416 goto done;
11417 base_commit_id = got_worktree_get_base_commit_id(worktree);
11418 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11419 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11420 goto done;
11423 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11424 base_commit_id, branch_head_commit_id, 1, repo,
11425 check_cancelled, NULL);
11426 if (error) {
11427 if (error->code == GOT_ERR_ANCESTRY) {
11428 error = got_error_msg(GOT_ERR_ANCESTRY,
11429 "specified branch shares no common "
11430 "ancestry with work tree's branch");
11432 goto done;
11435 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11436 struct got_pathlist_head paths;
11437 printf("%s is already based on %s\n",
11438 got_ref_get_name(branch),
11439 got_worktree_get_head_ref_name(worktree));
11440 error = switch_head_ref(branch, branch_head_commit_id,
11441 worktree, repo);
11442 if (error)
11443 goto done;
11444 error = got_worktree_set_base_commit_id(worktree, repo,
11445 branch_head_commit_id);
11446 if (error)
11447 goto done;
11448 TAILQ_INIT(&paths);
11449 error = got_pathlist_append(&paths, "", NULL);
11450 if (error)
11451 goto done;
11452 error = got_worktree_checkout_files(worktree,
11453 &paths, repo, update_progress, &upa,
11454 check_cancelled, NULL);
11455 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11456 if (error)
11457 goto done;
11458 if (upa.did_something) {
11459 char *id_str;
11460 error = got_object_id_str(&id_str,
11461 branch_head_commit_id);
11462 if (error)
11463 goto done;
11464 printf("Updated to %s: %s\n",
11465 got_worktree_get_head_ref_name(worktree),
11466 id_str);
11467 free(id_str);
11468 } else
11469 printf("Already up-to-date\n");
11470 print_update_progress_stats(&upa);
11471 goto done;
11475 commit_id = branch_head_commit_id;
11476 error = got_object_open_as_commit(&commit, repo, commit_id);
11477 if (error)
11478 goto done;
11480 parent_ids = got_object_commit_get_parent_ids(commit);
11481 pid = STAILQ_FIRST(parent_ids);
11482 if (pid) {
11483 error = collect_commits(&commits, commit_id, &pid->id,
11484 yca_id, got_worktree_get_path_prefix(worktree),
11485 GOT_ERR_REBASE_PATH, repo);
11486 if (error)
11487 goto done;
11490 got_object_commit_close(commit);
11491 commit = NULL;
11493 if (!continue_rebase) {
11494 error = got_worktree_rebase_prepare(&new_base_branch,
11495 &tmp_branch, &fileindex, worktree, branch, repo);
11496 if (error)
11497 goto done;
11500 if (STAILQ_EMPTY(&commits)) {
11501 if (continue_rebase) {
11502 error = rebase_complete(worktree, fileindex,
11503 branch, tmp_branch, repo, create_backup);
11504 goto done;
11505 } else {
11506 /* Fast-forward the reference of the branch. */
11507 struct got_object_id *new_head_commit_id;
11508 char *id_str;
11509 error = got_ref_resolve(&new_head_commit_id, repo,
11510 new_base_branch);
11511 if (error)
11512 goto done;
11513 error = got_object_id_str(&id_str, new_head_commit_id);
11514 if (error)
11515 goto done;
11516 printf("Forwarding %s to commit %s\n",
11517 got_ref_get_name(branch), id_str);
11518 free(id_str);
11519 error = got_ref_change_ref(branch,
11520 new_head_commit_id);
11521 if (error)
11522 goto done;
11523 /* No backup needed since objects did not change. */
11524 create_backup = 0;
11528 pid = NULL;
11529 STAILQ_FOREACH(qid, &commits, entry) {
11531 commit_id = &qid->id;
11532 parent_id = pid ? &pid->id : yca_id;
11533 pid = qid;
11535 memset(&upa, 0, sizeof(upa));
11536 error = got_worktree_rebase_merge_files(&merged_paths,
11537 worktree, fileindex, parent_id, commit_id, repo,
11538 update_progress, &upa, check_cancelled, NULL);
11539 if (error)
11540 goto done;
11542 print_merge_progress_stats(&upa);
11543 if (upa.conflicts > 0 || upa.missing > 0 ||
11544 upa.not_deleted > 0 || upa.unversioned > 0) {
11545 if (upa.conflicts > 0) {
11546 error = show_rebase_merge_conflict(&qid->id,
11547 repo);
11548 if (error)
11549 goto done;
11551 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11552 break;
11555 error = rebase_commit(&merged_paths, worktree, fileindex,
11556 tmp_branch, committer, commit_id, 0, repo);
11557 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11558 if (error)
11559 goto done;
11562 if (upa.conflicts > 0 || upa.missing > 0 ||
11563 upa.not_deleted > 0 || upa.unversioned > 0) {
11564 error = got_worktree_rebase_postpone(worktree, fileindex);
11565 if (error)
11566 goto done;
11567 if (upa.conflicts > 0 && upa.missing == 0 &&
11568 upa.not_deleted == 0 && upa.unversioned == 0) {
11569 error = got_error_msg(GOT_ERR_CONFLICTS,
11570 "conflicts must be resolved before rebasing "
11571 "can continue");
11572 } else if (upa.conflicts > 0) {
11573 error = got_error_msg(GOT_ERR_CONFLICTS,
11574 "conflicts must be resolved before rebasing "
11575 "can continue; changes destined for some "
11576 "files were not yet merged and should be "
11577 "merged manually if required before the "
11578 "rebase operation is continued");
11579 } else {
11580 error = got_error_msg(GOT_ERR_CONFLICTS,
11581 "changes destined for some files were not "
11582 "yet merged and should be merged manually "
11583 "if required before the rebase operation "
11584 "is continued");
11586 } else
11587 error = rebase_complete(worktree, fileindex, branch,
11588 tmp_branch, repo, create_backup);
11589 done:
11590 free(cwd);
11591 free(committer);
11592 free(gitconfig_path);
11593 got_object_id_queue_free(&commits);
11594 free(branch_head_commit_id);
11595 free(resume_commit_id);
11596 free(head_commit_id);
11597 free(yca_id);
11598 if (commit)
11599 got_object_commit_close(commit);
11600 if (branch)
11601 got_ref_close(branch);
11602 if (new_base_branch)
11603 got_ref_close(new_base_branch);
11604 if (tmp_branch)
11605 got_ref_close(tmp_branch);
11606 if (head_ref)
11607 got_ref_close(head_ref);
11608 if (worktree)
11609 got_worktree_close(worktree);
11610 if (repo) {
11611 const struct got_error *close_err = got_repo_close(repo);
11612 if (error == NULL)
11613 error = close_err;
11615 if (pack_fds) {
11616 const struct got_error *pack_err =
11617 got_repo_pack_fds_close(pack_fds);
11618 if (error == NULL)
11619 error = pack_err;
11621 return error;
11624 __dead static void
11625 usage_histedit(void)
11627 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11628 "[branch]\n", getprogname());
11629 exit(1);
11632 #define GOT_HISTEDIT_PICK 'p'
11633 #define GOT_HISTEDIT_EDIT 'e'
11634 #define GOT_HISTEDIT_FOLD 'f'
11635 #define GOT_HISTEDIT_DROP 'd'
11636 #define GOT_HISTEDIT_MESG 'm'
11638 static const struct got_histedit_cmd {
11639 unsigned char code;
11640 const char *name;
11641 const char *desc;
11642 } got_histedit_cmds[] = {
11643 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11644 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11645 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11646 "be used" },
11647 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11648 { GOT_HISTEDIT_MESG, "mesg",
11649 "single-line log message for commit above (open editor if empty)" },
11652 struct got_histedit_list_entry {
11653 TAILQ_ENTRY(got_histedit_list_entry) entry;
11654 struct got_object_id *commit_id;
11655 const struct got_histedit_cmd *cmd;
11656 char *logmsg;
11658 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11660 static const struct got_error *
11661 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11662 FILE *f, struct got_repository *repo)
11664 const struct got_error *err = NULL;
11665 char *logmsg = NULL, *id_str = NULL;
11666 struct got_commit_object *commit = NULL;
11667 int n;
11669 err = got_object_open_as_commit(&commit, repo, commit_id);
11670 if (err)
11671 goto done;
11673 err = get_short_logmsg(&logmsg, 34, commit);
11674 if (err)
11675 goto done;
11677 err = got_object_id_str(&id_str, commit_id);
11678 if (err)
11679 goto done;
11681 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11682 if (n < 0)
11683 err = got_ferror(f, GOT_ERR_IO);
11684 done:
11685 if (commit)
11686 got_object_commit_close(commit);
11687 free(id_str);
11688 free(logmsg);
11689 return err;
11692 static const struct got_error *
11693 histedit_write_commit_list(struct got_object_id_queue *commits,
11694 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11695 int edit_only, struct got_repository *repo)
11697 const struct got_error *err = NULL;
11698 struct got_object_qid *qid;
11699 const char *histedit_cmd = NULL;
11701 if (STAILQ_EMPTY(commits))
11702 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11704 STAILQ_FOREACH(qid, commits, entry) {
11705 histedit_cmd = got_histedit_cmds[0].name;
11706 if (drop_only)
11707 histedit_cmd = "drop";
11708 else if (edit_only)
11709 histedit_cmd = "edit";
11710 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11711 histedit_cmd = "fold";
11712 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11713 if (err)
11714 break;
11715 if (edit_logmsg_only) {
11716 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11717 if (n < 0) {
11718 err = got_ferror(f, GOT_ERR_IO);
11719 break;
11724 return err;
11727 static const struct got_error *
11728 write_cmd_list(FILE *f, const char *branch_name,
11729 struct got_object_id_queue *commits)
11731 const struct got_error *err = NULL;
11732 size_t i;
11733 int n;
11734 char *id_str;
11735 struct got_object_qid *qid;
11737 qid = STAILQ_FIRST(commits);
11738 err = got_object_id_str(&id_str, &qid->id);
11739 if (err)
11740 return err;
11742 n = fprintf(f,
11743 "# Editing the history of branch '%s' starting at\n"
11744 "# commit %s\n"
11745 "# Commits will be processed in order from top to "
11746 "bottom of this file.\n", branch_name, id_str);
11747 if (n < 0) {
11748 err = got_ferror(f, GOT_ERR_IO);
11749 goto done;
11752 n = fprintf(f, "# Available histedit commands:\n");
11753 if (n < 0) {
11754 err = got_ferror(f, GOT_ERR_IO);
11755 goto done;
11758 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11759 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11760 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11761 cmd->desc);
11762 if (n < 0) {
11763 err = got_ferror(f, GOT_ERR_IO);
11764 break;
11767 done:
11768 free(id_str);
11769 return err;
11772 static const struct got_error *
11773 histedit_syntax_error(int lineno)
11775 static char msg[42];
11776 int ret;
11778 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11779 lineno);
11780 if (ret < 0 || (size_t)ret >= sizeof(msg))
11781 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11783 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11786 static const struct got_error *
11787 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11788 char *logmsg, struct got_repository *repo)
11790 const struct got_error *err;
11791 struct got_commit_object *folded_commit = NULL;
11792 char *id_str, *folded_logmsg = NULL;
11794 err = got_object_id_str(&id_str, hle->commit_id);
11795 if (err)
11796 return err;
11798 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11799 if (err)
11800 goto done;
11802 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11803 if (err)
11804 goto done;
11805 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11806 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11807 folded_logmsg) == -1) {
11808 err = got_error_from_errno("asprintf");
11810 done:
11811 if (folded_commit)
11812 got_object_commit_close(folded_commit);
11813 free(id_str);
11814 free(folded_logmsg);
11815 return err;
11818 static struct got_histedit_list_entry *
11819 get_folded_commits(struct got_histedit_list_entry *hle)
11821 struct got_histedit_list_entry *prev, *folded = NULL;
11823 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11824 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11825 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11826 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11827 folded = prev;
11828 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11831 return folded;
11834 static const struct got_error *
11835 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11836 struct got_repository *repo)
11838 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11839 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11840 const struct got_error *err = NULL;
11841 struct got_commit_object *commit = NULL;
11842 int logmsg_len;
11843 int fd = -1;
11844 struct got_histedit_list_entry *folded = NULL;
11846 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11847 if (err)
11848 return err;
11850 folded = get_folded_commits(hle);
11851 if (folded) {
11852 while (folded != hle) {
11853 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11854 folded = TAILQ_NEXT(folded, entry);
11855 continue;
11857 err = append_folded_commit_msg(&new_msg, folded,
11858 logmsg, repo);
11859 if (err)
11860 goto done;
11861 free(logmsg);
11862 logmsg = new_msg;
11863 folded = TAILQ_NEXT(folded, entry);
11867 err = got_object_id_str(&id_str, hle->commit_id);
11868 if (err)
11869 goto done;
11870 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11871 if (err)
11872 goto done;
11873 logmsg_len = asprintf(&new_msg,
11874 "%s\n# original log message of commit %s: %s",
11875 logmsg ? logmsg : "", id_str, orig_logmsg);
11876 if (logmsg_len == -1) {
11877 err = got_error_from_errno("asprintf");
11878 goto done;
11880 free(logmsg);
11881 logmsg = new_msg;
11883 err = got_object_id_str(&id_str, hle->commit_id);
11884 if (err)
11885 goto done;
11887 err = got_opentemp_named_fd(&logmsg_path, &fd,
11888 GOT_TMPDIR_STR "/got-logmsg", "");
11889 if (err)
11890 goto done;
11892 if (write(fd, logmsg, logmsg_len) == -1) {
11893 err = got_error_from_errno2("write", logmsg_path);
11894 goto done;
11896 if (close(fd) == -1) {
11897 err = got_error_from_errno2("close", logmsg_path);
11898 goto done;
11900 fd = -1;
11902 err = get_editor(&editor);
11903 if (err)
11904 goto done;
11906 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11907 logmsg_len, 0);
11908 if (err) {
11909 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11910 goto done;
11911 err = NULL;
11912 hle->logmsg = strdup(new_msg);
11913 if (hle->logmsg == NULL)
11914 err = got_error_from_errno("strdup");
11916 done:
11917 if (fd != -1 && close(fd) == -1 && err == NULL)
11918 err = got_error_from_errno2("close", logmsg_path);
11919 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11920 err = got_error_from_errno2("unlink", logmsg_path);
11921 free(logmsg_path);
11922 free(logmsg);
11923 free(orig_logmsg);
11924 free(editor);
11925 if (commit)
11926 got_object_commit_close(commit);
11927 return err;
11930 static const struct got_error *
11931 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11932 FILE *f, struct got_repository *repo)
11934 const struct got_error *err = NULL;
11935 char *line = NULL, *p, *end;
11936 size_t i, linesize = 0;
11937 ssize_t linelen;
11938 int lineno = 0, lastcmd = -1;
11939 const struct got_histedit_cmd *cmd;
11940 struct got_object_id *commit_id = NULL;
11941 struct got_histedit_list_entry *hle = NULL;
11943 for (;;) {
11944 linelen = getline(&line, &linesize, f);
11945 if (linelen == -1) {
11946 const struct got_error *getline_err;
11947 if (feof(f))
11948 break;
11949 getline_err = got_error_from_errno("getline");
11950 err = got_ferror(f, getline_err->code);
11951 break;
11953 lineno++;
11954 p = line;
11955 while (isspace((unsigned char)p[0]))
11956 p++;
11957 if (p[0] == '#' || p[0] == '\0')
11958 continue;
11959 cmd = NULL;
11960 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11961 cmd = &got_histedit_cmds[i];
11962 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11963 isspace((unsigned char)p[strlen(cmd->name)])) {
11964 p += strlen(cmd->name);
11965 break;
11967 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11968 p++;
11969 break;
11972 if (i == nitems(got_histedit_cmds)) {
11973 err = histedit_syntax_error(lineno);
11974 break;
11976 while (isspace((unsigned char)p[0]))
11977 p++;
11978 if (cmd->code == GOT_HISTEDIT_MESG) {
11979 if (lastcmd != GOT_HISTEDIT_PICK &&
11980 lastcmd != GOT_HISTEDIT_EDIT) {
11981 err = got_error(GOT_ERR_HISTEDIT_CMD);
11982 break;
11984 if (p[0] == '\0') {
11985 err = histedit_edit_logmsg(hle, repo);
11986 if (err)
11987 break;
11988 } else {
11989 hle->logmsg = strdup(p);
11990 if (hle->logmsg == NULL) {
11991 err = got_error_from_errno("strdup");
11992 break;
11995 lastcmd = cmd->code;
11996 continue;
11997 } else {
11998 end = p;
11999 while (end[0] && !isspace((unsigned char)end[0]))
12000 end++;
12001 *end = '\0';
12003 err = got_object_resolve_id_str(&commit_id, repo, p);
12004 if (err) {
12005 /* override error code */
12006 err = histedit_syntax_error(lineno);
12007 break;
12010 hle = malloc(sizeof(*hle));
12011 if (hle == NULL) {
12012 err = got_error_from_errno("malloc");
12013 break;
12015 hle->cmd = cmd;
12016 hle->commit_id = commit_id;
12017 hle->logmsg = NULL;
12018 commit_id = NULL;
12019 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12020 lastcmd = cmd->code;
12023 free(line);
12024 free(commit_id);
12025 return err;
12028 static const struct got_error *
12029 histedit_check_script(struct got_histedit_list *histedit_cmds,
12030 struct got_object_id_queue *commits, struct got_repository *repo)
12032 const struct got_error *err = NULL;
12033 struct got_object_qid *qid;
12034 struct got_histedit_list_entry *hle;
12035 static char msg[92];
12036 char *id_str;
12038 if (TAILQ_EMPTY(histedit_cmds))
12039 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12040 "histedit script contains no commands");
12041 if (STAILQ_EMPTY(commits))
12042 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12044 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12045 struct got_histedit_list_entry *hle2;
12046 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12047 if (hle == hle2)
12048 continue;
12049 if (got_object_id_cmp(hle->commit_id,
12050 hle2->commit_id) != 0)
12051 continue;
12052 err = got_object_id_str(&id_str, hle->commit_id);
12053 if (err)
12054 return err;
12055 snprintf(msg, sizeof(msg), "commit %s is listed "
12056 "more than once in histedit script", id_str);
12057 free(id_str);
12058 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12062 STAILQ_FOREACH(qid, commits, entry) {
12063 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12064 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12065 break;
12067 if (hle == NULL) {
12068 err = got_object_id_str(&id_str, &qid->id);
12069 if (err)
12070 return err;
12071 snprintf(msg, sizeof(msg),
12072 "commit %s missing from histedit script", id_str);
12073 free(id_str);
12074 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12078 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12079 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12080 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12081 "last commit in histedit script cannot be folded");
12083 return NULL;
12086 static const struct got_error *
12087 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12088 const char *path, struct got_object_id_queue *commits,
12089 struct got_repository *repo)
12091 const struct got_error *err = NULL;
12092 struct stat st, st2;
12093 struct timespec timeout;
12094 char *editor;
12095 FILE *f = NULL;
12097 err = get_editor(&editor);
12098 if (err)
12099 return err;
12101 if (stat(path, &st) == -1) {
12102 err = got_error_from_errno2("stat", path);
12103 goto done;
12106 if (spawn_editor(editor, path) == -1) {
12107 err = got_error_from_errno("failed spawning editor");
12108 goto done;
12111 timeout.tv_sec = 0;
12112 timeout.tv_nsec = 1;
12113 nanosleep(&timeout, NULL);
12115 if (stat(path, &st2) == -1) {
12116 err = got_error_from_errno2("stat", path);
12117 goto done;
12120 if (st.st_size == st2.st_size &&
12121 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12122 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12123 "no changes made to histedit script, aborting");
12124 goto done;
12127 f = fopen(path, "re");
12128 if (f == NULL) {
12129 err = got_error_from_errno("fopen");
12130 goto done;
12132 err = histedit_parse_list(histedit_cmds, f, repo);
12133 if (err)
12134 goto done;
12136 err = histedit_check_script(histedit_cmds, commits, repo);
12137 done:
12138 if (f && fclose(f) == EOF && err == NULL)
12139 err = got_error_from_errno("fclose");
12140 free(editor);
12141 return err;
12144 static const struct got_error *
12145 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12146 struct got_object_id_queue *, const char *, const char *,
12147 struct got_repository *);
12149 static const struct got_error *
12150 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12151 struct got_object_id_queue *commits, const char *branch_name,
12152 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12153 struct got_repository *repo)
12155 const struct got_error *err;
12156 FILE *f = NULL;
12157 char *path = NULL;
12159 err = got_opentemp_named(&path, &f, "got-histedit", "");
12160 if (err)
12161 return err;
12163 err = write_cmd_list(f, branch_name, commits);
12164 if (err)
12165 goto done;
12167 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12168 fold_only, drop_only, edit_only, repo);
12169 if (err)
12170 goto done;
12172 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12173 rewind(f);
12174 err = histedit_parse_list(histedit_cmds, f, repo);
12175 } else {
12176 if (fclose(f) == EOF) {
12177 err = got_error_from_errno("fclose");
12178 goto done;
12180 f = NULL;
12181 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12182 if (err) {
12183 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12184 err->code != GOT_ERR_HISTEDIT_CMD)
12185 goto done;
12186 err = histedit_edit_list_retry(histedit_cmds, err,
12187 commits, path, branch_name, repo);
12190 done:
12191 if (f && fclose(f) == EOF && err == NULL)
12192 err = got_error_from_errno("fclose");
12193 if (path && unlink(path) != 0 && err == NULL)
12194 err = got_error_from_errno2("unlink", path);
12195 free(path);
12196 return err;
12199 static const struct got_error *
12200 histedit_save_list(struct got_histedit_list *histedit_cmds,
12201 struct got_worktree *worktree, struct got_repository *repo)
12203 const struct got_error *err = NULL;
12204 char *path = NULL;
12205 FILE *f = NULL;
12206 struct got_histedit_list_entry *hle;
12208 err = got_worktree_get_histedit_script_path(&path, worktree);
12209 if (err)
12210 return err;
12212 f = fopen(path, "we");
12213 if (f == NULL) {
12214 err = got_error_from_errno2("fopen", path);
12215 goto done;
12217 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12218 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12219 repo);
12220 if (err)
12221 break;
12223 if (hle->logmsg) {
12224 int n = fprintf(f, "%c %s\n",
12225 GOT_HISTEDIT_MESG, hle->logmsg);
12226 if (n < 0) {
12227 err = got_ferror(f, GOT_ERR_IO);
12228 break;
12232 done:
12233 if (f && fclose(f) == EOF && err == NULL)
12234 err = got_error_from_errno("fclose");
12235 free(path);
12236 return err;
12239 static void
12240 histedit_free_list(struct got_histedit_list *histedit_cmds)
12242 struct got_histedit_list_entry *hle;
12244 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12245 TAILQ_REMOVE(histedit_cmds, hle, entry);
12246 free(hle);
12250 static const struct got_error *
12251 histedit_load_list(struct got_histedit_list *histedit_cmds,
12252 const char *path, struct got_repository *repo)
12254 const struct got_error *err = NULL;
12255 FILE *f = NULL;
12257 f = fopen(path, "re");
12258 if (f == NULL) {
12259 err = got_error_from_errno2("fopen", path);
12260 goto done;
12263 err = histedit_parse_list(histedit_cmds, f, repo);
12264 done:
12265 if (f && fclose(f) == EOF && err == NULL)
12266 err = got_error_from_errno("fclose");
12267 return err;
12270 static const struct got_error *
12271 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12272 const struct got_error *edit_err, struct got_object_id_queue *commits,
12273 const char *path, const char *branch_name, struct got_repository *repo)
12275 const struct got_error *err = NULL, *prev_err = edit_err;
12276 int resp = ' ';
12278 while (resp != 'c' && resp != 'r' && resp != 'a') {
12279 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12280 "or (a)bort: ", getprogname(), prev_err->msg);
12281 resp = getchar();
12282 if (resp == '\n')
12283 resp = getchar();
12284 if (resp == 'c') {
12285 histedit_free_list(histedit_cmds);
12286 err = histedit_run_editor(histedit_cmds, path, commits,
12287 repo);
12288 if (err) {
12289 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12290 err->code != GOT_ERR_HISTEDIT_CMD)
12291 break;
12292 prev_err = err;
12293 resp = ' ';
12294 continue;
12296 break;
12297 } else if (resp == 'r') {
12298 histedit_free_list(histedit_cmds);
12299 err = histedit_edit_script(histedit_cmds,
12300 commits, branch_name, 0, 0, 0, 0, repo);
12301 if (err) {
12302 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12303 err->code != GOT_ERR_HISTEDIT_CMD)
12304 break;
12305 prev_err = err;
12306 resp = ' ';
12307 continue;
12309 break;
12310 } else if (resp == 'a') {
12311 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12312 break;
12313 } else
12314 printf("invalid response '%c'\n", resp);
12317 return err;
12320 static const struct got_error *
12321 histedit_complete(struct got_worktree *worktree,
12322 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12323 struct got_reference *branch, struct got_repository *repo)
12325 printf("Switching work tree to %s\n",
12326 got_ref_get_symref_target(branch));
12327 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12328 branch, repo);
12331 static const struct got_error *
12332 show_histedit_progress(struct got_commit_object *commit,
12333 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12335 const struct got_error *err;
12336 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12338 err = got_object_id_str(&old_id_str, hle->commit_id);
12339 if (err)
12340 goto done;
12342 if (new_id) {
12343 err = got_object_id_str(&new_id_str, new_id);
12344 if (err)
12345 goto done;
12348 old_id_str[12] = '\0';
12349 if (new_id_str)
12350 new_id_str[12] = '\0';
12352 if (hle->logmsg) {
12353 logmsg = strdup(hle->logmsg);
12354 if (logmsg == NULL) {
12355 err = got_error_from_errno("strdup");
12356 goto done;
12358 trim_logmsg(logmsg, 42);
12359 } else {
12360 err = get_short_logmsg(&logmsg, 42, commit);
12361 if (err)
12362 goto done;
12365 switch (hle->cmd->code) {
12366 case GOT_HISTEDIT_PICK:
12367 case GOT_HISTEDIT_EDIT:
12368 printf("%s -> %s: %s\n", old_id_str,
12369 new_id_str ? new_id_str : "no-op change", logmsg);
12370 break;
12371 case GOT_HISTEDIT_DROP:
12372 case GOT_HISTEDIT_FOLD:
12373 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12374 logmsg);
12375 break;
12376 default:
12377 break;
12379 done:
12380 free(old_id_str);
12381 free(new_id_str);
12382 return err;
12385 static const struct got_error *
12386 histedit_commit(struct got_pathlist_head *merged_paths,
12387 struct got_worktree *worktree, struct got_fileindex *fileindex,
12388 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12389 const char *committer, int allow_conflict, struct got_repository *repo)
12391 const struct got_error *err;
12392 struct got_commit_object *commit;
12393 struct got_object_id *new_commit_id;
12395 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12396 && hle->logmsg == NULL) {
12397 err = histedit_edit_logmsg(hle, repo);
12398 if (err)
12399 return err;
12402 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12403 if (err)
12404 return err;
12406 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12407 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12408 hle->logmsg, allow_conflict, repo);
12409 if (err) {
12410 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12411 goto done;
12412 err = show_histedit_progress(commit, hle, NULL);
12413 } else {
12414 err = show_histedit_progress(commit, hle, new_commit_id);
12415 free(new_commit_id);
12417 done:
12418 got_object_commit_close(commit);
12419 return err;
12422 static const struct got_error *
12423 histedit_skip_commit(struct got_histedit_list_entry *hle,
12424 struct got_worktree *worktree, struct got_repository *repo)
12426 const struct got_error *error;
12427 struct got_commit_object *commit;
12429 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12430 repo);
12431 if (error)
12432 return error;
12434 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12435 if (error)
12436 return error;
12438 error = show_histedit_progress(commit, hle, NULL);
12439 got_object_commit_close(commit);
12440 return error;
12443 static const struct got_error *
12444 check_local_changes(void *arg, unsigned char status,
12445 unsigned char staged_status, const char *path,
12446 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12447 struct got_object_id *commit_id, int dirfd, const char *de_name)
12449 int *have_local_changes = arg;
12451 switch (status) {
12452 case GOT_STATUS_ADD:
12453 case GOT_STATUS_DELETE:
12454 case GOT_STATUS_MODIFY:
12455 case GOT_STATUS_CONFLICT:
12456 *have_local_changes = 1;
12457 return got_error(GOT_ERR_CANCELLED);
12458 default:
12459 break;
12462 switch (staged_status) {
12463 case GOT_STATUS_ADD:
12464 case GOT_STATUS_DELETE:
12465 case GOT_STATUS_MODIFY:
12466 *have_local_changes = 1;
12467 return got_error(GOT_ERR_CANCELLED);
12468 default:
12469 break;
12472 return NULL;
12475 static const struct got_error *
12476 cmd_histedit(int argc, char *argv[])
12478 const struct got_error *error = NULL;
12479 struct got_worktree *worktree = NULL;
12480 struct got_fileindex *fileindex = NULL;
12481 struct got_repository *repo = NULL;
12482 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12483 struct got_reference *branch = NULL;
12484 struct got_reference *tmp_branch = NULL;
12485 struct got_object_id *resume_commit_id = NULL;
12486 struct got_object_id *base_commit_id = NULL;
12487 struct got_object_id *head_commit_id = NULL;
12488 struct got_commit_object *commit = NULL;
12489 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12490 struct got_update_progress_arg upa;
12491 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12492 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12493 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12494 const char *edit_script_path = NULL;
12495 struct got_object_id_queue commits;
12496 struct got_pathlist_head merged_paths;
12497 const struct got_object_id_queue *parent_ids;
12498 struct got_object_qid *pid;
12499 struct got_histedit_list histedit_cmds;
12500 struct got_histedit_list_entry *hle;
12501 int *pack_fds = NULL;
12503 STAILQ_INIT(&commits);
12504 TAILQ_INIT(&histedit_cmds);
12505 TAILQ_INIT(&merged_paths);
12506 memset(&upa, 0, sizeof(upa));
12508 #ifndef PROFILE
12509 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12510 "unveil", NULL) == -1)
12511 err(1, "pledge");
12512 #endif
12514 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12515 switch (ch) {
12516 case 'a':
12517 abort_edit = 1;
12518 break;
12519 case 'C':
12520 allow_conflict = 1;
12521 break;
12522 case 'c':
12523 continue_edit = 1;
12524 break;
12525 case 'd':
12526 drop_only = 1;
12527 break;
12528 case 'e':
12529 edit_only = 1;
12530 break;
12531 case 'F':
12532 edit_script_path = optarg;
12533 break;
12534 case 'f':
12535 fold_only = 1;
12536 break;
12537 case 'l':
12538 list_backups = 1;
12539 break;
12540 case 'm':
12541 edit_logmsg_only = 1;
12542 break;
12543 case 'X':
12544 delete_backups = 1;
12545 break;
12546 default:
12547 usage_histedit();
12548 /* NOTREACHED */
12552 argc -= optind;
12553 argv += optind;
12555 if (abort_edit && allow_conflict)
12556 option_conflict('a', 'C');
12557 if (abort_edit && continue_edit)
12558 option_conflict('a', 'c');
12559 if (edit_script_path && allow_conflict)
12560 option_conflict('F', 'C');
12561 if (edit_script_path && edit_logmsg_only)
12562 option_conflict('F', 'm');
12563 if (abort_edit && edit_logmsg_only)
12564 option_conflict('a', 'm');
12565 if (edit_logmsg_only && allow_conflict)
12566 option_conflict('m', 'C');
12567 if (continue_edit && edit_logmsg_only)
12568 option_conflict('c', 'm');
12569 if (abort_edit && fold_only)
12570 option_conflict('a', 'f');
12571 if (fold_only && allow_conflict)
12572 option_conflict('f', 'C');
12573 if (continue_edit && fold_only)
12574 option_conflict('c', 'f');
12575 if (fold_only && edit_logmsg_only)
12576 option_conflict('f', 'm');
12577 if (edit_script_path && fold_only)
12578 option_conflict('F', 'f');
12579 if (abort_edit && edit_only)
12580 option_conflict('a', 'e');
12581 if (continue_edit && edit_only)
12582 option_conflict('c', 'e');
12583 if (edit_only && edit_logmsg_only)
12584 option_conflict('e', 'm');
12585 if (edit_script_path && edit_only)
12586 option_conflict('F', 'e');
12587 if (fold_only && edit_only)
12588 option_conflict('f', 'e');
12589 if (drop_only && abort_edit)
12590 option_conflict('d', 'a');
12591 if (drop_only && allow_conflict)
12592 option_conflict('d', 'C');
12593 if (drop_only && continue_edit)
12594 option_conflict('d', 'c');
12595 if (drop_only && edit_logmsg_only)
12596 option_conflict('d', 'm');
12597 if (drop_only && edit_only)
12598 option_conflict('d', 'e');
12599 if (drop_only && edit_script_path)
12600 option_conflict('d', 'F');
12601 if (drop_only && fold_only)
12602 option_conflict('d', 'f');
12603 if (list_backups) {
12604 if (abort_edit)
12605 option_conflict('l', 'a');
12606 if (allow_conflict)
12607 option_conflict('l', 'C');
12608 if (continue_edit)
12609 option_conflict('l', 'c');
12610 if (edit_script_path)
12611 option_conflict('l', 'F');
12612 if (edit_logmsg_only)
12613 option_conflict('l', 'm');
12614 if (drop_only)
12615 option_conflict('l', 'd');
12616 if (fold_only)
12617 option_conflict('l', 'f');
12618 if (edit_only)
12619 option_conflict('l', 'e');
12620 if (delete_backups)
12621 option_conflict('l', 'X');
12622 if (argc != 0 && argc != 1)
12623 usage_histedit();
12624 } else if (delete_backups) {
12625 if (abort_edit)
12626 option_conflict('X', 'a');
12627 if (allow_conflict)
12628 option_conflict('X', 'C');
12629 if (continue_edit)
12630 option_conflict('X', 'c');
12631 if (drop_only)
12632 option_conflict('X', 'd');
12633 if (edit_script_path)
12634 option_conflict('X', 'F');
12635 if (edit_logmsg_only)
12636 option_conflict('X', 'm');
12637 if (fold_only)
12638 option_conflict('X', 'f');
12639 if (edit_only)
12640 option_conflict('X', 'e');
12641 if (list_backups)
12642 option_conflict('X', 'l');
12643 if (argc != 0 && argc != 1)
12644 usage_histedit();
12645 } else if (allow_conflict && !continue_edit)
12646 errx(1, "-C option requires -c");
12647 else if (argc != 0)
12648 usage_histedit();
12651 * This command cannot apply unveil(2) in all cases because the
12652 * user may choose to run an editor to edit the histedit script
12653 * and to edit individual commit log messages.
12654 * unveil(2) traverses exec(2); if an editor is used we have to
12655 * apply unveil after edit script and log messages have been written.
12656 * XXX TODO: Make use of unveil(2) where possible.
12659 cwd = getcwd(NULL, 0);
12660 if (cwd == NULL) {
12661 error = got_error_from_errno("getcwd");
12662 goto done;
12665 error = got_repo_pack_fds_open(&pack_fds);
12666 if (error != NULL)
12667 goto done;
12669 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12670 if (error) {
12671 if (list_backups || delete_backups) {
12672 if (error->code != GOT_ERR_NOT_WORKTREE)
12673 goto done;
12674 } else {
12675 if (error->code == GOT_ERR_NOT_WORKTREE)
12676 error = wrap_not_worktree_error(error,
12677 "histedit", cwd);
12678 goto done;
12682 if (list_backups || delete_backups) {
12683 error = got_repo_open(&repo,
12684 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12685 NULL, pack_fds);
12686 if (error != NULL)
12687 goto done;
12688 error = apply_unveil(got_repo_get_path(repo), 0,
12689 worktree ? got_worktree_get_root_path(worktree) : NULL);
12690 if (error)
12691 goto done;
12692 error = process_backup_refs(
12693 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12694 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12695 goto done; /* nothing else to do */
12698 error = get_gitconfig_path(&gitconfig_path);
12699 if (error)
12700 goto done;
12701 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12702 gitconfig_path, pack_fds);
12703 if (error != NULL)
12704 goto done;
12706 if (worktree != NULL && !list_backups && !delete_backups) {
12707 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12708 if (error)
12709 goto done;
12712 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12713 if (error)
12714 goto done;
12715 if (rebase_in_progress) {
12716 error = got_error(GOT_ERR_REBASING);
12717 goto done;
12720 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12721 repo);
12722 if (error)
12723 goto done;
12724 if (merge_in_progress) {
12725 error = got_error(GOT_ERR_MERGE_BUSY);
12726 goto done;
12729 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12730 if (error)
12731 goto done;
12733 if (edit_in_progress && edit_logmsg_only) {
12734 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12735 "histedit operation is in progress in this "
12736 "work tree and must be continued or aborted "
12737 "before the -m option can be used");
12738 goto done;
12740 if (edit_in_progress && drop_only) {
12741 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12742 "histedit operation is in progress in this "
12743 "work tree and must be continued or aborted "
12744 "before the -d option can be used");
12745 goto done;
12747 if (edit_in_progress && fold_only) {
12748 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12749 "histedit operation is in progress in this "
12750 "work tree and must be continued or aborted "
12751 "before the -f option can be used");
12752 goto done;
12754 if (edit_in_progress && edit_only) {
12755 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12756 "histedit operation is in progress in this "
12757 "work tree and must be continued or aborted "
12758 "before the -e option can be used");
12759 goto done;
12762 if (edit_in_progress && abort_edit) {
12763 error = got_worktree_histedit_continue(&resume_commit_id,
12764 &tmp_branch, &branch, &base_commit_id, &fileindex,
12765 worktree, repo);
12766 if (error)
12767 goto done;
12768 printf("Switching work tree to %s\n",
12769 got_ref_get_symref_target(branch));
12770 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12771 branch, base_commit_id, abort_progress, &upa);
12772 if (error)
12773 goto done;
12774 printf("Histedit of %s aborted\n",
12775 got_ref_get_symref_target(branch));
12776 print_merge_progress_stats(&upa);
12777 goto done; /* nothing else to do */
12778 } else if (abort_edit) {
12779 error = got_error(GOT_ERR_NOT_HISTEDIT);
12780 goto done;
12783 error = get_author(&committer, repo, worktree);
12784 if (error)
12785 goto done;
12787 if (continue_edit) {
12788 char *path;
12790 if (!edit_in_progress) {
12791 error = got_error(GOT_ERR_NOT_HISTEDIT);
12792 goto done;
12795 error = got_worktree_get_histedit_script_path(&path, worktree);
12796 if (error)
12797 goto done;
12799 error = histedit_load_list(&histedit_cmds, path, repo);
12800 free(path);
12801 if (error)
12802 goto done;
12804 error = got_worktree_histedit_continue(&resume_commit_id,
12805 &tmp_branch, &branch, &base_commit_id, &fileindex,
12806 worktree, repo);
12807 if (error)
12808 goto done;
12810 error = got_ref_resolve(&head_commit_id, repo, branch);
12811 if (error)
12812 goto done;
12814 error = got_object_open_as_commit(&commit, repo,
12815 head_commit_id);
12816 if (error)
12817 goto done;
12818 parent_ids = got_object_commit_get_parent_ids(commit);
12819 pid = STAILQ_FIRST(parent_ids);
12820 if (pid == NULL) {
12821 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12822 goto done;
12824 error = collect_commits(&commits, head_commit_id, &pid->id,
12825 base_commit_id, got_worktree_get_path_prefix(worktree),
12826 GOT_ERR_HISTEDIT_PATH, repo);
12827 got_object_commit_close(commit);
12828 commit = NULL;
12829 if (error)
12830 goto done;
12831 } else {
12832 if (edit_in_progress) {
12833 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12834 goto done;
12837 error = got_ref_open(&branch, repo,
12838 got_worktree_get_head_ref_name(worktree), 0);
12839 if (error != NULL)
12840 goto done;
12842 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12843 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12844 "will not edit commit history of a branch outside "
12845 "the \"refs/heads/\" reference namespace");
12846 goto done;
12849 error = got_ref_resolve(&head_commit_id, repo, branch);
12850 got_ref_close(branch);
12851 branch = NULL;
12852 if (error)
12853 goto done;
12855 error = got_object_open_as_commit(&commit, repo,
12856 head_commit_id);
12857 if (error)
12858 goto done;
12859 parent_ids = got_object_commit_get_parent_ids(commit);
12860 pid = STAILQ_FIRST(parent_ids);
12861 if (pid == NULL) {
12862 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12863 goto done;
12865 error = collect_commits(&commits, head_commit_id, &pid->id,
12866 got_worktree_get_base_commit_id(worktree),
12867 got_worktree_get_path_prefix(worktree),
12868 GOT_ERR_HISTEDIT_PATH, repo);
12869 got_object_commit_close(commit);
12870 commit = NULL;
12871 if (error)
12872 goto done;
12874 if (STAILQ_EMPTY(&commits)) {
12875 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12876 goto done;
12879 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12880 &base_commit_id, &fileindex, worktree, repo);
12881 if (error)
12882 goto done;
12884 if (edit_script_path) {
12885 error = histedit_load_list(&histedit_cmds,
12886 edit_script_path, repo);
12887 if (error) {
12888 got_worktree_histedit_abort(worktree, fileindex,
12889 repo, branch, base_commit_id,
12890 abort_progress, &upa);
12891 print_merge_progress_stats(&upa);
12892 goto done;
12894 } else {
12895 const char *branch_name;
12896 branch_name = got_ref_get_symref_target(branch);
12897 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12898 branch_name += 11;
12899 error = histedit_edit_script(&histedit_cmds, &commits,
12900 branch_name, edit_logmsg_only, fold_only,
12901 drop_only, edit_only, repo);
12902 if (error) {
12903 got_worktree_histedit_abort(worktree, fileindex,
12904 repo, branch, base_commit_id,
12905 abort_progress, &upa);
12906 print_merge_progress_stats(&upa);
12907 goto done;
12912 error = histedit_save_list(&histedit_cmds, worktree,
12913 repo);
12914 if (error) {
12915 got_worktree_histedit_abort(worktree, fileindex,
12916 repo, branch, base_commit_id,
12917 abort_progress, &upa);
12918 print_merge_progress_stats(&upa);
12919 goto done;
12924 error = histedit_check_script(&histedit_cmds, &commits, repo);
12925 if (error)
12926 goto done;
12928 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12929 if (resume_commit_id) {
12930 if (got_object_id_cmp(hle->commit_id,
12931 resume_commit_id) != 0)
12932 continue;
12934 resume_commit_id = NULL;
12935 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12936 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12937 error = histedit_skip_commit(hle, worktree,
12938 repo);
12939 if (error)
12940 goto done;
12941 } else {
12942 struct got_pathlist_head paths;
12943 int have_changes = 0;
12945 TAILQ_INIT(&paths);
12946 error = got_pathlist_append(&paths, "", NULL);
12947 if (error)
12948 goto done;
12949 error = got_worktree_status(worktree, &paths,
12950 repo, 0, check_local_changes, &have_changes,
12951 check_cancelled, NULL);
12952 got_pathlist_free(&paths,
12953 GOT_PATHLIST_FREE_NONE);
12954 if (error) {
12955 if (error->code != GOT_ERR_CANCELLED)
12956 goto done;
12957 if (sigint_received || sigpipe_received)
12958 goto done;
12960 if (have_changes) {
12961 error = histedit_commit(NULL, worktree,
12962 fileindex, tmp_branch, hle,
12963 committer, allow_conflict, repo);
12964 if (error)
12965 goto done;
12966 } else {
12967 error = got_object_open_as_commit(
12968 &commit, repo, hle->commit_id);
12969 if (error)
12970 goto done;
12971 error = show_histedit_progress(commit,
12972 hle, NULL);
12973 got_object_commit_close(commit);
12974 commit = NULL;
12975 if (error)
12976 goto done;
12979 continue;
12982 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12983 error = histedit_skip_commit(hle, worktree, repo);
12984 if (error)
12985 goto done;
12986 continue;
12989 error = got_object_open_as_commit(&commit, repo,
12990 hle->commit_id);
12991 if (error)
12992 goto done;
12993 parent_ids = got_object_commit_get_parent_ids(commit);
12994 pid = STAILQ_FIRST(parent_ids);
12996 error = got_worktree_histedit_merge_files(&merged_paths,
12997 worktree, fileindex, &pid->id, hle->commit_id, repo,
12998 update_progress, &upa, check_cancelled, NULL);
12999 if (error)
13000 goto done;
13001 got_object_commit_close(commit);
13002 commit = NULL;
13004 print_merge_progress_stats(&upa);
13005 if (upa.conflicts > 0 || upa.missing > 0 ||
13006 upa.not_deleted > 0 || upa.unversioned > 0) {
13007 if (upa.conflicts > 0) {
13008 error = show_rebase_merge_conflict(
13009 hle->commit_id, repo);
13010 if (error)
13011 goto done;
13013 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13014 break;
13017 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13018 char *id_str;
13019 error = got_object_id_str(&id_str, hle->commit_id);
13020 if (error)
13021 goto done;
13022 printf("Stopping histedit for amending commit %s\n",
13023 id_str);
13024 free(id_str);
13025 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13026 error = got_worktree_histedit_postpone(worktree,
13027 fileindex);
13028 goto done;
13031 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13032 error = histedit_skip_commit(hle, worktree, repo);
13033 if (error)
13034 goto done;
13035 continue;
13038 error = histedit_commit(&merged_paths, worktree, fileindex,
13039 tmp_branch, hle, committer, allow_conflict, repo);
13040 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13041 if (error)
13042 goto done;
13045 if (upa.conflicts > 0 || upa.missing > 0 ||
13046 upa.not_deleted > 0 || upa.unversioned > 0) {
13047 error = got_worktree_histedit_postpone(worktree, fileindex);
13048 if (error)
13049 goto done;
13050 if (upa.conflicts > 0 && upa.missing == 0 &&
13051 upa.not_deleted == 0 && upa.unversioned == 0) {
13052 error = got_error_msg(GOT_ERR_CONFLICTS,
13053 "conflicts must be resolved before histedit "
13054 "can continue");
13055 } else if (upa.conflicts > 0) {
13056 error = got_error_msg(GOT_ERR_CONFLICTS,
13057 "conflicts must be resolved before histedit "
13058 "can continue; changes destined for some "
13059 "files were not yet merged and should be "
13060 "merged manually if required before the "
13061 "histedit operation is continued");
13062 } else {
13063 error = got_error_msg(GOT_ERR_CONFLICTS,
13064 "changes destined for some files were not "
13065 "yet merged and should be merged manually "
13066 "if required before the histedit operation "
13067 "is continued");
13069 } else
13070 error = histedit_complete(worktree, fileindex, tmp_branch,
13071 branch, repo);
13072 done:
13073 free(cwd);
13074 free(committer);
13075 free(gitconfig_path);
13076 got_object_id_queue_free(&commits);
13077 histedit_free_list(&histedit_cmds);
13078 free(head_commit_id);
13079 free(base_commit_id);
13080 free(resume_commit_id);
13081 if (commit)
13082 got_object_commit_close(commit);
13083 if (branch)
13084 got_ref_close(branch);
13085 if (tmp_branch)
13086 got_ref_close(tmp_branch);
13087 if (worktree)
13088 got_worktree_close(worktree);
13089 if (repo) {
13090 const struct got_error *close_err = got_repo_close(repo);
13091 if (error == NULL)
13092 error = close_err;
13094 if (pack_fds) {
13095 const struct got_error *pack_err =
13096 got_repo_pack_fds_close(pack_fds);
13097 if (error == NULL)
13098 error = pack_err;
13100 return error;
13103 __dead static void
13104 usage_integrate(void)
13106 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13107 exit(1);
13110 static const struct got_error *
13111 cmd_integrate(int argc, char *argv[])
13113 const struct got_error *error = NULL;
13114 struct got_repository *repo = NULL;
13115 struct got_worktree *worktree = NULL;
13116 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13117 const char *branch_arg = NULL;
13118 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13119 struct got_fileindex *fileindex = NULL;
13120 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13121 int ch;
13122 struct got_update_progress_arg upa;
13123 int *pack_fds = NULL;
13125 #ifndef PROFILE
13126 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13127 "unveil", NULL) == -1)
13128 err(1, "pledge");
13129 #endif
13131 while ((ch = getopt(argc, argv, "")) != -1) {
13132 switch (ch) {
13133 default:
13134 usage_integrate();
13135 /* NOTREACHED */
13139 argc -= optind;
13140 argv += optind;
13142 if (argc != 1)
13143 usage_integrate();
13144 branch_arg = argv[0];
13146 cwd = getcwd(NULL, 0);
13147 if (cwd == NULL) {
13148 error = got_error_from_errno("getcwd");
13149 goto done;
13152 error = got_repo_pack_fds_open(&pack_fds);
13153 if (error != NULL)
13154 goto done;
13156 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13157 if (error) {
13158 if (error->code == GOT_ERR_NOT_WORKTREE)
13159 error = wrap_not_worktree_error(error, "integrate",
13160 cwd);
13161 goto done;
13164 error = check_rebase_or_histedit_in_progress(worktree);
13165 if (error)
13166 goto done;
13168 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13169 NULL, pack_fds);
13170 if (error != NULL)
13171 goto done;
13173 error = apply_unveil(got_repo_get_path(repo), 0,
13174 got_worktree_get_root_path(worktree));
13175 if (error)
13176 goto done;
13178 error = check_merge_in_progress(worktree, repo);
13179 if (error)
13180 goto done;
13182 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13183 error = got_error_from_errno("asprintf");
13184 goto done;
13187 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13188 &base_branch_ref, worktree, refname, repo);
13189 if (error)
13190 goto done;
13192 refname = strdup(got_ref_get_name(branch_ref));
13193 if (refname == NULL) {
13194 error = got_error_from_errno("strdup");
13195 got_worktree_integrate_abort(worktree, fileindex, repo,
13196 branch_ref, base_branch_ref);
13197 goto done;
13199 base_refname = strdup(got_ref_get_name(base_branch_ref));
13200 if (base_refname == NULL) {
13201 error = got_error_from_errno("strdup");
13202 got_worktree_integrate_abort(worktree, fileindex, repo,
13203 branch_ref, base_branch_ref);
13204 goto done;
13206 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13207 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13208 got_worktree_integrate_abort(worktree, fileindex, repo,
13209 branch_ref, base_branch_ref);
13210 goto done;
13213 error = got_ref_resolve(&commit_id, repo, branch_ref);
13214 if (error)
13215 goto done;
13217 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13218 if (error)
13219 goto done;
13221 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13222 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13223 "specified branch has already been integrated");
13224 got_worktree_integrate_abort(worktree, fileindex, repo,
13225 branch_ref, base_branch_ref);
13226 goto done;
13229 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13230 if (error) {
13231 if (error->code == GOT_ERR_ANCESTRY)
13232 error = got_error(GOT_ERR_REBASE_REQUIRED);
13233 got_worktree_integrate_abort(worktree, fileindex, repo,
13234 branch_ref, base_branch_ref);
13235 goto done;
13238 memset(&upa, 0, sizeof(upa));
13239 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13240 branch_ref, base_branch_ref, update_progress, &upa,
13241 check_cancelled, NULL);
13242 if (error)
13243 goto done;
13245 printf("Integrated %s into %s\n", refname, base_refname);
13246 print_update_progress_stats(&upa);
13247 done:
13248 if (repo) {
13249 const struct got_error *close_err = got_repo_close(repo);
13250 if (error == NULL)
13251 error = close_err;
13253 if (worktree)
13254 got_worktree_close(worktree);
13255 if (pack_fds) {
13256 const struct got_error *pack_err =
13257 got_repo_pack_fds_close(pack_fds);
13258 if (error == NULL)
13259 error = pack_err;
13261 free(cwd);
13262 free(base_commit_id);
13263 free(commit_id);
13264 free(refname);
13265 free(base_refname);
13266 return error;
13269 __dead static void
13270 usage_merge(void)
13272 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13273 exit(1);
13276 static const struct got_error *
13277 cmd_merge(int argc, char *argv[])
13279 const struct got_error *error = NULL;
13280 struct got_worktree *worktree = NULL;
13281 struct got_repository *repo = NULL;
13282 struct got_fileindex *fileindex = NULL;
13283 char *cwd = NULL, *id_str = NULL, *author = NULL;
13284 char *gitconfig_path = NULL;
13285 struct got_reference *branch = NULL, *wt_branch = NULL;
13286 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13287 struct got_object_id *wt_branch_tip = NULL;
13288 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13289 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13290 struct got_update_progress_arg upa;
13291 struct got_object_id *merge_commit_id = NULL;
13292 char *branch_name = NULL;
13293 int *pack_fds = NULL;
13295 memset(&upa, 0, sizeof(upa));
13297 #ifndef PROFILE
13298 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13299 "unveil", NULL) == -1)
13300 err(1, "pledge");
13301 #endif
13303 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13304 switch (ch) {
13305 case 'a':
13306 abort_merge = 1;
13307 break;
13308 case 'C':
13309 allow_conflict = 1;
13310 break;
13311 case 'c':
13312 continue_merge = 1;
13313 break;
13314 case 'M':
13315 prefer_fast_forward = 0;
13316 break;
13317 case 'n':
13318 interrupt_merge = 1;
13319 break;
13320 default:
13321 usage_merge();
13322 /* NOTREACHED */
13326 argc -= optind;
13327 argv += optind;
13329 if (abort_merge) {
13330 if (continue_merge)
13331 option_conflict('a', 'c');
13332 if (!prefer_fast_forward)
13333 option_conflict('a', 'M');
13334 if (interrupt_merge)
13335 option_conflict('a', 'n');
13336 } else if (continue_merge) {
13337 if (!prefer_fast_forward)
13338 option_conflict('c', 'M');
13339 if (interrupt_merge)
13340 option_conflict('c', 'n');
13342 if (allow_conflict) {
13343 if (!continue_merge)
13344 errx(1, "-C option requires -c");
13346 if (abort_merge || continue_merge) {
13347 if (argc != 0)
13348 usage_merge();
13349 } else if (argc != 1)
13350 usage_merge();
13352 cwd = getcwd(NULL, 0);
13353 if (cwd == NULL) {
13354 error = got_error_from_errno("getcwd");
13355 goto done;
13358 error = got_repo_pack_fds_open(&pack_fds);
13359 if (error != NULL)
13360 goto done;
13362 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13363 if (error) {
13364 if (error->code == GOT_ERR_NOT_WORKTREE)
13365 error = wrap_not_worktree_error(error,
13366 "merge", cwd);
13367 goto done;
13370 error = get_gitconfig_path(&gitconfig_path);
13371 if (error)
13372 goto done;
13373 error = got_repo_open(&repo,
13374 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13375 gitconfig_path, pack_fds);
13376 if (error != NULL)
13377 goto done;
13379 if (worktree != NULL) {
13380 error = worktree_has_logmsg_ref("merge", worktree, repo);
13381 if (error)
13382 goto done;
13385 error = apply_unveil(got_repo_get_path(repo), 0,
13386 worktree ? got_worktree_get_root_path(worktree) : NULL);
13387 if (error)
13388 goto done;
13390 error = check_rebase_or_histedit_in_progress(worktree);
13391 if (error)
13392 goto done;
13394 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13395 repo);
13396 if (error)
13397 goto done;
13399 if (merge_in_progress && !(abort_merge || continue_merge)) {
13400 error = got_error(GOT_ERR_MERGE_BUSY);
13401 goto done;
13404 if (!merge_in_progress && (abort_merge || continue_merge)) {
13405 error = got_error(GOT_ERR_NOT_MERGING);
13406 goto done;
13409 if (abort_merge) {
13410 error = got_worktree_merge_continue(&branch_name,
13411 &branch_tip, &fileindex, worktree, repo);
13412 if (error)
13413 goto done;
13414 error = got_worktree_merge_abort(worktree, fileindex, repo,
13415 abort_progress, &upa);
13416 if (error)
13417 goto done;
13418 printf("Merge of %s aborted\n", branch_name);
13419 goto done; /* nothing else to do */
13422 if (strncmp(got_worktree_get_head_ref_name(worktree),
13423 "refs/heads/", 11) != 0) {
13424 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13425 "work tree's current branch %s is outside the "
13426 "\"refs/heads/\" reference namespace; "
13427 "update -b required",
13428 got_worktree_get_head_ref_name(worktree));
13429 goto done;
13432 error = get_author(&author, repo, worktree);
13433 if (error)
13434 goto done;
13436 error = got_ref_open(&wt_branch, repo,
13437 got_worktree_get_head_ref_name(worktree), 0);
13438 if (error)
13439 goto done;
13440 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13441 if (error)
13442 goto done;
13444 if (continue_merge) {
13445 struct got_object_id *base_commit_id;
13446 base_commit_id = got_worktree_get_base_commit_id(worktree);
13447 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13448 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13449 goto done;
13451 error = got_worktree_merge_continue(&branch_name,
13452 &branch_tip, &fileindex, worktree, repo);
13453 if (error)
13454 goto done;
13455 } else {
13456 error = got_ref_open(&branch, repo, argv[0], 0);
13457 if (error != NULL)
13458 goto done;
13459 branch_name = strdup(got_ref_get_name(branch));
13460 if (branch_name == NULL) {
13461 error = got_error_from_errno("strdup");
13462 goto done;
13464 error = got_ref_resolve(&branch_tip, repo, branch);
13465 if (error)
13466 goto done;
13469 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13470 wt_branch_tip, branch_tip, 0, repo,
13471 check_cancelled, NULL);
13472 if (error && error->code != GOT_ERR_ANCESTRY)
13473 goto done;
13475 if (!continue_merge) {
13476 error = check_path_prefix(wt_branch_tip, branch_tip,
13477 got_worktree_get_path_prefix(worktree),
13478 GOT_ERR_MERGE_PATH, repo);
13479 if (error)
13480 goto done;
13481 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13482 if (error)
13483 goto done;
13484 if (prefer_fast_forward && yca_id &&
13485 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13486 struct got_pathlist_head paths;
13487 if (interrupt_merge) {
13488 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13489 "there are no changes to merge since %s "
13490 "is already based on %s; merge cannot be "
13491 "interrupted for amending; -n",
13492 branch_name, got_ref_get_name(wt_branch));
13493 goto done;
13495 printf("Forwarding %s to %s\n",
13496 got_ref_get_name(wt_branch), branch_name);
13497 error = got_ref_change_ref(wt_branch, branch_tip);
13498 if (error)
13499 goto done;
13500 error = got_ref_write(wt_branch, repo);
13501 if (error)
13502 goto done;
13503 error = got_worktree_set_base_commit_id(worktree, repo,
13504 branch_tip);
13505 if (error)
13506 goto done;
13507 TAILQ_INIT(&paths);
13508 error = got_pathlist_append(&paths, "", NULL);
13509 if (error)
13510 goto done;
13511 error = got_worktree_checkout_files(worktree,
13512 &paths, repo, update_progress, &upa,
13513 check_cancelled, NULL);
13514 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13515 if (error)
13516 goto done;
13517 if (upa.did_something) {
13518 char *id_str;
13519 error = got_object_id_str(&id_str, branch_tip);
13520 if (error)
13521 goto done;
13522 printf("Updated to commit %s\n", id_str);
13523 free(id_str);
13524 } else
13525 printf("Already up-to-date\n");
13526 print_update_progress_stats(&upa);
13527 goto done;
13529 error = got_worktree_merge_write_refs(worktree, branch, repo);
13530 if (error)
13531 goto done;
13533 error = got_worktree_merge_branch(worktree, fileindex,
13534 yca_id, branch_tip, repo, update_progress, &upa,
13535 check_cancelled, NULL);
13536 if (error)
13537 goto done;
13538 print_merge_progress_stats(&upa);
13539 if (!upa.did_something) {
13540 error = got_worktree_merge_abort(worktree, fileindex,
13541 repo, abort_progress, &upa);
13542 if (error)
13543 goto done;
13544 printf("Already up-to-date\n");
13545 goto done;
13549 if (interrupt_merge) {
13550 error = got_worktree_merge_postpone(worktree, fileindex);
13551 if (error)
13552 goto done;
13553 printf("Merge of %s interrupted on request\n", branch_name);
13554 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13555 upa.not_deleted > 0 || upa.unversioned > 0) {
13556 error = got_worktree_merge_postpone(worktree, fileindex);
13557 if (error)
13558 goto done;
13559 if (upa.conflicts > 0 && upa.missing == 0 &&
13560 upa.not_deleted == 0 && upa.unversioned == 0) {
13561 error = got_error_msg(GOT_ERR_CONFLICTS,
13562 "conflicts must be resolved before merging "
13563 "can continue");
13564 } else if (upa.conflicts > 0) {
13565 error = got_error_msg(GOT_ERR_CONFLICTS,
13566 "conflicts must be resolved before merging "
13567 "can continue; changes destined for some "
13568 "files were not yet merged and "
13569 "should be merged manually if required before the "
13570 "merge operation is continued");
13571 } else {
13572 error = got_error_msg(GOT_ERR_CONFLICTS,
13573 "changes destined for some "
13574 "files were not yet merged and should be "
13575 "merged manually if required before the "
13576 "merge operation is continued");
13578 goto done;
13579 } else {
13580 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13581 fileindex, author, NULL, 1, branch_tip, branch_name,
13582 allow_conflict, repo, continue_merge ? print_status : NULL,
13583 NULL);
13584 if (error)
13585 goto done;
13586 error = got_worktree_merge_complete(worktree, fileindex, repo);
13587 if (error)
13588 goto done;
13589 error = got_object_id_str(&id_str, merge_commit_id);
13590 if (error)
13591 goto done;
13592 printf("Merged %s into %s: %s\n", branch_name,
13593 got_worktree_get_head_ref_name(worktree),
13594 id_str);
13597 done:
13598 free(gitconfig_path);
13599 free(id_str);
13600 free(merge_commit_id);
13601 free(author);
13602 free(branch_tip);
13603 free(branch_name);
13604 free(yca_id);
13605 if (branch)
13606 got_ref_close(branch);
13607 if (wt_branch)
13608 got_ref_close(wt_branch);
13609 if (worktree)
13610 got_worktree_close(worktree);
13611 if (repo) {
13612 const struct got_error *close_err = got_repo_close(repo);
13613 if (error == NULL)
13614 error = close_err;
13616 if (pack_fds) {
13617 const struct got_error *pack_err =
13618 got_repo_pack_fds_close(pack_fds);
13619 if (error == NULL)
13620 error = pack_err;
13622 return error;
13625 __dead static void
13626 usage_stage(void)
13628 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13629 "[path ...]\n", getprogname());
13630 exit(1);
13633 static const struct got_error *
13634 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13635 const char *path, struct got_object_id *blob_id,
13636 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13637 int dirfd, const char *de_name)
13639 const struct got_error *err = NULL;
13640 char *id_str = NULL;
13642 if (staged_status != GOT_STATUS_ADD &&
13643 staged_status != GOT_STATUS_MODIFY &&
13644 staged_status != GOT_STATUS_DELETE)
13645 return NULL;
13647 if (staged_status == GOT_STATUS_ADD ||
13648 staged_status == GOT_STATUS_MODIFY)
13649 err = got_object_id_str(&id_str, staged_blob_id);
13650 else
13651 err = got_object_id_str(&id_str, blob_id);
13652 if (err)
13653 return err;
13655 printf("%s %c %s\n", id_str, staged_status, path);
13656 free(id_str);
13657 return NULL;
13660 static const struct got_error *
13661 cmd_stage(int argc, char *argv[])
13663 const struct got_error *error = NULL;
13664 struct got_repository *repo = NULL;
13665 struct got_worktree *worktree = NULL;
13666 char *cwd = NULL;
13667 struct got_pathlist_head paths;
13668 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13669 FILE *patch_script_file = NULL;
13670 const char *patch_script_path = NULL;
13671 struct choose_patch_arg cpa;
13672 int *pack_fds = NULL;
13674 TAILQ_INIT(&paths);
13676 #ifndef PROFILE
13677 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13678 "unveil", NULL) == -1)
13679 err(1, "pledge");
13680 #endif
13682 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13683 switch (ch) {
13684 case 'F':
13685 patch_script_path = optarg;
13686 break;
13687 case 'l':
13688 list_stage = 1;
13689 break;
13690 case 'p':
13691 pflag = 1;
13692 break;
13693 case 'S':
13694 allow_bad_symlinks = 1;
13695 break;
13696 default:
13697 usage_stage();
13698 /* NOTREACHED */
13702 argc -= optind;
13703 argv += optind;
13705 if (list_stage && (pflag || patch_script_path))
13706 errx(1, "-l option cannot be used with other options");
13707 if (patch_script_path && !pflag)
13708 errx(1, "-F option can only be used together with -p option");
13710 cwd = getcwd(NULL, 0);
13711 if (cwd == NULL) {
13712 error = got_error_from_errno("getcwd");
13713 goto done;
13716 error = got_repo_pack_fds_open(&pack_fds);
13717 if (error != NULL)
13718 goto done;
13720 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13721 if (error) {
13722 if (error->code == GOT_ERR_NOT_WORKTREE)
13723 error = wrap_not_worktree_error(error, "stage", cwd);
13724 goto done;
13727 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13728 NULL, pack_fds);
13729 if (error != NULL)
13730 goto done;
13732 if (patch_script_path) {
13733 patch_script_file = fopen(patch_script_path, "re");
13734 if (patch_script_file == NULL) {
13735 error = got_error_from_errno2("fopen",
13736 patch_script_path);
13737 goto done;
13740 error = apply_unveil(got_repo_get_path(repo), 0,
13741 got_worktree_get_root_path(worktree));
13742 if (error)
13743 goto done;
13745 error = check_merge_in_progress(worktree, repo);
13746 if (error)
13747 goto done;
13749 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13750 if (error)
13751 goto done;
13753 if (list_stage)
13754 error = got_worktree_status(worktree, &paths, repo, 0,
13755 print_stage, NULL, check_cancelled, NULL);
13756 else {
13757 cpa.patch_script_file = patch_script_file;
13758 cpa.action = "stage";
13759 error = got_worktree_stage(worktree, &paths,
13760 pflag ? NULL : print_status, NULL,
13761 pflag ? choose_patch : NULL, &cpa,
13762 allow_bad_symlinks, repo);
13764 done:
13765 if (patch_script_file && fclose(patch_script_file) == EOF &&
13766 error == NULL)
13767 error = got_error_from_errno2("fclose", patch_script_path);
13768 if (repo) {
13769 const struct got_error *close_err = got_repo_close(repo);
13770 if (error == NULL)
13771 error = close_err;
13773 if (worktree)
13774 got_worktree_close(worktree);
13775 if (pack_fds) {
13776 const struct got_error *pack_err =
13777 got_repo_pack_fds_close(pack_fds);
13778 if (error == NULL)
13779 error = pack_err;
13781 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13782 free(cwd);
13783 return error;
13786 __dead static void
13787 usage_unstage(void)
13789 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13790 "[path ...]\n", getprogname());
13791 exit(1);
13795 static const struct got_error *
13796 cmd_unstage(int argc, char *argv[])
13798 const struct got_error *error = NULL;
13799 struct got_repository *repo = NULL;
13800 struct got_worktree *worktree = NULL;
13801 char *cwd = NULL;
13802 struct got_pathlist_head paths;
13803 int ch, pflag = 0;
13804 struct got_update_progress_arg upa;
13805 FILE *patch_script_file = NULL;
13806 const char *patch_script_path = NULL;
13807 struct choose_patch_arg cpa;
13808 int *pack_fds = NULL;
13810 TAILQ_INIT(&paths);
13812 #ifndef PROFILE
13813 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13814 "unveil", NULL) == -1)
13815 err(1, "pledge");
13816 #endif
13818 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13819 switch (ch) {
13820 case 'F':
13821 patch_script_path = optarg;
13822 break;
13823 case 'p':
13824 pflag = 1;
13825 break;
13826 default:
13827 usage_unstage();
13828 /* NOTREACHED */
13832 argc -= optind;
13833 argv += optind;
13835 if (patch_script_path && !pflag)
13836 errx(1, "-F option can only be used together with -p option");
13838 cwd = getcwd(NULL, 0);
13839 if (cwd == NULL) {
13840 error = got_error_from_errno("getcwd");
13841 goto done;
13844 error = got_repo_pack_fds_open(&pack_fds);
13845 if (error != NULL)
13846 goto done;
13848 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13849 if (error) {
13850 if (error->code == GOT_ERR_NOT_WORKTREE)
13851 error = wrap_not_worktree_error(error, "unstage", cwd);
13852 goto done;
13855 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13856 NULL, pack_fds);
13857 if (error != NULL)
13858 goto done;
13860 if (patch_script_path) {
13861 patch_script_file = fopen(patch_script_path, "re");
13862 if (patch_script_file == NULL) {
13863 error = got_error_from_errno2("fopen",
13864 patch_script_path);
13865 goto done;
13869 error = apply_unveil(got_repo_get_path(repo), 0,
13870 got_worktree_get_root_path(worktree));
13871 if (error)
13872 goto done;
13874 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13875 if (error)
13876 goto done;
13878 cpa.patch_script_file = patch_script_file;
13879 cpa.action = "unstage";
13880 memset(&upa, 0, sizeof(upa));
13881 error = got_worktree_unstage(worktree, &paths, update_progress,
13882 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13883 if (!error)
13884 print_merge_progress_stats(&upa);
13885 done:
13886 if (patch_script_file && fclose(patch_script_file) == EOF &&
13887 error == NULL)
13888 error = got_error_from_errno2("fclose", patch_script_path);
13889 if (repo) {
13890 const struct got_error *close_err = got_repo_close(repo);
13891 if (error == NULL)
13892 error = close_err;
13894 if (worktree)
13895 got_worktree_close(worktree);
13896 if (pack_fds) {
13897 const struct got_error *pack_err =
13898 got_repo_pack_fds_close(pack_fds);
13899 if (error == NULL)
13900 error = pack_err;
13902 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13903 free(cwd);
13904 return error;
13907 __dead static void
13908 usage_cat(void)
13910 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13911 "arg ...\n", getprogname());
13912 exit(1);
13915 static const struct got_error *
13916 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13918 const struct got_error *err;
13919 struct got_blob_object *blob;
13920 int fd = -1;
13922 fd = got_opentempfd();
13923 if (fd == -1)
13924 return got_error_from_errno("got_opentempfd");
13926 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13927 if (err)
13928 goto done;
13930 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13931 done:
13932 if (fd != -1 && close(fd) == -1 && err == NULL)
13933 err = got_error_from_errno("close");
13934 if (blob)
13935 got_object_blob_close(blob);
13936 return err;
13939 static const struct got_error *
13940 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13942 const struct got_error *err;
13943 struct got_tree_object *tree;
13944 int nentries, i;
13946 err = got_object_open_as_tree(&tree, repo, id);
13947 if (err)
13948 return err;
13950 nentries = got_object_tree_get_nentries(tree);
13951 for (i = 0; i < nentries; i++) {
13952 struct got_tree_entry *te;
13953 char *id_str;
13954 if (sigint_received || sigpipe_received)
13955 break;
13956 te = got_object_tree_get_entry(tree, i);
13957 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13958 if (err)
13959 break;
13960 fprintf(outfile, "%s %.7o %s\n", id_str,
13961 got_tree_entry_get_mode(te),
13962 got_tree_entry_get_name(te));
13963 free(id_str);
13966 got_object_tree_close(tree);
13967 return err;
13970 static const struct got_error *
13971 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13973 const struct got_error *err;
13974 struct got_commit_object *commit;
13975 const struct got_object_id_queue *parent_ids;
13976 struct got_object_qid *pid;
13977 char *id_str = NULL;
13978 const char *logmsg = NULL;
13979 char gmtoff[6];
13981 err = got_object_open_as_commit(&commit, repo, id);
13982 if (err)
13983 return err;
13985 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13986 if (err)
13987 goto done;
13989 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13990 parent_ids = got_object_commit_get_parent_ids(commit);
13991 fprintf(outfile, "numparents %d\n",
13992 got_object_commit_get_nparents(commit));
13993 STAILQ_FOREACH(pid, parent_ids, entry) {
13994 char *pid_str;
13995 err = got_object_id_str(&pid_str, &pid->id);
13996 if (err)
13997 goto done;
13998 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13999 free(pid_str);
14001 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14002 got_object_commit_get_author_gmtoff(commit));
14003 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14004 got_object_commit_get_author(commit),
14005 (long long)got_object_commit_get_author_time(commit),
14006 gmtoff);
14008 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14009 got_object_commit_get_committer_gmtoff(commit));
14010 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14011 got_object_commit_get_committer(commit),
14012 (long long)got_object_commit_get_committer_time(commit),
14013 gmtoff);
14015 logmsg = got_object_commit_get_logmsg_raw(commit);
14016 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14017 fprintf(outfile, "%s", logmsg);
14018 done:
14019 free(id_str);
14020 got_object_commit_close(commit);
14021 return err;
14024 static const struct got_error *
14025 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14027 const struct got_error *err;
14028 struct got_tag_object *tag;
14029 char *id_str = NULL;
14030 const char *tagmsg = NULL;
14031 char gmtoff[6];
14033 err = got_object_open_as_tag(&tag, repo, id);
14034 if (err)
14035 return err;
14037 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14038 if (err)
14039 goto done;
14041 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14043 switch (got_object_tag_get_object_type(tag)) {
14044 case GOT_OBJ_TYPE_BLOB:
14045 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14046 GOT_OBJ_LABEL_BLOB);
14047 break;
14048 case GOT_OBJ_TYPE_TREE:
14049 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14050 GOT_OBJ_LABEL_TREE);
14051 break;
14052 case GOT_OBJ_TYPE_COMMIT:
14053 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14054 GOT_OBJ_LABEL_COMMIT);
14055 break;
14056 case GOT_OBJ_TYPE_TAG:
14057 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14058 GOT_OBJ_LABEL_TAG);
14059 break;
14060 default:
14061 break;
14064 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14065 got_object_tag_get_name(tag));
14067 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14068 got_object_tag_get_tagger_gmtoff(tag));
14069 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14070 got_object_tag_get_tagger(tag),
14071 (long long)got_object_tag_get_tagger_time(tag),
14072 gmtoff);
14074 tagmsg = got_object_tag_get_message(tag);
14075 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14076 fprintf(outfile, "%s", tagmsg);
14077 done:
14078 free(id_str);
14079 got_object_tag_close(tag);
14080 return err;
14083 static const struct got_error *
14084 cmd_cat(int argc, char *argv[])
14086 const struct got_error *error;
14087 struct got_repository *repo = NULL;
14088 struct got_worktree *worktree = NULL;
14089 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14090 char *keyword_idstr = NULL;
14091 const char *commit_id_str = NULL;
14092 struct got_object_id *id = NULL, *commit_id = NULL;
14093 struct got_commit_object *commit = NULL;
14094 int ch, obj_type, i, force_path = 0;
14095 struct got_reflist_head refs;
14096 int *pack_fds = NULL;
14098 TAILQ_INIT(&refs);
14100 #ifndef PROFILE
14101 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14102 NULL) == -1)
14103 err(1, "pledge");
14104 #endif
14106 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14107 switch (ch) {
14108 case 'c':
14109 commit_id_str = optarg;
14110 break;
14111 case 'P':
14112 force_path = 1;
14113 break;
14114 case 'r':
14115 repo_path = realpath(optarg, NULL);
14116 if (repo_path == NULL)
14117 return got_error_from_errno2("realpath",
14118 optarg);
14119 got_path_strip_trailing_slashes(repo_path);
14120 break;
14121 default:
14122 usage_cat();
14123 /* NOTREACHED */
14127 argc -= optind;
14128 argv += optind;
14130 cwd = getcwd(NULL, 0);
14131 if (cwd == NULL) {
14132 error = got_error_from_errno("getcwd");
14133 goto done;
14136 error = got_repo_pack_fds_open(&pack_fds);
14137 if (error != NULL)
14138 goto done;
14140 if (repo_path == NULL) {
14141 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14142 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14143 goto done;
14144 if (worktree) {
14145 repo_path = strdup(
14146 got_worktree_get_repo_path(worktree));
14147 if (repo_path == NULL) {
14148 error = got_error_from_errno("strdup");
14149 goto done;
14152 if (commit_id_str == NULL) {
14153 /* Release work tree lock. */
14154 got_worktree_close(worktree);
14155 worktree = NULL;
14160 if (repo_path == NULL) {
14161 repo_path = strdup(cwd);
14162 if (repo_path == NULL)
14163 return got_error_from_errno("strdup");
14166 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14167 free(repo_path);
14168 if (error != NULL)
14169 goto done;
14171 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14172 if (error)
14173 goto done;
14175 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14176 if (error)
14177 goto done;
14179 if (commit_id_str != NULL) {
14180 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14181 repo, worktree);
14182 if (error != NULL)
14183 goto done;
14184 if (keyword_idstr != NULL)
14185 commit_id_str = keyword_idstr;
14186 if (worktree != NULL) {
14187 got_worktree_close(worktree);
14188 worktree = NULL;
14190 } else
14191 commit_id_str = GOT_REF_HEAD;
14192 error = got_repo_match_object_id(&commit_id, NULL,
14193 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14194 if (error)
14195 goto done;
14197 error = got_object_open_as_commit(&commit, repo, commit_id);
14198 if (error)
14199 goto done;
14201 for (i = 0; i < argc; i++) {
14202 if (force_path) {
14203 error = got_object_id_by_path(&id, repo, commit,
14204 argv[i]);
14205 if (error)
14206 break;
14207 } else {
14208 error = got_repo_match_object_id(&id, &label, argv[i],
14209 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14210 repo);
14211 if (error) {
14212 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14213 error->code != GOT_ERR_NOT_REF)
14214 break;
14215 error = got_object_id_by_path(&id, repo,
14216 commit, argv[i]);
14217 if (error)
14218 break;
14222 error = got_object_get_type(&obj_type, repo, id);
14223 if (error)
14224 break;
14226 switch (obj_type) {
14227 case GOT_OBJ_TYPE_BLOB:
14228 error = cat_blob(id, repo, stdout);
14229 break;
14230 case GOT_OBJ_TYPE_TREE:
14231 error = cat_tree(id, repo, stdout);
14232 break;
14233 case GOT_OBJ_TYPE_COMMIT:
14234 error = cat_commit(id, repo, stdout);
14235 break;
14236 case GOT_OBJ_TYPE_TAG:
14237 error = cat_tag(id, repo, stdout);
14238 break;
14239 default:
14240 error = got_error(GOT_ERR_OBJ_TYPE);
14241 break;
14243 if (error)
14244 break;
14245 free(label);
14246 label = NULL;
14247 free(id);
14248 id = NULL;
14250 done:
14251 free(label);
14252 free(id);
14253 free(commit_id);
14254 free(keyword_idstr);
14255 if (commit)
14256 got_object_commit_close(commit);
14257 if (worktree)
14258 got_worktree_close(worktree);
14259 if (repo) {
14260 const struct got_error *close_err = got_repo_close(repo);
14261 if (error == NULL)
14262 error = close_err;
14264 if (pack_fds) {
14265 const struct got_error *pack_err =
14266 got_repo_pack_fds_close(pack_fds);
14267 if (error == NULL)
14268 error = pack_err;
14271 got_ref_list_free(&refs);
14272 return error;
14275 __dead static void
14276 usage_info(void)
14278 fprintf(stderr, "usage: %s info [path ...]\n",
14279 getprogname());
14280 exit(1);
14283 static const struct got_error *
14284 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14285 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14286 struct got_object_id *commit_id)
14288 const struct got_error *err = NULL;
14289 char *id_str = NULL;
14290 char datebuf[128];
14291 struct tm mytm, *tm;
14292 struct got_pathlist_head *paths = arg;
14293 struct got_pathlist_entry *pe;
14296 * Clear error indication from any of the path arguments which
14297 * would cause this file index entry to be displayed.
14299 TAILQ_FOREACH(pe, paths, entry) {
14300 if (got_path_cmp(path, pe->path, strlen(path),
14301 pe->path_len) == 0 ||
14302 got_path_is_child(path, pe->path, pe->path_len))
14303 pe->data = NULL; /* no error */
14306 printf(GOT_COMMIT_SEP_STR);
14307 if (S_ISLNK(mode))
14308 printf("symlink: %s\n", path);
14309 else if (S_ISREG(mode)) {
14310 printf("file: %s\n", path);
14311 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14312 } else if (S_ISDIR(mode))
14313 printf("directory: %s\n", path);
14314 else
14315 printf("something: %s\n", path);
14317 tm = localtime_r(&mtime, &mytm);
14318 if (tm == NULL)
14319 return NULL;
14320 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14321 return got_error(GOT_ERR_NO_SPACE);
14322 printf("timestamp: %s\n", datebuf);
14324 if (blob_id) {
14325 err = got_object_id_str(&id_str, blob_id);
14326 if (err)
14327 return err;
14328 printf("based on blob: %s\n", id_str);
14329 free(id_str);
14332 if (staged_blob_id) {
14333 err = got_object_id_str(&id_str, staged_blob_id);
14334 if (err)
14335 return err;
14336 printf("based on staged blob: %s\n", id_str);
14337 free(id_str);
14340 if (commit_id) {
14341 err = got_object_id_str(&id_str, commit_id);
14342 if (err)
14343 return err;
14344 printf("based on commit: %s\n", id_str);
14345 free(id_str);
14348 return NULL;
14351 static const struct got_error *
14352 cmd_info(int argc, char *argv[])
14354 const struct got_error *error = NULL;
14355 struct got_worktree *worktree = NULL;
14356 char *cwd = NULL, *id_str = NULL;
14357 struct got_pathlist_head paths;
14358 char *uuidstr = NULL;
14359 int ch, show_files = 0;
14361 TAILQ_INIT(&paths);
14363 #ifndef PROFILE
14364 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14365 NULL) == -1)
14366 err(1, "pledge");
14367 #endif
14369 while ((ch = getopt(argc, argv, "")) != -1) {
14370 switch (ch) {
14371 default:
14372 usage_info();
14373 /* NOTREACHED */
14377 argc -= optind;
14378 argv += optind;
14380 cwd = getcwd(NULL, 0);
14381 if (cwd == NULL) {
14382 error = got_error_from_errno("getcwd");
14383 goto done;
14386 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14387 if (error) {
14388 if (error->code == GOT_ERR_NOT_WORKTREE)
14389 error = wrap_not_worktree_error(error, "info", cwd);
14390 goto done;
14393 #ifndef PROFILE
14394 /* Remove "wpath cpath proc exec sendfd" promises. */
14395 if (pledge("stdio rpath flock unveil", NULL) == -1)
14396 err(1, "pledge");
14397 #endif
14398 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14399 if (error)
14400 goto done;
14402 if (argc >= 1) {
14403 error = get_worktree_paths_from_argv(&paths, argc, argv,
14404 worktree);
14405 if (error)
14406 goto done;
14407 show_files = 1;
14410 error = got_object_id_str(&id_str,
14411 got_worktree_get_base_commit_id(worktree));
14412 if (error)
14413 goto done;
14415 error = got_worktree_get_uuid(&uuidstr, worktree);
14416 if (error)
14417 goto done;
14419 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14420 printf("work tree base commit: %s\n", id_str);
14421 printf("work tree path prefix: %s\n",
14422 got_worktree_get_path_prefix(worktree));
14423 printf("work tree branch reference: %s\n",
14424 got_worktree_get_head_ref_name(worktree));
14425 printf("work tree UUID: %s\n", uuidstr);
14426 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14428 if (show_files) {
14429 struct got_pathlist_entry *pe;
14430 TAILQ_FOREACH(pe, &paths, entry) {
14431 if (pe->path_len == 0)
14432 continue;
14434 * Assume this path will fail. This will be corrected
14435 * in print_path_info() in case the path does suceeed.
14437 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14439 error = got_worktree_path_info(worktree, &paths,
14440 print_path_info, &paths, check_cancelled, NULL);
14441 if (error)
14442 goto done;
14443 TAILQ_FOREACH(pe, &paths, entry) {
14444 if (pe->data != NULL) {
14445 const struct got_error *perr;
14447 perr = pe->data;
14448 error = got_error_fmt(perr->code, "%s",
14449 pe->path);
14450 break;
14454 done:
14455 if (worktree)
14456 got_worktree_close(worktree);
14457 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14458 free(cwd);
14459 free(id_str);
14460 free(uuidstr);
14461 return error;