Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fflush(stdout);
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/usr/bin/vi");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_import(void)
352 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
353 "[-r repository-path] directory\n", getprogname());
354 exit(1);
357 static int
358 spawn_editor(const char *editor, const char *file)
360 pid_t pid;
361 sig_t sighup, sigint, sigquit;
362 int st = -1;
364 sighup = signal(SIGHUP, SIG_IGN);
365 sigint = signal(SIGINT, SIG_IGN);
366 sigquit = signal(SIGQUIT, SIG_IGN);
368 switch (pid = fork()) {
369 case -1:
370 goto doneediting;
371 case 0:
372 execl(editor, editor, file, (char *)NULL);
373 _exit(127);
376 while (waitpid(pid, &st, 0) == -1)
377 if (errno != EINTR)
378 break;
380 doneediting:
381 (void)signal(SIGHUP, sighup);
382 (void)signal(SIGINT, sigint);
383 (void)signal(SIGQUIT, sigquit);
385 if (!WIFEXITED(st)) {
386 errno = EINTR;
387 return -1;
390 return WEXITSTATUS(st);
393 static const struct got_error *
394 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
400 *logmsg = NULL;
401 *len = 0;
403 if (fseeko(fp, 0L, SEEK_SET) == -1)
404 return got_error_from_errno("fseeko");
406 *logmsg = malloc(filesize + 1);
407 if (*logmsg == NULL)
408 return got_error_from_errno("malloc");
409 (*logmsg)[0] = '\0';
411 while (getline(&line, &linesize, fp) != -1) {
412 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t logmsg_len;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (require_modification) {
458 struct timespec timeout;
460 timeout.tv_sec = 0;
461 timeout.tv_nsec = 1;
462 nanosleep(&timeout, NULL);
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno2("stat", logmsg_path);
468 if (require_modification && st.st_size == st2.st_size &&
469 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 fp = fopen(logmsg_path, "re");
474 if (fp == NULL) {
475 err = got_error_from_errno("fopen");
476 goto done;
479 /* strip comments and leading/trailing newlines */
480 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
481 if (err)
482 goto done;
483 if (logmsg_len == 0) {
484 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
485 "commit message cannot be empty, aborting");
486 goto done;
488 done:
489 if (fp && fclose(fp) == EOF && err == NULL)
490 err = got_error_from_errno("fclose");
491 if (err) {
492 free(*logmsg);
493 *logmsg = NULL;
495 return err;
498 static const struct got_error *
499 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
500 const char *path_dir, const char *branch_name)
502 char *initial_content = NULL;
503 const struct got_error *err = NULL;
504 int initial_content_len;
505 int fd = -1;
507 initial_content_len = asprintf(&initial_content,
508 "\n# %s to be imported to branch %s\n", path_dir,
509 branch_name);
510 if (initial_content_len == -1)
511 return got_error_from_errno("asprintf");
513 err = got_opentemp_named_fd(logmsg_path, &fd,
514 GOT_TMPDIR_STR "/got-importmsg", "");
515 if (err)
516 goto done;
518 if (write(fd, initial_content, initial_content_len) == -1) {
519 err = got_error_from_errno2("write", *logmsg_path);
520 goto done;
522 if (close(fd) == -1) {
523 err = got_error_from_errno2("close", *logmsg_path);
524 goto done;
526 fd = -1;
528 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
529 initial_content_len, 1);
530 done:
531 if (fd != -1 && close(fd) == -1 && err == NULL)
532 err = got_error_from_errno2("close", *logmsg_path);
533 free(initial_content);
534 if (err) {
535 free(*logmsg_path);
536 *logmsg_path = NULL;
538 return err;
541 static const struct got_error *
542 import_progress(void *arg, const char *path)
544 printf("A %s\n", path);
545 return NULL;
548 static const struct got_error *
549 valid_author(const char *author)
551 const char *email = author;
553 /*
554 * Git' expects the author (or committer) to be in the form
555 * "name <email>", which are mostly free form (see the
556 * "committer" description in git-fast-import(1)). We're only
557 * doing this to avoid git's object parser breaking on commits
558 * we create.
559 */
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (author != email && *author == '<' && *(author - 1) != ' ')
564 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
565 "between author name and email required", email);
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const char *
711 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 if (worktree)
717 worktree_conf = got_worktree_get_gotconfig(worktree);
718 repo_conf = got_repo_get_gotconfig(repo);
720 /*
721 * Priority of potential author information sources, from most
722 * significant to least significant:
723 * 1) work tree's .got/got.conf file
724 * 2) repository's got.conf file
725 */
727 if (worktree_conf)
728 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
729 if (got_signer_id == NULL)
730 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
732 return got_signer_id;
735 static const struct got_error *
736 get_gitconfig_path(char **gitconfig_path)
738 const char *homedir = getenv("HOME");
740 *gitconfig_path = NULL;
741 if (homedir) {
742 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
743 return got_error_from_errno("asprintf");
746 return NULL;
749 static const struct got_error *
750 cmd_import(int argc, char *argv[])
752 const struct got_error *error = NULL;
753 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
754 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
755 const char *branch_name = NULL;
756 char *id_str = NULL, *logmsg_path = NULL;
757 char refname[PATH_MAX] = "refs/heads/";
758 struct got_repository *repo = NULL;
759 struct got_reference *branch_ref = NULL, *head_ref = NULL;
760 struct got_object_id *new_commit_id = NULL;
761 int ch, n = 0;
762 struct got_pathlist_head ignores;
763 struct got_pathlist_entry *pe;
764 int preserve_logmsg = 0;
765 int *pack_fds = NULL;
767 TAILQ_INIT(&ignores);
769 #ifndef PROFILE
770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
771 "unveil",
772 NULL) == -1)
773 err(1, "pledge");
774 #endif
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 if (argc != 1)
814 usage_import();
816 if (repo_path == NULL) {
817 repo_path = getcwd(NULL, 0);
818 if (repo_path == NULL)
819 return got_error_from_errno("getcwd");
821 got_path_strip_trailing_slashes(repo_path);
822 error = get_gitconfig_path(&gitconfig_path);
823 if (error)
824 goto done;
825 error = got_repo_pack_fds_open(&pack_fds);
826 if (error != NULL)
827 goto done;
828 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
829 if (error)
830 goto done;
832 error = get_author(&author, repo, NULL);
833 if (error)
834 return error;
836 /*
837 * Don't let the user create a branch name with a leading '-'.
838 * While technically a valid reference name, this case is usually
839 * an unintended typo.
840 */
841 if (branch_name && branch_name[0] == '-')
842 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
844 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
845 if (error && error->code != GOT_ERR_NOT_REF)
846 goto done;
848 if (branch_name)
849 n = strlcat(refname, branch_name, sizeof(refname));
850 else if (head_ref && got_ref_is_symbolic(head_ref))
851 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
852 sizeof(refname));
853 else
854 n = strlcat(refname, "main", sizeof(refname));
855 if (n >= sizeof(refname)) {
856 error = got_error(GOT_ERR_NO_SPACE);
857 goto done;
860 error = got_ref_open(&branch_ref, repo, refname, 0);
861 if (error) {
862 if (error->code != GOT_ERR_NOT_REF)
863 goto done;
864 } else {
865 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
866 "import target branch already exists");
867 goto done;
870 path_dir = realpath(argv[0], NULL);
871 if (path_dir == NULL) {
872 error = got_error_from_errno2("realpath", argv[0]);
873 goto done;
875 got_path_strip_trailing_slashes(path_dir);
877 /*
878 * unveil(2) traverses exec(2); if an editor is used we have
879 * to apply unveil after the log message has been written.
880 */
881 if (logmsg == NULL || *logmsg == '\0') {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes;
2291 struct got_remote_repo *remote = NULL;
2292 int nremotes;
2293 char *id_str = NULL;
2294 struct got_repository *repo = NULL;
2295 struct got_worktree *worktree = NULL;
2296 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2297 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2298 char *head_refname = NULL;
2299 struct got_pathlist_entry *pe;
2300 struct got_reflist_head remote_refs;
2301 struct got_reflist_entry *re;
2302 struct got_object_id *pack_hash = NULL;
2303 int i, ch, fetchfd = -1, fetchstatus;
2304 pid_t fetchpid = -1;
2305 struct got_fetch_progress_arg fpa;
2306 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2307 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2308 int *pack_fds = NULL, have_bflag = 0;
2309 const char *remote_head = NULL, *worktree_branch = NULL;
2311 TAILQ_INIT(&refs);
2312 TAILQ_INIT(&symrefs);
2313 TAILQ_INIT(&remote_refs);
2314 TAILQ_INIT(&wanted_branches);
2315 TAILQ_INIT(&wanted_refs);
2317 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2318 switch (ch) {
2319 case 'a':
2320 fetch_all_branches = 1;
2321 break;
2322 case 'b':
2323 error = got_pathlist_append(&wanted_branches,
2324 optarg, NULL);
2325 if (error)
2326 return error;
2327 have_bflag = 1;
2328 break;
2329 case 'd':
2330 delete_refs = 1;
2331 break;
2332 case 'l':
2333 list_refs_only = 1;
2334 break;
2335 case 'q':
2336 verbosity = -1;
2337 break;
2338 case 'R':
2339 error = got_pathlist_append(&wanted_refs,
2340 optarg, NULL);
2341 if (error)
2342 return error;
2343 break;
2344 case 'r':
2345 repo_path = realpath(optarg, NULL);
2346 if (repo_path == NULL)
2347 return got_error_from_errno2("realpath",
2348 optarg);
2349 got_path_strip_trailing_slashes(repo_path);
2350 break;
2351 case 't':
2352 replace_tags = 1;
2353 break;
2354 case 'v':
2355 if (verbosity < 0)
2356 verbosity = 0;
2357 else if (verbosity < 3)
2358 verbosity++;
2359 break;
2360 case 'X':
2361 delete_remote = 1;
2362 break;
2363 default:
2364 usage_fetch();
2365 break;
2368 argc -= optind;
2369 argv += optind;
2371 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2372 option_conflict('a', 'b');
2373 if (list_refs_only) {
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('l', 'b');
2376 if (fetch_all_branches)
2377 option_conflict('l', 'a');
2378 if (delete_refs)
2379 option_conflict('l', 'd');
2380 if (delete_remote)
2381 option_conflict('l', 'X');
2383 if (delete_remote) {
2384 if (fetch_all_branches)
2385 option_conflict('X', 'a');
2386 if (!TAILQ_EMPTY(&wanted_branches))
2387 option_conflict('X', 'b');
2388 if (delete_refs)
2389 option_conflict('X', 'd');
2390 if (replace_tags)
2391 option_conflict('X', 't');
2392 if (!TAILQ_EMPTY(&wanted_refs))
2393 option_conflict('X', 'R');
2396 if (argc == 0) {
2397 if (delete_remote)
2398 errx(1, "-X option requires a remote name");
2399 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2400 } else if (argc == 1)
2401 remote_name = argv[0];
2402 else
2403 usage_fetch();
2405 cwd = getcwd(NULL, 0);
2406 if (cwd == NULL) {
2407 error = got_error_from_errno("getcwd");
2408 goto done;
2411 error = got_repo_pack_fds_open(&pack_fds);
2412 if (error != NULL)
2413 goto done;
2415 if (repo_path == NULL) {
2416 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2417 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2418 goto done;
2419 else
2420 error = NULL;
2421 if (worktree) {
2422 repo_path =
2423 strdup(got_worktree_get_repo_path(worktree));
2424 if (repo_path == NULL)
2425 error = got_error_from_errno("strdup");
2426 if (error)
2427 goto done;
2428 } else {
2429 repo_path = strdup(cwd);
2430 if (repo_path == NULL) {
2431 error = got_error_from_errno("strdup");
2432 goto done;
2437 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2438 if (error)
2439 goto done;
2441 if (delete_remote) {
2442 error = delete_refs_for_remote(repo, remote_name);
2443 goto done; /* nothing else to do */
2446 if (worktree) {
2447 worktree_conf = got_worktree_get_gotconfig(worktree);
2448 if (worktree_conf) {
2449 got_gotconfig_get_remotes(&nremotes, &remotes,
2450 worktree_conf);
2451 for (i = 0; i < nremotes; i++) {
2452 if (strcmp(remotes[i].name, remote_name) == 0) {
2453 error = got_repo_remote_repo_dup(&remote,
2454 &remotes[i]);
2455 if (error)
2456 goto done;
2457 break;
2462 if (remote == NULL) {
2463 repo_conf = got_repo_get_gotconfig(repo);
2464 if (repo_conf) {
2465 got_gotconfig_get_remotes(&nremotes, &remotes,
2466 repo_conf);
2467 for (i = 0; i < nremotes; i++) {
2468 if (strcmp(remotes[i].name, remote_name) == 0) {
2469 error = got_repo_remote_repo_dup(&remote,
2470 &remotes[i]);
2471 if (error)
2472 goto done;
2473 break;
2478 if (remote == NULL) {
2479 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2480 for (i = 0; i < nremotes; i++) {
2481 if (strcmp(remotes[i].name, remote_name) == 0) {
2482 error = got_repo_remote_repo_dup(&remote,
2483 &remotes[i]);
2484 if (error)
2485 goto done;
2486 break;
2490 if (remote == NULL) {
2491 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2492 goto done;
2495 if (TAILQ_EMPTY(&wanted_branches)) {
2496 if (!fetch_all_branches)
2497 fetch_all_branches = remote->fetch_all_branches;
2498 for (i = 0; i < remote->nfetch_branches; i++) {
2499 error = got_pathlist_append(&wanted_branches,
2500 remote->fetch_branches[i], NULL);
2501 if (error)
2502 goto done;
2505 if (TAILQ_EMPTY(&wanted_refs)) {
2506 for (i = 0; i < remote->nfetch_refs; i++) {
2507 error = got_pathlist_append(&wanted_refs,
2508 remote->fetch_refs[i], NULL);
2509 if (error)
2510 goto done;
2514 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2515 &repo_name, remote->fetch_url);
2516 if (error)
2517 goto done;
2519 if (strcmp(proto, "git") == 0) {
2520 #ifndef PROFILE
2521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2522 "sendfd dns inet unveil", NULL) == -1)
2523 err(1, "pledge");
2524 #endif
2525 } else if (strcmp(proto, "git+ssh") == 0 ||
2526 strcmp(proto, "ssh") == 0) {
2527 #ifndef PROFILE
2528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2529 "sendfd unveil", NULL) == -1)
2530 err(1, "pledge");
2531 #endif
2532 } else if (strcmp(proto, "http") == 0 ||
2533 strcmp(proto, "git+http") == 0) {
2534 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2535 goto done;
2536 } else {
2537 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2538 goto done;
2541 error = got_dial_apply_unveil(proto);
2542 if (error)
2543 goto done;
2545 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2546 if (error)
2547 goto done;
2549 if (worktree) {
2550 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2551 if (head_refname == NULL) {
2552 error = got_error_from_errno("strdup");
2553 goto done;
2556 /* Release work tree lock. */
2557 got_worktree_close(worktree);
2558 worktree = NULL;
2561 if (verbosity >= 0) {
2562 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2563 remote->name, proto, host,
2564 port ? ":" : "", port ? port : "",
2565 *server_path == '/' ? "" : "/", server_path);
2568 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2569 server_path, verbosity);
2570 if (error)
2571 goto done;
2573 if (!have_bflag) {
2575 * If set, get this remote's HEAD ref target so
2576 * if it has changed on the server we can fetch it.
2578 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2579 got_ref_cmp_by_name, repo);
2580 if (error)
2581 goto done;
2583 TAILQ_FOREACH(re, &remote_refs, entry) {
2584 const char *remote_refname, *remote_target;
2585 size_t remote_name_len;
2587 if (!got_ref_is_symbolic(re->ref))
2588 continue;
2590 remote_name_len = strlen(remote->name);
2591 remote_refname = got_ref_get_name(re->ref);
2593 /* we only want refs/remotes/$remote->name/HEAD */
2594 if (strncmp(remote_refname + 13, remote->name,
2595 remote_name_len) != 0)
2596 continue;
2598 if (strcmp(remote_refname + remote_name_len + 14,
2599 GOT_REF_HEAD) != 0)
2600 continue;
2603 * Take the name itself because we already
2604 * only match with refs/heads/ in fetch_pack().
2606 remote_target = got_ref_get_symref_target(re->ref);
2607 remote_head = remote_target + remote_name_len + 14;
2608 break;
2611 if (head_refname &&
2612 strncmp(head_refname, "refs/heads/", 11) == 0)
2613 worktree_branch = head_refname;
2616 fpa.last_scaled_size[0] = '\0';
2617 fpa.last_p_indexed = -1;
2618 fpa.last_p_resolved = -1;
2619 fpa.verbosity = verbosity;
2620 fpa.repo = repo;
2621 fpa.create_configs = 0;
2622 fpa.configs_created = 0;
2623 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2625 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2626 remote->mirror_references, fetch_all_branches, &wanted_branches,
2627 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2628 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2629 if (error)
2630 goto done;
2632 if (list_refs_only) {
2633 error = list_remote_refs(&symrefs, &refs);
2634 goto done;
2637 if (pack_hash == NULL) {
2638 if (verbosity >= 0)
2639 printf("Already up-to-date\n");
2640 } else if (verbosity >= 0) {
2641 error = got_object_id_str(&id_str, pack_hash);
2642 if (error)
2643 goto done;
2644 printf("\nFetched %s.pack\n", id_str);
2645 free(id_str);
2646 id_str = NULL;
2649 /* Update references provided with the pack file. */
2650 TAILQ_FOREACH(pe, &refs, entry) {
2651 const char *refname = pe->path;
2652 struct got_object_id *id = pe->data;
2653 struct got_reference *ref;
2654 char *remote_refname;
2656 if (is_wanted_ref(&wanted_refs, refname) &&
2657 !remote->mirror_references) {
2658 error = update_wanted_ref(refname, id,
2659 remote->name, verbosity, repo);
2660 if (error)
2661 goto done;
2662 continue;
2665 if (remote->mirror_references ||
2666 strncmp("refs/tags/", refname, 10) == 0) {
2667 error = got_ref_open(&ref, repo, refname, 1);
2668 if (error) {
2669 if (error->code != GOT_ERR_NOT_REF)
2670 goto done;
2671 error = create_ref(refname, id, verbosity,
2672 repo);
2673 if (error)
2674 goto done;
2675 } else {
2676 error = update_ref(ref, id, replace_tags,
2677 verbosity, repo);
2678 unlock_err = got_ref_unlock(ref);
2679 if (unlock_err && error == NULL)
2680 error = unlock_err;
2681 got_ref_close(ref);
2682 if (error)
2683 goto done;
2685 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2686 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2687 remote_name, refname + 11) == -1) {
2688 error = got_error_from_errno("asprintf");
2689 goto done;
2692 error = got_ref_open(&ref, repo, remote_refname, 1);
2693 if (error) {
2694 if (error->code != GOT_ERR_NOT_REF)
2695 goto done;
2696 error = create_ref(remote_refname, id,
2697 verbosity, repo);
2698 if (error)
2699 goto done;
2700 } else {
2701 error = update_ref(ref, id, replace_tags,
2702 verbosity, repo);
2703 unlock_err = got_ref_unlock(ref);
2704 if (unlock_err && error == NULL)
2705 error = unlock_err;
2706 got_ref_close(ref);
2707 if (error)
2708 goto done;
2711 /* Also create a local branch if none exists yet. */
2712 error = got_ref_open(&ref, repo, refname, 1);
2713 if (error) {
2714 if (error->code != GOT_ERR_NOT_REF)
2715 goto done;
2716 error = create_ref(refname, id, verbosity,
2717 repo);
2718 if (error)
2719 goto done;
2720 } else {
2721 unlock_err = got_ref_unlock(ref);
2722 if (unlock_err && error == NULL)
2723 error = unlock_err;
2724 got_ref_close(ref);
2728 if (delete_refs) {
2729 error = delete_missing_refs(&refs, &symrefs, remote,
2730 verbosity, repo);
2731 if (error)
2732 goto done;
2735 if (!remote->mirror_references) {
2736 /* Update remote HEAD reference if the server provided one. */
2737 TAILQ_FOREACH(pe, &symrefs, entry) {
2738 struct got_reference *target_ref;
2739 const char *refname = pe->path;
2740 const char *target = pe->data;
2741 char *remote_refname = NULL, *remote_target = NULL;
2743 if (strcmp(refname, GOT_REF_HEAD) != 0)
2744 continue;
2746 if (strncmp("refs/heads/", target, 11) != 0)
2747 continue;
2749 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2750 remote->name, refname) == -1) {
2751 error = got_error_from_errno("asprintf");
2752 goto done;
2754 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2755 remote->name, target + 11) == -1) {
2756 error = got_error_from_errno("asprintf");
2757 free(remote_refname);
2758 goto done;
2761 error = got_ref_open(&target_ref, repo, remote_target,
2762 0);
2763 if (error) {
2764 free(remote_refname);
2765 free(remote_target);
2766 if (error->code == GOT_ERR_NOT_REF) {
2767 error = NULL;
2768 continue;
2770 goto done;
2772 error = update_symref(remote_refname, target_ref,
2773 verbosity, repo);
2774 free(remote_refname);
2775 free(remote_target);
2776 got_ref_close(target_ref);
2777 if (error)
2778 goto done;
2781 done:
2782 if (fetchpid > 0) {
2783 if (kill(fetchpid, SIGTERM) == -1)
2784 error = got_error_from_errno("kill");
2785 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2786 error = got_error_from_errno("waitpid");
2788 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2789 error = got_error_from_errno("close");
2790 if (repo) {
2791 const struct got_error *close_err = got_repo_close(repo);
2792 if (error == NULL)
2793 error = close_err;
2795 if (worktree)
2796 got_worktree_close(worktree);
2797 if (pack_fds) {
2798 const struct got_error *pack_err =
2799 got_repo_pack_fds_close(pack_fds);
2800 if (error == NULL)
2801 error = pack_err;
2803 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2804 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2805 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2806 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2807 got_ref_list_free(&remote_refs);
2808 got_repo_free_remote_repo_data(remote);
2809 free(remote);
2810 free(head_refname);
2811 free(id_str);
2812 free(cwd);
2813 free(repo_path);
2814 free(pack_hash);
2815 free(proto);
2816 free(host);
2817 free(port);
2818 free(server_path);
2819 free(repo_name);
2820 return error;
2824 __dead static void
2825 usage_checkout(void)
2827 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2828 "[-p path-prefix] repository-path [work-tree-path]\n",
2829 getprogname());
2830 exit(1);
2833 static void
2834 show_worktree_base_ref_warning(void)
2836 fprintf(stderr, "%s: warning: could not create a reference "
2837 "to the work tree's base commit; the commit could be "
2838 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2839 "repository writable and running 'got update' will prevent this\n",
2840 getprogname());
2843 struct got_checkout_progress_arg {
2844 const char *worktree_path;
2845 int had_base_commit_ref_error;
2846 int verbosity;
2849 static const struct got_error *
2850 checkout_progress(void *arg, unsigned char status, const char *path)
2852 struct got_checkout_progress_arg *a = arg;
2854 /* Base commit bump happens silently. */
2855 if (status == GOT_STATUS_BUMP_BASE)
2856 return NULL;
2858 if (status == GOT_STATUS_BASE_REF_ERR) {
2859 a->had_base_commit_ref_error = 1;
2860 return NULL;
2863 while (path[0] == '/')
2864 path++;
2866 if (a->verbosity >= 0)
2867 printf("%c %s/%s\n", status, a->worktree_path, path);
2869 return NULL;
2872 static const struct got_error *
2873 check_cancelled(void *arg)
2875 if (sigint_received || sigpipe_received)
2876 return got_error(GOT_ERR_CANCELLED);
2877 return NULL;
2880 static const struct got_error *
2881 check_linear_ancestry(struct got_object_id *commit_id,
2882 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2883 struct got_repository *repo)
2885 const struct got_error *err = NULL;
2886 struct got_object_id *yca_id;
2888 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2889 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2890 if (err)
2891 return err;
2893 if (yca_id == NULL)
2894 return got_error(GOT_ERR_ANCESTRY);
2897 * Require a straight line of history between the target commit
2898 * and the work tree's base commit.
2900 * Non-linear situations such as this require a rebase:
2902 * (commit) D F (base_commit)
2903 * \ /
2904 * C E
2905 * \ /
2906 * B (yca)
2907 * |
2908 * A
2910 * 'got update' only handles linear cases:
2911 * Update forwards in time: A (base/yca) - B - C - D (commit)
2912 * Update backwards in time: D (base) - C - B - A (commit/yca)
2914 if (allow_forwards_in_time_only) {
2915 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2916 return got_error(GOT_ERR_ANCESTRY);
2917 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2918 got_object_id_cmp(base_commit_id, yca_id) != 0)
2919 return got_error(GOT_ERR_ANCESTRY);
2921 free(yca_id);
2922 return NULL;
2925 static const struct got_error *
2926 check_same_branch(struct got_object_id *commit_id,
2927 struct got_reference *head_ref, struct got_repository *repo)
2929 const struct got_error *err = NULL;
2930 struct got_commit_graph *graph = NULL;
2931 struct got_object_id *head_commit_id = NULL;
2933 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2934 if (err)
2935 goto done;
2937 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2938 goto done;
2940 err = got_commit_graph_open(&graph, "/", 1);
2941 if (err)
2942 goto done;
2944 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2945 check_cancelled, NULL);
2946 if (err)
2947 goto done;
2949 for (;;) {
2950 struct got_object_id id;
2952 err = got_commit_graph_iter_next(&id, graph, repo,
2953 check_cancelled, NULL);
2954 if (err) {
2955 if (err->code == GOT_ERR_ITER_COMPLETED)
2956 err = got_error(GOT_ERR_ANCESTRY);
2957 break;
2960 if (got_object_id_cmp(&id, commit_id) == 0)
2961 break;
2963 done:
2964 if (graph)
2965 got_commit_graph_close(graph);
2966 free(head_commit_id);
2967 return err;
2970 static const struct got_error *
2971 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2973 static char msg[512];
2974 const char *branch_name;
2976 if (got_ref_is_symbolic(ref))
2977 branch_name = got_ref_get_symref_target(ref);
2978 else
2979 branch_name = got_ref_get_name(ref);
2981 if (strncmp("refs/heads/", branch_name, 11) == 0)
2982 branch_name += 11;
2984 snprintf(msg, sizeof(msg),
2985 "target commit is not contained in branch '%s'; "
2986 "the branch to use must be specified with -b; "
2987 "if necessary a new branch can be created for "
2988 "this commit with 'got branch -c %s BRANCH_NAME'",
2989 branch_name, commit_id_str);
2991 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2994 static const struct got_error *
2995 cmd_checkout(int argc, char *argv[])
2997 const struct got_error *error = NULL;
2998 struct got_repository *repo = NULL;
2999 struct got_reference *head_ref = NULL, *ref = NULL;
3000 struct got_worktree *worktree = NULL;
3001 char *repo_path = NULL;
3002 char *worktree_path = NULL;
3003 const char *path_prefix = "";
3004 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3005 char *commit_id_str = NULL, *keyword_idstr = NULL;
3006 struct got_object_id *commit_id = NULL;
3007 char *cwd = NULL;
3008 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3009 struct got_pathlist_head paths;
3010 struct got_checkout_progress_arg cpa;
3011 int *pack_fds = NULL;
3013 TAILQ_INIT(&paths);
3015 #ifndef PROFILE
3016 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3017 "unveil", NULL) == -1)
3018 err(1, "pledge");
3019 #endif
3021 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3022 switch (ch) {
3023 case 'b':
3024 branch_name = optarg;
3025 break;
3026 case 'c':
3027 commit_id_str = strdup(optarg);
3028 if (commit_id_str == NULL)
3029 return got_error_from_errno("strdup");
3030 break;
3031 case 'E':
3032 allow_nonempty = 1;
3033 break;
3034 case 'p':
3035 path_prefix = optarg;
3036 break;
3037 case 'q':
3038 verbosity = -1;
3039 break;
3040 default:
3041 usage_checkout();
3042 /* NOTREACHED */
3046 argc -= optind;
3047 argv += optind;
3049 if (argc == 1) {
3050 char *base, *dotgit;
3051 const char *path;
3052 repo_path = realpath(argv[0], NULL);
3053 if (repo_path == NULL)
3054 return got_error_from_errno2("realpath", argv[0]);
3055 cwd = getcwd(NULL, 0);
3056 if (cwd == NULL) {
3057 error = got_error_from_errno("getcwd");
3058 goto done;
3060 if (path_prefix[0])
3061 path = path_prefix;
3062 else
3063 path = repo_path;
3064 error = got_path_basename(&base, path);
3065 if (error)
3066 goto done;
3067 dotgit = strstr(base, ".git");
3068 if (dotgit)
3069 *dotgit = '\0';
3070 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3071 error = got_error_from_errno("asprintf");
3072 free(base);
3073 goto done;
3075 free(base);
3076 } else if (argc == 2) {
3077 repo_path = realpath(argv[0], NULL);
3078 if (repo_path == NULL) {
3079 error = got_error_from_errno2("realpath", argv[0]);
3080 goto done;
3082 worktree_path = realpath(argv[1], NULL);
3083 if (worktree_path == NULL) {
3084 if (errno != ENOENT) {
3085 error = got_error_from_errno2("realpath",
3086 argv[1]);
3087 goto done;
3089 worktree_path = strdup(argv[1]);
3090 if (worktree_path == NULL) {
3091 error = got_error_from_errno("strdup");
3092 goto done;
3095 } else
3096 usage_checkout();
3098 got_path_strip_trailing_slashes(repo_path);
3099 got_path_strip_trailing_slashes(worktree_path);
3101 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3102 got_path_is_child(repo_path, worktree_path,
3103 strlen(worktree_path))) {
3104 error = got_error_fmt(GOT_ERR_BAD_PATH,
3105 "work tree and repository paths may not overlap: %s",
3106 worktree_path);
3107 goto done;
3110 error = got_repo_pack_fds_open(&pack_fds);
3111 if (error != NULL)
3112 goto done;
3114 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3115 if (error != NULL)
3116 goto done;
3118 /* Pre-create work tree path for unveil(2) */
3119 error = got_path_mkdir(worktree_path);
3120 if (error) {
3121 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3122 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3123 goto done;
3124 if (!allow_nonempty &&
3125 !got_path_dir_is_empty(worktree_path)) {
3126 error = got_error_path(worktree_path,
3127 GOT_ERR_DIR_NOT_EMPTY);
3128 goto done;
3132 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3133 if (error)
3134 goto done;
3136 error = got_ref_open(&head_ref, repo, branch_name, 0);
3137 if (error != NULL)
3138 goto done;
3140 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3141 GOT_WORKTREE_GOT_DIR, repo);
3142 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3143 goto done;
3145 error = got_worktree_open(&worktree, worktree_path,
3146 GOT_WORKTREE_GOT_DIR);
3147 if (error != NULL)
3148 goto done;
3150 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3151 path_prefix);
3152 if (error != NULL)
3153 goto done;
3154 if (!same_path_prefix) {
3155 error = got_error(GOT_ERR_PATH_PREFIX);
3156 goto done;
3159 if (commit_id_str) {
3160 struct got_reflist_head refs;
3161 TAILQ_INIT(&refs);
3162 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3163 NULL);
3164 if (error)
3165 goto done;
3167 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3168 repo, worktree);
3169 if (error != NULL)
3170 goto done;
3171 if (keyword_idstr != NULL) {
3172 free(commit_id_str);
3173 commit_id_str = keyword_idstr;
3176 error = got_repo_match_object_id(&commit_id, NULL,
3177 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3178 got_ref_list_free(&refs);
3179 if (error)
3180 goto done;
3181 error = check_linear_ancestry(commit_id,
3182 got_worktree_get_base_commit_id(worktree), 0, repo);
3183 if (error != NULL) {
3184 if (error->code == GOT_ERR_ANCESTRY) {
3185 error = checkout_ancestry_error(
3186 head_ref, commit_id_str);
3188 goto done;
3190 error = check_same_branch(commit_id, head_ref, repo);
3191 if (error) {
3192 if (error->code == GOT_ERR_ANCESTRY) {
3193 error = checkout_ancestry_error(
3194 head_ref, commit_id_str);
3196 goto done;
3198 error = got_worktree_set_base_commit_id(worktree, repo,
3199 commit_id);
3200 if (error)
3201 goto done;
3202 /* Expand potentially abbreviated commit ID string. */
3203 free(commit_id_str);
3204 error = got_object_id_str(&commit_id_str, commit_id);
3205 if (error)
3206 goto done;
3207 } else {
3208 commit_id = got_object_id_dup(
3209 got_worktree_get_base_commit_id(worktree));
3210 if (commit_id == NULL) {
3211 error = got_error_from_errno("got_object_id_dup");
3212 goto done;
3214 error = got_object_id_str(&commit_id_str, commit_id);
3215 if (error)
3216 goto done;
3219 error = got_pathlist_append(&paths, "", NULL);
3220 if (error)
3221 goto done;
3222 cpa.worktree_path = worktree_path;
3223 cpa.had_base_commit_ref_error = 0;
3224 cpa.verbosity = verbosity;
3225 error = got_worktree_checkout_files(worktree, &paths, repo,
3226 checkout_progress, &cpa, check_cancelled, NULL);
3227 if (error != NULL)
3228 goto done;
3230 if (got_ref_is_symbolic(head_ref)) {
3231 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3232 if (error)
3233 goto done;
3234 refname = got_ref_get_name(ref);
3235 } else
3236 refname = got_ref_get_name(head_ref);
3237 printf("Checked out %s: %s\n", refname, commit_id_str);
3238 printf("Now shut up and hack\n");
3239 if (cpa.had_base_commit_ref_error)
3240 show_worktree_base_ref_warning();
3241 done:
3242 if (pack_fds) {
3243 const struct got_error *pack_err =
3244 got_repo_pack_fds_close(pack_fds);
3245 if (error == NULL)
3246 error = pack_err;
3248 if (head_ref)
3249 got_ref_close(head_ref);
3250 if (ref)
3251 got_ref_close(ref);
3252 if (repo) {
3253 const struct got_error *close_err = got_repo_close(repo);
3254 if (error == NULL)
3255 error = close_err;
3257 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3258 free(commit_id_str);
3259 free(commit_id);
3260 free(repo_path);
3261 free(worktree_path);
3262 free(cwd);
3263 return error;
3266 struct got_update_progress_arg {
3267 int did_something;
3268 int conflicts;
3269 int obstructed;
3270 int not_updated;
3271 int missing;
3272 int not_deleted;
3273 int unversioned;
3274 int verbosity;
3277 static void
3278 print_update_progress_stats(struct got_update_progress_arg *upa)
3280 if (!upa->did_something)
3281 return;
3283 if (upa->conflicts > 0)
3284 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3285 if (upa->obstructed > 0)
3286 printf("File paths obstructed by a non-regular file: %d\n",
3287 upa->obstructed);
3288 if (upa->not_updated > 0)
3289 printf("Files not updated because of existing merge "
3290 "conflicts: %d\n", upa->not_updated);
3294 * The meaning of some status codes differs between merge-style operations and
3295 * update operations. For example, the ! status code means "file was missing"
3296 * if changes were merged into the work tree, and "missing file was restored"
3297 * if the work tree was updated. This function should be used by any operation
3298 * which merges changes into the work tree without updating the work tree.
3300 static void
3301 print_merge_progress_stats(struct got_update_progress_arg *upa)
3303 if (!upa->did_something)
3304 return;
3306 if (upa->conflicts > 0)
3307 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3308 if (upa->obstructed > 0)
3309 printf("File paths obstructed by a non-regular file: %d\n",
3310 upa->obstructed);
3311 if (upa->missing > 0)
3312 printf("Files which had incoming changes but could not be "
3313 "found in the work tree: %d\n", upa->missing);
3314 if (upa->not_deleted > 0)
3315 printf("Files not deleted due to differences in deleted "
3316 "content: %d\n", upa->not_deleted);
3317 if (upa->unversioned > 0)
3318 printf("Files not merged because an unversioned file was "
3319 "found in the work tree: %d\n", upa->unversioned);
3322 __dead static void
3323 usage_update(void)
3325 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3326 "[path ...]\n", getprogname());
3327 exit(1);
3330 static const struct got_error *
3331 update_progress(void *arg, unsigned char status, const char *path)
3333 struct got_update_progress_arg *upa = arg;
3335 if (status == GOT_STATUS_EXISTS ||
3336 status == GOT_STATUS_BASE_REF_ERR)
3337 return NULL;
3339 upa->did_something = 1;
3341 /* Base commit bump happens silently. */
3342 if (status == GOT_STATUS_BUMP_BASE)
3343 return NULL;
3345 if (status == GOT_STATUS_CONFLICT)
3346 upa->conflicts++;
3347 if (status == GOT_STATUS_OBSTRUCTED)
3348 upa->obstructed++;
3349 if (status == GOT_STATUS_CANNOT_UPDATE)
3350 upa->not_updated++;
3351 if (status == GOT_STATUS_MISSING)
3352 upa->missing++;
3353 if (status == GOT_STATUS_CANNOT_DELETE)
3354 upa->not_deleted++;
3355 if (status == GOT_STATUS_UNVERSIONED)
3356 upa->unversioned++;
3358 while (path[0] == '/')
3359 path++;
3360 if (upa->verbosity >= 0)
3361 printf("%c %s\n", status, path);
3363 return NULL;
3366 static const struct got_error *
3367 switch_head_ref(struct got_reference *head_ref,
3368 struct got_object_id *commit_id, struct got_worktree *worktree,
3369 struct got_repository *repo)
3371 const struct got_error *err = NULL;
3372 char *base_id_str;
3373 int ref_has_moved = 0;
3375 /* Trivial case: switching between two different references. */
3376 if (strcmp(got_ref_get_name(head_ref),
3377 got_worktree_get_head_ref_name(worktree)) != 0) {
3378 printf("Switching work tree from %s to %s\n",
3379 got_worktree_get_head_ref_name(worktree),
3380 got_ref_get_name(head_ref));
3381 return got_worktree_set_head_ref(worktree, head_ref);
3384 err = check_linear_ancestry(commit_id,
3385 got_worktree_get_base_commit_id(worktree), 0, repo);
3386 if (err) {
3387 if (err->code != GOT_ERR_ANCESTRY)
3388 return err;
3389 ref_has_moved = 1;
3391 if (!ref_has_moved)
3392 return NULL;
3394 /* Switching to a rebased branch with the same reference name. */
3395 err = got_object_id_str(&base_id_str,
3396 got_worktree_get_base_commit_id(worktree));
3397 if (err)
3398 return err;
3399 printf("Reference %s now points at a different branch\n",
3400 got_worktree_get_head_ref_name(worktree));
3401 printf("Switching work tree from %s to %s\n", base_id_str,
3402 got_worktree_get_head_ref_name(worktree));
3403 return NULL;
3406 static const struct got_error *
3407 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3409 const struct got_error *err;
3410 int in_progress;
3412 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3413 if (err)
3414 return err;
3415 if (in_progress)
3416 return got_error(GOT_ERR_REBASING);
3418 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3419 if (err)
3420 return err;
3421 if (in_progress)
3422 return got_error(GOT_ERR_HISTEDIT_BUSY);
3424 return NULL;
3427 static const struct got_error *
3428 check_merge_in_progress(struct got_worktree *worktree,
3429 struct got_repository *repo)
3431 const struct got_error *err;
3432 int in_progress;
3434 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3435 if (err)
3436 return err;
3437 if (in_progress)
3438 return got_error(GOT_ERR_MERGE_BUSY);
3440 return NULL;
3443 static const struct got_error *
3444 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3445 char *argv[], struct got_worktree *worktree)
3447 const struct got_error *err = NULL;
3448 char *path;
3449 struct got_pathlist_entry *new;
3450 int i;
3452 if (argc == 0) {
3453 path = strdup("");
3454 if (path == NULL)
3455 return got_error_from_errno("strdup");
3456 return got_pathlist_append(paths, path, NULL);
3459 for (i = 0; i < argc; i++) {
3460 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3461 if (err)
3462 break;
3463 err = got_pathlist_insert(&new, paths, path, NULL);
3464 if (err || new == NULL /* duplicate */) {
3465 free(path);
3466 if (err)
3467 break;
3471 return err;
3474 static const struct got_error *
3475 wrap_not_worktree_error(const struct got_error *orig_err,
3476 const char *cmdname, const char *path)
3478 const struct got_error *err;
3479 struct got_repository *repo;
3480 static char msg[512];
3481 int *pack_fds = NULL;
3483 err = got_repo_pack_fds_open(&pack_fds);
3484 if (err)
3485 return err;
3487 err = got_repo_open(&repo, path, NULL, pack_fds);
3488 if (err)
3489 return orig_err;
3491 snprintf(msg, sizeof(msg),
3492 "'got %s' needs a work tree in addition to a git repository\n"
3493 "Work trees can be checked out from this Git repository with "
3494 "'got checkout'.\n"
3495 "The got(1) manual page contains more information.", cmdname);
3496 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3497 if (repo) {
3498 const struct got_error *close_err = got_repo_close(repo);
3499 if (err == NULL)
3500 err = close_err;
3502 if (pack_fds) {
3503 const struct got_error *pack_err =
3504 got_repo_pack_fds_close(pack_fds);
3505 if (err == NULL)
3506 err = pack_err;
3508 return err;
3511 static const struct got_error *
3512 cmd_update(int argc, char *argv[])
3514 const struct got_error *error = NULL;
3515 struct got_repository *repo = NULL;
3516 struct got_worktree *worktree = NULL;
3517 char *worktree_path = NULL;
3518 struct got_object_id *commit_id = NULL;
3519 char *commit_id_str = NULL;
3520 const char *branch_name = NULL;
3521 struct got_reference *head_ref = NULL;
3522 struct got_pathlist_head paths;
3523 struct got_pathlist_entry *pe;
3524 int ch, verbosity = 0;
3525 struct got_update_progress_arg upa;
3526 int *pack_fds = NULL;
3528 TAILQ_INIT(&paths);
3530 #ifndef PROFILE
3531 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3532 "unveil", NULL) == -1)
3533 err(1, "pledge");
3534 #endif
3536 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3537 switch (ch) {
3538 case 'b':
3539 branch_name = optarg;
3540 break;
3541 case 'c':
3542 commit_id_str = strdup(optarg);
3543 if (commit_id_str == NULL)
3544 return got_error_from_errno("strdup");
3545 break;
3546 case 'q':
3547 verbosity = -1;
3548 break;
3549 default:
3550 usage_update();
3551 /* NOTREACHED */
3555 argc -= optind;
3556 argv += optind;
3558 worktree_path = getcwd(NULL, 0);
3559 if (worktree_path == NULL) {
3560 error = got_error_from_errno("getcwd");
3561 goto done;
3564 error = got_repo_pack_fds_open(&pack_fds);
3565 if (error != NULL)
3566 goto done;
3568 error = got_worktree_open(&worktree, worktree_path,
3569 GOT_WORKTREE_GOT_DIR);
3570 if (error) {
3571 if (error->code == GOT_ERR_NOT_WORKTREE)
3572 error = wrap_not_worktree_error(error, "update",
3573 worktree_path);
3574 goto done;
3577 error = check_rebase_or_histedit_in_progress(worktree);
3578 if (error)
3579 goto done;
3581 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3582 NULL, pack_fds);
3583 if (error != NULL)
3584 goto done;
3586 error = apply_unveil(got_repo_get_path(repo), 0,
3587 got_worktree_get_root_path(worktree));
3588 if (error)
3589 goto done;
3591 error = check_merge_in_progress(worktree, repo);
3592 if (error)
3593 goto done;
3595 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3596 if (error)
3597 goto done;
3599 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3600 got_worktree_get_head_ref_name(worktree), 0);
3601 if (error != NULL)
3602 goto done;
3603 if (commit_id_str == NULL) {
3604 error = got_ref_resolve(&commit_id, repo, head_ref);
3605 if (error != NULL)
3606 goto done;
3607 error = got_object_id_str(&commit_id_str, commit_id);
3608 if (error != NULL)
3609 goto done;
3610 } else {
3611 struct got_reflist_head refs;
3612 char *keyword_idstr = NULL;
3614 TAILQ_INIT(&refs);
3616 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3617 NULL);
3618 if (error)
3619 goto done;
3621 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3622 repo, worktree);
3623 if (error != NULL)
3624 goto done;
3625 if (keyword_idstr != NULL) {
3626 free(commit_id_str);
3627 commit_id_str = keyword_idstr;
3630 error = got_repo_match_object_id(&commit_id, NULL,
3631 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3632 got_ref_list_free(&refs);
3633 free(commit_id_str);
3634 commit_id_str = NULL;
3635 if (error)
3636 goto done;
3637 error = got_object_id_str(&commit_id_str, commit_id);
3638 if (error)
3639 goto done;
3642 if (branch_name) {
3643 struct got_object_id *head_commit_id;
3644 TAILQ_FOREACH(pe, &paths, entry) {
3645 if (pe->path_len == 0)
3646 continue;
3647 error = got_error_msg(GOT_ERR_BAD_PATH,
3648 "switching between branches requires that "
3649 "the entire work tree gets updated");
3650 goto done;
3652 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3653 if (error)
3654 goto done;
3655 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3656 repo);
3657 free(head_commit_id);
3658 if (error != NULL)
3659 goto done;
3660 error = check_same_branch(commit_id, head_ref, repo);
3661 if (error)
3662 goto done;
3663 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3664 if (error)
3665 goto done;
3666 } else {
3667 error = check_linear_ancestry(commit_id,
3668 got_worktree_get_base_commit_id(worktree), 0, repo);
3669 if (error != NULL) {
3670 if (error->code == GOT_ERR_ANCESTRY)
3671 error = got_error(GOT_ERR_BRANCH_MOVED);
3672 goto done;
3674 error = check_same_branch(commit_id, head_ref, repo);
3675 if (error)
3676 goto done;
3679 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3680 commit_id) != 0) {
3681 error = got_worktree_set_base_commit_id(worktree, repo,
3682 commit_id);
3683 if (error)
3684 goto done;
3687 memset(&upa, 0, sizeof(upa));
3688 upa.verbosity = verbosity;
3689 error = got_worktree_checkout_files(worktree, &paths, repo,
3690 update_progress, &upa, check_cancelled, NULL);
3691 if (error != NULL)
3692 goto done;
3694 if (upa.did_something) {
3695 printf("Updated to %s: %s\n",
3696 got_worktree_get_head_ref_name(worktree), commit_id_str);
3697 } else
3698 printf("Already up-to-date\n");
3700 print_update_progress_stats(&upa);
3701 done:
3702 if (pack_fds) {
3703 const struct got_error *pack_err =
3704 got_repo_pack_fds_close(pack_fds);
3705 if (error == NULL)
3706 error = pack_err;
3708 if (repo) {
3709 const struct got_error *close_err = got_repo_close(repo);
3710 if (error == NULL)
3711 error = close_err;
3713 if (head_ref != NULL)
3714 got_ref_close(head_ref);
3715 free(worktree_path);
3716 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3717 free(commit_id);
3718 free(commit_id_str);
3719 return error;
3722 static const struct got_error *
3723 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3724 const char *path, int diff_context, int ignore_whitespace,
3725 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3726 struct got_repository *repo, FILE *outfile)
3728 const struct got_error *err = NULL;
3729 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3730 FILE *f1 = NULL, *f2 = NULL;
3731 int fd1 = -1, fd2 = -1;
3733 fd1 = got_opentempfd();
3734 if (fd1 == -1)
3735 return got_error_from_errno("got_opentempfd");
3736 fd2 = got_opentempfd();
3737 if (fd2 == -1) {
3738 err = got_error_from_errno("got_opentempfd");
3739 goto done;
3742 if (blob_id1) {
3743 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3744 fd1);
3745 if (err)
3746 goto done;
3749 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3750 if (err)
3751 goto done;
3753 f1 = got_opentemp();
3754 if (f1 == NULL) {
3755 err = got_error_from_errno("got_opentemp");
3756 goto done;
3758 f2 = got_opentemp();
3759 if (f2 == NULL) {
3760 err = got_error_from_errno("got_opentemp");
3761 goto done;
3764 while (path[0] == '/')
3765 path++;
3766 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3767 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3768 force_text_diff, dsa, outfile);
3769 done:
3770 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3771 err = got_error_from_errno("close");
3772 if (blob1)
3773 got_object_blob_close(blob1);
3774 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3775 err = got_error_from_errno("close");
3776 if (blob2)
3777 got_object_blob_close(blob2);
3778 if (f1 && fclose(f1) == EOF && err == NULL)
3779 err = got_error_from_errno("fclose");
3780 if (f2 && fclose(f2) == EOF && err == NULL)
3781 err = got_error_from_errno("fclose");
3782 return err;
3785 static const struct got_error *
3786 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3787 const char *path, int diff_context, int ignore_whitespace,
3788 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3789 struct got_repository *repo, FILE *outfile)
3791 const struct got_error *err = NULL;
3792 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3793 struct got_diff_blob_output_unidiff_arg arg;
3794 FILE *f1 = NULL, *f2 = NULL;
3795 int fd1 = -1, fd2 = -1;
3797 if (tree_id1) {
3798 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3799 if (err)
3800 goto done;
3801 fd1 = got_opentempfd();
3802 if (fd1 == -1) {
3803 err = got_error_from_errno("got_opentempfd");
3804 goto done;
3808 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3809 if (err)
3810 goto done;
3812 f1 = got_opentemp();
3813 if (f1 == NULL) {
3814 err = got_error_from_errno("got_opentemp");
3815 goto done;
3818 f2 = got_opentemp();
3819 if (f2 == NULL) {
3820 err = got_error_from_errno("got_opentemp");
3821 goto done;
3823 fd2 = got_opentempfd();
3824 if (fd2 == -1) {
3825 err = got_error_from_errno("got_opentempfd");
3826 goto done;
3828 arg.diff_context = diff_context;
3829 arg.ignore_whitespace = ignore_whitespace;
3830 arg.force_text_diff = force_text_diff;
3831 arg.diffstat = dsa;
3832 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3833 arg.outfile = outfile;
3834 arg.lines = NULL;
3835 arg.nlines = 0;
3836 while (path[0] == '/')
3837 path++;
3838 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3839 got_diff_blob_output_unidiff, &arg, 1);
3840 done:
3841 if (tree1)
3842 got_object_tree_close(tree1);
3843 if (tree2)
3844 got_object_tree_close(tree2);
3845 if (f1 && fclose(f1) == EOF && err == NULL)
3846 err = got_error_from_errno("fclose");
3847 if (f2 && fclose(f2) == EOF && err == NULL)
3848 err = got_error_from_errno("fclose");
3849 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3850 err = got_error_from_errno("close");
3851 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3852 err = got_error_from_errno("close");
3853 return err;
3856 static const struct got_error *
3857 get_changed_paths(struct got_pathlist_head *paths,
3858 struct got_commit_object *commit, struct got_repository *repo,
3859 struct got_diffstat_cb_arg *dsa)
3861 const struct got_error *err = NULL;
3862 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3863 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3864 struct got_object_qid *qid;
3865 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3866 FILE *f1 = NULL, *f2 = NULL;
3867 int fd1 = -1, fd2 = -1;
3869 if (dsa) {
3870 cb = got_diff_tree_compute_diffstat;
3872 f1 = got_opentemp();
3873 if (f1 == NULL) {
3874 err = got_error_from_errno("got_opentemp");
3875 goto done;
3877 f2 = got_opentemp();
3878 if (f2 == NULL) {
3879 err = got_error_from_errno("got_opentemp");
3880 goto done;
3882 fd1 = got_opentempfd();
3883 if (fd1 == -1) {
3884 err = got_error_from_errno("got_opentempfd");
3885 goto done;
3887 fd2 = got_opentempfd();
3888 if (fd2 == -1) {
3889 err = got_error_from_errno("got_opentempfd");
3890 goto done;
3894 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3895 if (qid != NULL) {
3896 struct got_commit_object *pcommit;
3897 err = got_object_open_as_commit(&pcommit, repo,
3898 &qid->id);
3899 if (err)
3900 return err;
3902 tree_id1 = got_object_id_dup(
3903 got_object_commit_get_tree_id(pcommit));
3904 if (tree_id1 == NULL) {
3905 got_object_commit_close(pcommit);
3906 return got_error_from_errno("got_object_id_dup");
3908 got_object_commit_close(pcommit);
3912 if (tree_id1) {
3913 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3914 if (err)
3915 goto done;
3918 tree_id2 = got_object_commit_get_tree_id(commit);
3919 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3920 if (err)
3921 goto done;
3923 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3924 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3925 done:
3926 if (tree1)
3927 got_object_tree_close(tree1);
3928 if (tree2)
3929 got_object_tree_close(tree2);
3930 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3931 err = got_error_from_errno("close");
3932 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3933 err = got_error_from_errno("close");
3934 if (f1 && fclose(f1) == EOF && err == NULL)
3935 err = got_error_from_errno("fclose");
3936 if (f2 && fclose(f2) == EOF && err == NULL)
3937 err = got_error_from_errno("fclose");
3938 free(tree_id1);
3939 return err;
3942 static const struct got_error *
3943 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3944 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3945 struct got_repository *repo, FILE *outfile)
3947 const struct got_error *err = NULL;
3948 struct got_commit_object *pcommit = NULL;
3949 char *id_str1 = NULL, *id_str2 = NULL;
3950 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3951 struct got_object_qid *qid;
3953 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3954 if (qid != NULL) {
3955 err = got_object_open_as_commit(&pcommit, repo,
3956 &qid->id);
3957 if (err)
3958 return err;
3959 err = got_object_id_str(&id_str1, &qid->id);
3960 if (err)
3961 goto done;
3964 err = got_object_id_str(&id_str2, id);
3965 if (err)
3966 goto done;
3968 if (path && path[0] != '\0') {
3969 int obj_type;
3970 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3971 if (err)
3972 goto done;
3973 if (pcommit) {
3974 err = got_object_id_by_path(&obj_id1, repo,
3975 pcommit, path);
3976 if (err) {
3977 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3978 free(obj_id2);
3979 goto done;
3983 err = got_object_get_type(&obj_type, repo, obj_id2);
3984 if (err) {
3985 free(obj_id2);
3986 goto done;
3988 fprintf(outfile,
3989 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3990 fprintf(outfile, "commit - %s\n",
3991 id_str1 ? id_str1 : "/dev/null");
3992 fprintf(outfile, "commit + %s\n", id_str2);
3993 switch (obj_type) {
3994 case GOT_OBJ_TYPE_BLOB:
3995 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3996 0, 0, dsa, repo, outfile);
3997 break;
3998 case GOT_OBJ_TYPE_TREE:
3999 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4000 0, 0, dsa, repo, outfile);
4001 break;
4002 default:
4003 err = got_error(GOT_ERR_OBJ_TYPE);
4004 break;
4006 free(obj_id1);
4007 free(obj_id2);
4008 } else {
4009 obj_id2 = got_object_commit_get_tree_id(commit);
4010 if (pcommit)
4011 obj_id1 = got_object_commit_get_tree_id(pcommit);
4012 fprintf(outfile,
4013 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4014 fprintf(outfile, "commit - %s\n",
4015 id_str1 ? id_str1 : "/dev/null");
4016 fprintf(outfile, "commit + %s\n", id_str2);
4017 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4018 dsa, repo, outfile);
4020 done:
4021 free(id_str1);
4022 free(id_str2);
4023 if (pcommit)
4024 got_object_commit_close(pcommit);
4025 return err;
4028 static char *
4029 get_datestr(time_t *time, char *datebuf)
4031 struct tm mytm, *tm;
4032 char *p, *s;
4034 tm = gmtime_r(time, &mytm);
4035 if (tm == NULL)
4036 return NULL;
4037 s = asctime_r(tm, datebuf);
4038 if (s == NULL)
4039 return NULL;
4040 p = strchr(s, '\n');
4041 if (p)
4042 *p = '\0';
4043 return s;
4046 static const struct got_error *
4047 match_commit(int *have_match, struct got_object_id *id,
4048 struct got_commit_object *commit, regex_t *regex)
4050 const struct got_error *err = NULL;
4051 regmatch_t regmatch;
4052 char *id_str = NULL, *logmsg = NULL;
4054 *have_match = 0;
4056 err = got_object_id_str(&id_str, id);
4057 if (err)
4058 return err;
4060 err = got_object_commit_get_logmsg(&logmsg, commit);
4061 if (err)
4062 goto done;
4064 if (regexec(regex, got_object_commit_get_author(commit), 1,
4065 &regmatch, 0) == 0 ||
4066 regexec(regex, got_object_commit_get_committer(commit), 1,
4067 &regmatch, 0) == 0 ||
4068 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4069 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4070 *have_match = 1;
4071 done:
4072 free(id_str);
4073 free(logmsg);
4074 return err;
4077 static void
4078 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4079 regex_t *regex)
4081 regmatch_t regmatch;
4082 struct got_pathlist_entry *pe;
4084 *have_match = 0;
4086 TAILQ_FOREACH(pe, changed_paths, entry) {
4087 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4088 *have_match = 1;
4089 break;
4094 static const struct got_error *
4095 match_patch(int *have_match, struct got_commit_object *commit,
4096 struct got_object_id *id, const char *path, int diff_context,
4097 struct got_repository *repo, regex_t *regex, FILE *f)
4099 const struct got_error *err = NULL;
4100 char *line = NULL;
4101 size_t linesize = 0;
4102 regmatch_t regmatch;
4104 *have_match = 0;
4106 err = got_opentemp_truncate(f);
4107 if (err)
4108 return err;
4110 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4111 if (err)
4112 goto done;
4114 if (fseeko(f, 0L, SEEK_SET) == -1) {
4115 err = got_error_from_errno("fseeko");
4116 goto done;
4119 while (getline(&line, &linesize, f) != -1) {
4120 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4121 *have_match = 1;
4122 break;
4125 done:
4126 free(line);
4127 return err;
4130 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4132 static const struct got_error*
4133 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4134 struct got_object_id *id, struct got_repository *repo,
4135 int local_only)
4137 static const struct got_error *err = NULL;
4138 struct got_reflist_entry *re;
4139 char *s;
4140 const char *name;
4142 *refs_str = NULL;
4144 TAILQ_FOREACH(re, refs, entry) {
4145 struct got_tag_object *tag = NULL;
4146 struct got_object_id *ref_id;
4147 int cmp;
4149 name = got_ref_get_name(re->ref);
4150 if (strcmp(name, GOT_REF_HEAD) == 0)
4151 continue;
4152 if (strncmp(name, "refs/", 5) == 0)
4153 name += 5;
4154 if (strncmp(name, "got/", 4) == 0)
4155 continue;
4156 if (strncmp(name, "heads/", 6) == 0)
4157 name += 6;
4158 if (strncmp(name, "remotes/", 8) == 0) {
4159 if (local_only)
4160 continue;
4161 name += 8;
4162 s = strstr(name, "/" GOT_REF_HEAD);
4163 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4164 continue;
4166 err = got_ref_resolve(&ref_id, repo, re->ref);
4167 if (err)
4168 break;
4169 if (strncmp(name, "tags/", 5) == 0) {
4170 err = got_object_open_as_tag(&tag, repo, ref_id);
4171 if (err) {
4172 if (err->code != GOT_ERR_OBJ_TYPE) {
4173 free(ref_id);
4174 break;
4176 /* Ref points at something other than a tag. */
4177 err = NULL;
4178 tag = NULL;
4181 cmp = got_object_id_cmp(tag ?
4182 got_object_tag_get_object_id(tag) : ref_id, id);
4183 free(ref_id);
4184 if (tag)
4185 got_object_tag_close(tag);
4186 if (cmp != 0)
4187 continue;
4188 s = *refs_str;
4189 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4190 s ? ", " : "", name) == -1) {
4191 err = got_error_from_errno("asprintf");
4192 free(s);
4193 *refs_str = NULL;
4194 break;
4196 free(s);
4199 return err;
4202 static const struct got_error *
4203 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4204 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4206 const struct got_error *err = NULL;
4207 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4208 char *comma, *s, *nl;
4209 struct got_reflist_head *refs;
4210 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4211 struct tm tm;
4212 time_t committer_time;
4214 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4215 if (refs) {
4216 err = build_refs_str(&ref_str, refs, id, repo, 1);
4217 if (err)
4218 return err;
4220 /* Display the first matching ref only. */
4221 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4222 *comma = '\0';
4225 if (ref_str == NULL) {
4226 err = got_object_id_str(&id_str, id);
4227 if (err)
4228 return err;
4231 committer_time = got_object_commit_get_committer_time(commit);
4232 if (gmtime_r(&committer_time, &tm) == NULL) {
4233 err = got_error_from_errno("gmtime_r");
4234 goto done;
4236 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4237 err = got_error(GOT_ERR_NO_SPACE);
4238 goto done;
4241 err = got_object_commit_get_logmsg(&logmsg0, commit);
4242 if (err)
4243 goto done;
4245 s = logmsg0;
4246 while (isspace((unsigned char)s[0]))
4247 s++;
4249 nl = strchr(s, '\n');
4250 if (nl) {
4251 *nl = '\0';
4254 if (ref_str)
4255 printf("%s%-7s %s\n", datebuf, ref_str, s);
4256 else
4257 printf("%s%.7s %s\n", datebuf, id_str, s);
4259 if (fflush(stdout) != 0 && err == NULL)
4260 err = got_error_from_errno("fflush");
4261 done:
4262 free(id_str);
4263 free(ref_str);
4264 free(logmsg0);
4265 return err;
4268 static const struct got_error *
4269 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4271 struct got_pathlist_entry *pe;
4273 if (header != NULL)
4274 printf("%s\n", header);
4276 TAILQ_FOREACH(pe, dsa->paths, entry) {
4277 struct got_diff_changed_path *cp = pe->data;
4278 int pad = dsa->max_path_len - pe->path_len + 1;
4280 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4281 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4283 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4284 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4285 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4287 if (fflush(stdout) != 0)
4288 return got_error_from_errno("fflush");
4290 return NULL;
4293 static const struct got_error *
4294 printfile(FILE *f)
4296 char buf[8192];
4297 size_t r;
4299 if (fseeko(f, 0L, SEEK_SET) == -1)
4300 return got_error_from_errno("fseek");
4302 for (;;) {
4303 r = fread(buf, 1, sizeof(buf), f);
4304 if (r == 0) {
4305 if (ferror(f))
4306 return got_error_from_errno("fread");
4307 if (feof(f))
4308 break;
4310 if (fwrite(buf, 1, r, stdout) != r)
4311 return got_ferror(stdout, GOT_ERR_IO);
4314 return NULL;
4317 static const struct got_error *
4318 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4319 struct got_repository *repo, const char *path,
4320 struct got_pathlist_head *changed_paths,
4321 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4322 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4323 const char *prefix)
4325 const struct got_error *err = NULL;
4326 FILE *f = NULL;
4327 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4328 char datebuf[26];
4329 time_t committer_time;
4330 const char *author, *committer;
4331 char *refs_str = NULL;
4333 err = got_object_id_str(&id_str, id);
4334 if (err)
4335 return err;
4337 if (custom_refs_str == NULL) {
4338 struct got_reflist_head *refs;
4339 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4340 if (refs) {
4341 err = build_refs_str(&refs_str, refs, id, repo, 0);
4342 if (err)
4343 goto done;
4347 printf(GOT_COMMIT_SEP_STR);
4348 if (custom_refs_str)
4349 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4350 custom_refs_str);
4351 else
4352 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4353 refs_str ? " (" : "", refs_str ? refs_str : "",
4354 refs_str ? ")" : "");
4355 free(id_str);
4356 id_str = NULL;
4357 free(refs_str);
4358 refs_str = NULL;
4359 printf("from: %s\n", got_object_commit_get_author(commit));
4360 author = got_object_commit_get_author(commit);
4361 committer = got_object_commit_get_committer(commit);
4362 if (strcmp(author, committer) != 0)
4363 printf("via: %s\n", committer);
4364 committer_time = got_object_commit_get_committer_time(commit);
4365 datestr = get_datestr(&committer_time, datebuf);
4366 if (datestr)
4367 printf("date: %s UTC\n", datestr);
4368 if (got_object_commit_get_nparents(commit) > 1) {
4369 const struct got_object_id_queue *parent_ids;
4370 struct got_object_qid *qid;
4371 int n = 1;
4372 parent_ids = got_object_commit_get_parent_ids(commit);
4373 STAILQ_FOREACH(qid, parent_ids, entry) {
4374 err = got_object_id_str(&id_str, &qid->id);
4375 if (err)
4376 goto done;
4377 printf("parent %d: %s\n", n++, id_str);
4378 free(id_str);
4379 id_str = NULL;
4383 err = got_object_commit_get_logmsg(&logmsg0, commit);
4384 if (err)
4385 goto done;
4387 logmsg = logmsg0;
4388 do {
4389 line = strsep(&logmsg, "\n");
4390 if (line)
4391 printf(" %s\n", line);
4392 } while (line);
4393 free(logmsg0);
4395 if (changed_paths && diffstat == NULL) {
4396 struct got_pathlist_entry *pe;
4398 TAILQ_FOREACH(pe, changed_paths, entry) {
4399 struct got_diff_changed_path *cp = pe->data;
4401 printf(" %c %s\n", cp->status, pe->path);
4403 printf("\n");
4405 if (show_patch) {
4406 if (diffstat) {
4407 f = got_opentemp();
4408 if (f == NULL) {
4409 err = got_error_from_errno("got_opentemp");
4410 goto done;
4414 err = print_patch(commit, id, path, diff_context, diffstat,
4415 repo, diffstat == NULL ? stdout : f);
4416 if (err)
4417 goto done;
4419 if (diffstat) {
4420 err = print_diffstat(diffstat, NULL);
4421 if (err)
4422 goto done;
4423 if (show_patch) {
4424 err = printfile(f);
4425 if (err)
4426 goto done;
4429 if (show_patch)
4430 printf("\n");
4432 if (fflush(stdout) != 0 && err == NULL)
4433 err = got_error_from_errno("fflush");
4434 done:
4435 if (f && fclose(f) == EOF && err == NULL)
4436 err = got_error_from_errno("fclose");
4437 free(id_str);
4438 free(refs_str);
4439 return err;
4442 static const struct got_error *
4443 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4444 struct got_repository *repo, const char *path, int show_changed_paths,
4445 int show_diffstat, int show_patch, const char *search_pattern,
4446 int diff_context, int limit, int log_branches, int reverse_display_order,
4447 struct got_reflist_object_id_map *refs_idmap, int one_line,
4448 FILE *tmpfile)
4450 const struct got_error *err;
4451 struct got_commit_graph *graph;
4452 regex_t regex;
4453 int have_match;
4454 struct got_object_id_queue reversed_commits;
4455 struct got_object_qid *qid;
4456 struct got_commit_object *commit;
4457 struct got_pathlist_head changed_paths;
4459 STAILQ_INIT(&reversed_commits);
4460 TAILQ_INIT(&changed_paths);
4462 if (search_pattern && regcomp(&regex, search_pattern,
4463 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4464 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4466 err = got_commit_graph_open(&graph, path, !log_branches);
4467 if (err)
4468 return err;
4469 err = got_commit_graph_iter_start(graph, root_id, repo,
4470 check_cancelled, NULL);
4471 if (err)
4472 goto done;
4473 for (;;) {
4474 struct got_object_id id;
4475 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4476 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4478 if (sigint_received || sigpipe_received)
4479 break;
4481 err = got_commit_graph_iter_next(&id, graph, repo,
4482 check_cancelled, NULL);
4483 if (err) {
4484 if (err->code == GOT_ERR_ITER_COMPLETED)
4485 err = NULL;
4486 break;
4489 err = got_object_open_as_commit(&commit, repo, &id);
4490 if (err)
4491 break;
4493 if (((show_changed_paths && !show_diffstat) ||
4494 (show_diffstat && !show_patch))
4495 && !reverse_display_order) {
4496 err = get_changed_paths(&changed_paths, commit, repo,
4497 show_diffstat ? &dsa : NULL);
4498 if (err)
4499 break;
4502 if (search_pattern) {
4503 err = match_commit(&have_match, &id, commit, &regex);
4504 if (err) {
4505 got_object_commit_close(commit);
4506 break;
4508 if (have_match == 0 && show_changed_paths)
4509 match_changed_paths(&have_match,
4510 &changed_paths, &regex);
4511 if (have_match == 0 && show_patch) {
4512 err = match_patch(&have_match, commit, &id,
4513 path, diff_context, repo, &regex, tmpfile);
4514 if (err)
4515 break;
4517 if (have_match == 0) {
4518 got_object_commit_close(commit);
4519 got_pathlist_free(&changed_paths,
4520 GOT_PATHLIST_FREE_ALL);
4521 continue;
4525 if (reverse_display_order) {
4526 err = got_object_qid_alloc(&qid, &id);
4527 if (err)
4528 break;
4529 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4530 got_object_commit_close(commit);
4531 } else {
4532 if (one_line)
4533 err = print_commit_oneline(commit, &id,
4534 repo, refs_idmap);
4535 else
4536 err = print_commit(commit, &id, repo, path,
4537 (show_changed_paths || show_diffstat) ?
4538 &changed_paths : NULL,
4539 show_diffstat ? &dsa : NULL, show_patch,
4540 diff_context, refs_idmap, NULL, NULL);
4541 got_object_commit_close(commit);
4542 if (err)
4543 break;
4545 if ((limit && --limit == 0) ||
4546 (end_id && got_object_id_cmp(&id, end_id) == 0))
4547 break;
4549 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4551 if (reverse_display_order) {
4552 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4553 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4554 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4556 err = got_object_open_as_commit(&commit, repo,
4557 &qid->id);
4558 if (err)
4559 break;
4560 if ((show_changed_paths && !show_diffstat) ||
4561 (show_diffstat && !show_patch)) {
4562 err = get_changed_paths(&changed_paths, commit,
4563 repo, show_diffstat ? &dsa : NULL);
4564 if (err)
4565 break;
4567 if (one_line)
4568 err = print_commit_oneline(commit, &qid->id,
4569 repo, refs_idmap);
4570 else
4571 err = print_commit(commit, &qid->id, repo, path,
4572 (show_changed_paths || show_diffstat) ?
4573 &changed_paths : NULL,
4574 show_diffstat ? &dsa : NULL, show_patch,
4575 diff_context, refs_idmap, NULL, NULL);
4576 got_object_commit_close(commit);
4577 if (err)
4578 break;
4579 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4582 done:
4583 while (!STAILQ_EMPTY(&reversed_commits)) {
4584 qid = STAILQ_FIRST(&reversed_commits);
4585 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4586 got_object_qid_free(qid);
4588 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4589 if (search_pattern)
4590 regfree(&regex);
4591 got_commit_graph_close(graph);
4592 return err;
4595 __dead static void
4596 usage_log(void)
4598 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4599 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4600 "[path]\n", getprogname());
4601 exit(1);
4604 static int
4605 get_default_log_limit(void)
4607 const char *got_default_log_limit;
4608 long long n;
4609 const char *errstr;
4611 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4612 if (got_default_log_limit == NULL)
4613 return 0;
4614 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4615 if (errstr != NULL)
4616 return 0;
4617 return n;
4620 static const struct got_error *
4621 cmd_log(int argc, char *argv[])
4623 const struct got_error *error;
4624 struct got_repository *repo = NULL;
4625 struct got_worktree *worktree = NULL;
4626 struct got_object_id *start_id = NULL, *end_id = NULL;
4627 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4628 char *keyword_idstr = NULL;
4629 const char *start_commit = NULL, *end_commit = NULL;
4630 const char *search_pattern = NULL;
4631 int diff_context = -1, ch;
4632 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4633 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4634 const char *errstr;
4635 struct got_reflist_head refs;
4636 struct got_reflist_object_id_map *refs_idmap = NULL;
4637 FILE *tmpfile = NULL;
4638 int *pack_fds = NULL;
4640 TAILQ_INIT(&refs);
4642 #ifndef PROFILE
4643 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4644 NULL)
4645 == -1)
4646 err(1, "pledge");
4647 #endif
4649 limit = get_default_log_limit();
4651 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4652 switch (ch) {
4653 case 'b':
4654 log_branches = 1;
4655 break;
4656 case 'C':
4657 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4658 &errstr);
4659 if (errstr != NULL)
4660 errx(1, "number of context lines is %s: %s",
4661 errstr, optarg);
4662 break;
4663 case 'c':
4664 start_commit = optarg;
4665 break;
4666 case 'd':
4667 show_diffstat = 1;
4668 break;
4669 case 'l':
4670 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4671 if (errstr != NULL)
4672 errx(1, "number of commits is %s: %s",
4673 errstr, optarg);
4674 break;
4675 case 'P':
4676 show_changed_paths = 1;
4677 break;
4678 case 'p':
4679 show_patch = 1;
4680 break;
4681 case 'R':
4682 reverse_display_order = 1;
4683 break;
4684 case 'r':
4685 repo_path = realpath(optarg, NULL);
4686 if (repo_path == NULL)
4687 return got_error_from_errno2("realpath",
4688 optarg);
4689 got_path_strip_trailing_slashes(repo_path);
4690 break;
4691 case 'S':
4692 search_pattern = optarg;
4693 break;
4694 case 's':
4695 one_line = 1;
4696 break;
4697 case 'x':
4698 end_commit = optarg;
4699 break;
4700 default:
4701 usage_log();
4702 /* NOTREACHED */
4706 argc -= optind;
4707 argv += optind;
4709 if (diff_context == -1)
4710 diff_context = 3;
4711 else if (!show_patch)
4712 errx(1, "-C requires -p");
4714 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4715 errx(1, "cannot use -s with -d, -p or -P");
4717 cwd = getcwd(NULL, 0);
4718 if (cwd == NULL) {
4719 error = got_error_from_errno("getcwd");
4720 goto done;
4723 error = got_repo_pack_fds_open(&pack_fds);
4724 if (error != NULL)
4725 goto done;
4727 if (repo_path == NULL) {
4728 error = got_worktree_open(&worktree, cwd,
4729 GOT_WORKTREE_GOT_DIR);
4730 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4731 goto done;
4732 error = NULL;
4735 if (argc == 1) {
4736 if (worktree) {
4737 error = got_worktree_resolve_path(&path, worktree,
4738 argv[0]);
4739 if (error)
4740 goto done;
4741 } else {
4742 path = strdup(argv[0]);
4743 if (path == NULL) {
4744 error = got_error_from_errno("strdup");
4745 goto done;
4748 } else if (argc != 0)
4749 usage_log();
4751 if (repo_path == NULL) {
4752 repo_path = worktree ?
4753 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4755 if (repo_path == NULL) {
4756 error = got_error_from_errno("strdup");
4757 goto done;
4760 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4761 if (error != NULL)
4762 goto done;
4764 error = apply_unveil(got_repo_get_path(repo), 1,
4765 worktree ? got_worktree_get_root_path(worktree) : NULL);
4766 if (error)
4767 goto done;
4769 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4770 if (error)
4771 goto done;
4773 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4774 if (error)
4775 goto done;
4777 if (start_commit == NULL) {
4778 struct got_reference *head_ref;
4779 struct got_commit_object *commit = NULL;
4780 error = got_ref_open(&head_ref, repo,
4781 worktree ? got_worktree_get_head_ref_name(worktree)
4782 : GOT_REF_HEAD, 0);
4783 if (error != NULL)
4784 goto done;
4785 error = got_ref_resolve(&start_id, repo, head_ref);
4786 got_ref_close(head_ref);
4787 if (error != NULL)
4788 goto done;
4789 error = got_object_open_as_commit(&commit, repo,
4790 start_id);
4791 if (error != NULL)
4792 goto done;
4793 got_object_commit_close(commit);
4794 } else {
4795 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4796 repo, worktree);
4797 if (error != NULL)
4798 goto done;
4799 if (keyword_idstr != NULL)
4800 start_commit = keyword_idstr;
4802 error = got_repo_match_object_id(&start_id, NULL,
4803 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4804 if (error != NULL)
4805 goto done;
4807 if (end_commit != NULL) {
4808 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4809 repo, worktree);
4810 if (error != NULL)
4811 goto done;
4812 if (keyword_idstr != NULL)
4813 end_commit = keyword_idstr;
4815 error = got_repo_match_object_id(&end_id, NULL,
4816 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4817 if (error != NULL)
4818 goto done;
4821 if (worktree) {
4823 * If a path was specified on the command line it was resolved
4824 * to a path in the work tree above. Prepend the work tree's
4825 * path prefix to obtain the corresponding in-repository path.
4827 if (path) {
4828 const char *prefix;
4829 prefix = got_worktree_get_path_prefix(worktree);
4830 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4831 (path[0] != '\0') ? "/" : "", path) == -1) {
4832 error = got_error_from_errno("asprintf");
4833 goto done;
4836 } else
4837 error = got_repo_map_path(&in_repo_path, repo,
4838 path ? path : "");
4839 if (error != NULL)
4840 goto done;
4841 if (in_repo_path) {
4842 free(path);
4843 path = in_repo_path;
4846 if (worktree) {
4847 /* Release work tree lock. */
4848 got_worktree_close(worktree);
4849 worktree = NULL;
4852 if (search_pattern && show_patch) {
4853 tmpfile = got_opentemp();
4854 if (tmpfile == NULL) {
4855 error = got_error_from_errno("got_opentemp");
4856 goto done;
4860 error = print_commits(start_id, end_id, repo, path ? path : "",
4861 show_changed_paths, show_diffstat, show_patch, search_pattern,
4862 diff_context, limit, log_branches, reverse_display_order,
4863 refs_idmap, one_line, tmpfile);
4864 done:
4865 free(path);
4866 free(repo_path);
4867 free(cwd);
4868 free(start_id);
4869 free(end_id);
4870 free(keyword_idstr);
4871 if (worktree)
4872 got_worktree_close(worktree);
4873 if (repo) {
4874 const struct got_error *close_err = got_repo_close(repo);
4875 if (error == NULL)
4876 error = close_err;
4878 if (pack_fds) {
4879 const struct got_error *pack_err =
4880 got_repo_pack_fds_close(pack_fds);
4881 if (error == NULL)
4882 error = pack_err;
4884 if (refs_idmap)
4885 got_reflist_object_id_map_free(refs_idmap);
4886 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4887 error = got_error_from_errno("fclose");
4888 got_ref_list_free(&refs);
4889 return error;
4892 __dead static void
4893 usage_diff(void)
4895 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4896 "[-r repository-path] [object1 object2 | path ...]\n",
4897 getprogname());
4898 exit(1);
4901 struct print_diff_arg {
4902 struct got_repository *repo;
4903 struct got_worktree *worktree;
4904 struct got_diffstat_cb_arg *diffstat;
4905 int diff_context;
4906 const char *id_str;
4907 int header_shown;
4908 int diff_staged;
4909 enum got_diff_algorithm diff_algo;
4910 int ignore_whitespace;
4911 int force_text_diff;
4912 FILE *f1;
4913 FILE *f2;
4914 FILE *outfile;
4918 * Create a file which contains the target path of a symlink so we can feed
4919 * it as content to the diff engine.
4921 static const struct got_error *
4922 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4923 const char *abspath)
4925 const struct got_error *err = NULL;
4926 char target_path[PATH_MAX];
4927 ssize_t target_len, outlen;
4929 *fd = -1;
4931 if (dirfd != -1) {
4932 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4933 if (target_len == -1)
4934 return got_error_from_errno2("readlinkat", abspath);
4935 } else {
4936 target_len = readlink(abspath, target_path, PATH_MAX);
4937 if (target_len == -1)
4938 return got_error_from_errno2("readlink", abspath);
4941 *fd = got_opentempfd();
4942 if (*fd == -1)
4943 return got_error_from_errno("got_opentempfd");
4945 outlen = write(*fd, target_path, target_len);
4946 if (outlen == -1) {
4947 err = got_error_from_errno("got_opentempfd");
4948 goto done;
4951 if (lseek(*fd, 0, SEEK_SET) == -1) {
4952 err = got_error_from_errno2("lseek", abspath);
4953 goto done;
4955 done:
4956 if (err) {
4957 close(*fd);
4958 *fd = -1;
4960 return err;
4963 static const struct got_error *
4964 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4965 const char *path, struct got_object_id *blob_id,
4966 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4967 int dirfd, const char *de_name)
4969 struct print_diff_arg *a = arg;
4970 const struct got_error *err = NULL;
4971 struct got_blob_object *blob1 = NULL;
4972 int fd = -1, fd1 = -1, fd2 = -1;
4973 FILE *f2 = NULL;
4974 char *abspath = NULL, *label1 = NULL;
4975 struct stat sb;
4976 off_t size1 = 0;
4977 int f2_exists = 0;
4979 memset(&sb, 0, sizeof(sb));
4981 if (a->diff_staged) {
4982 if (staged_status != GOT_STATUS_MODIFY &&
4983 staged_status != GOT_STATUS_ADD &&
4984 staged_status != GOT_STATUS_DELETE)
4985 return NULL;
4986 } else {
4987 if (staged_status == GOT_STATUS_DELETE)
4988 return NULL;
4989 if (status == GOT_STATUS_NONEXISTENT)
4990 return got_error_set_errno(ENOENT, path);
4991 if (status != GOT_STATUS_MODIFY &&
4992 status != GOT_STATUS_ADD &&
4993 status != GOT_STATUS_DELETE &&
4994 status != GOT_STATUS_CONFLICT)
4995 return NULL;
4998 err = got_opentemp_truncate(a->f1);
4999 if (err)
5000 return got_error_from_errno("got_opentemp_truncate");
5001 err = got_opentemp_truncate(a->f2);
5002 if (err)
5003 return got_error_from_errno("got_opentemp_truncate");
5005 if (!a->header_shown) {
5006 if (fprintf(a->outfile, "diff %s%s\n",
5007 a->diff_staged ? "-s " : "",
5008 got_worktree_get_root_path(a->worktree)) < 0) {
5009 err = got_error_from_errno("fprintf");
5010 goto done;
5012 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5013 err = got_error_from_errno("fprintf");
5014 goto done;
5016 if (fprintf(a->outfile, "path + %s%s\n",
5017 got_worktree_get_root_path(a->worktree),
5018 a->diff_staged ? " (staged changes)" : "") < 0) {
5019 err = got_error_from_errno("fprintf");
5020 goto done;
5022 a->header_shown = 1;
5025 if (a->diff_staged) {
5026 const char *label1 = NULL, *label2 = NULL;
5027 switch (staged_status) {
5028 case GOT_STATUS_MODIFY:
5029 label1 = path;
5030 label2 = path;
5031 break;
5032 case GOT_STATUS_ADD:
5033 label2 = path;
5034 break;
5035 case GOT_STATUS_DELETE:
5036 label1 = path;
5037 break;
5038 default:
5039 return got_error(GOT_ERR_FILE_STATUS);
5041 fd1 = got_opentempfd();
5042 if (fd1 == -1) {
5043 err = got_error_from_errno("got_opentempfd");
5044 goto done;
5046 fd2 = got_opentempfd();
5047 if (fd2 == -1) {
5048 err = got_error_from_errno("got_opentempfd");
5049 goto done;
5051 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5052 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5053 a->diff_algo, a->diff_context, a->ignore_whitespace,
5054 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5055 goto done;
5058 fd1 = got_opentempfd();
5059 if (fd1 == -1) {
5060 err = got_error_from_errno("got_opentempfd");
5061 goto done;
5064 if (staged_status == GOT_STATUS_ADD ||
5065 staged_status == GOT_STATUS_MODIFY) {
5066 char *id_str;
5067 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5068 8192, fd1);
5069 if (err)
5070 goto done;
5071 err = got_object_id_str(&id_str, staged_blob_id);
5072 if (err)
5073 goto done;
5074 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5075 err = got_error_from_errno("asprintf");
5076 free(id_str);
5077 goto done;
5079 free(id_str);
5080 } else if (status != GOT_STATUS_ADD) {
5081 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5082 fd1);
5083 if (err)
5084 goto done;
5087 if (status != GOT_STATUS_DELETE) {
5088 if (asprintf(&abspath, "%s/%s",
5089 got_worktree_get_root_path(a->worktree), path) == -1) {
5090 err = got_error_from_errno("asprintf");
5091 goto done;
5094 if (dirfd != -1) {
5095 fd = openat(dirfd, de_name,
5096 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5097 if (fd == -1) {
5098 if (!got_err_open_nofollow_on_symlink()) {
5099 err = got_error_from_errno2("openat",
5100 abspath);
5101 goto done;
5103 err = get_symlink_target_file(&fd, dirfd,
5104 de_name, abspath);
5105 if (err)
5106 goto done;
5108 } else {
5109 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5110 if (fd == -1) {
5111 if (!got_err_open_nofollow_on_symlink()) {
5112 err = got_error_from_errno2("open",
5113 abspath);
5114 goto done;
5116 err = get_symlink_target_file(&fd, dirfd,
5117 de_name, abspath);
5118 if (err)
5119 goto done;
5122 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5123 err = got_error_from_errno2("fstatat", abspath);
5124 goto done;
5126 f2 = fdopen(fd, "r");
5127 if (f2 == NULL) {
5128 err = got_error_from_errno2("fdopen", abspath);
5129 goto done;
5131 fd = -1;
5132 f2_exists = 1;
5135 if (blob1) {
5136 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5137 a->f1, blob1);
5138 if (err)
5139 goto done;
5142 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5143 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5144 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5145 done:
5146 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5147 err = got_error_from_errno("close");
5148 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5149 err = got_error_from_errno("close");
5150 if (blob1)
5151 got_object_blob_close(blob1);
5152 if (fd != -1 && close(fd) == -1 && err == NULL)
5153 err = got_error_from_errno("close");
5154 if (f2 && fclose(f2) == EOF && err == NULL)
5155 err = got_error_from_errno("fclose");
5156 free(abspath);
5157 return err;
5160 static const struct got_error *
5161 cmd_diff(int argc, char *argv[])
5163 const struct got_error *error;
5164 struct got_repository *repo = NULL;
5165 struct got_worktree *worktree = NULL;
5166 char *cwd = NULL, *repo_path = NULL;
5167 const char *commit_args[2] = { NULL, NULL };
5168 int ncommit_args = 0;
5169 struct got_object_id *ids[2] = { NULL, NULL };
5170 char *labels[2] = { NULL, NULL };
5171 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5172 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5173 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5174 const char *errstr;
5175 struct got_reflist_head refs;
5176 struct got_pathlist_head diffstat_paths, paths;
5177 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5178 int fd1 = -1, fd2 = -1;
5179 int *pack_fds = NULL;
5180 struct got_diffstat_cb_arg dsa;
5182 memset(&dsa, 0, sizeof(dsa));
5184 TAILQ_INIT(&refs);
5185 TAILQ_INIT(&paths);
5186 TAILQ_INIT(&diffstat_paths);
5188 #ifndef PROFILE
5189 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5190 NULL) == -1)
5191 err(1, "pledge");
5192 #endif
5194 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5195 switch (ch) {
5196 case 'a':
5197 force_text_diff = 1;
5198 break;
5199 case 'C':
5200 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5201 &errstr);
5202 if (errstr != NULL)
5203 errx(1, "number of context lines is %s: %s",
5204 errstr, optarg);
5205 break;
5206 case 'c':
5207 if (ncommit_args >= 2)
5208 errx(1, "too many -c options used");
5209 commit_args[ncommit_args++] = optarg;
5210 break;
5211 case 'd':
5212 show_diffstat = 1;
5213 break;
5214 case 'P':
5215 force_path = 1;
5216 break;
5217 case 'r':
5218 repo_path = realpath(optarg, NULL);
5219 if (repo_path == NULL)
5220 return got_error_from_errno2("realpath",
5221 optarg);
5222 got_path_strip_trailing_slashes(repo_path);
5223 rflag = 1;
5224 break;
5225 case 's':
5226 diff_staged = 1;
5227 break;
5228 case 'w':
5229 ignore_whitespace = 1;
5230 break;
5231 default:
5232 usage_diff();
5233 /* NOTREACHED */
5237 argc -= optind;
5238 argv += optind;
5240 cwd = getcwd(NULL, 0);
5241 if (cwd == NULL) {
5242 error = got_error_from_errno("getcwd");
5243 goto done;
5246 error = got_repo_pack_fds_open(&pack_fds);
5247 if (error != NULL)
5248 goto done;
5250 if (repo_path == NULL) {
5251 error = got_worktree_open(&worktree, cwd,
5252 GOT_WORKTREE_GOT_DIR);
5253 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5254 goto done;
5255 else
5256 error = NULL;
5257 if (worktree) {
5258 repo_path =
5259 strdup(got_worktree_get_repo_path(worktree));
5260 if (repo_path == NULL) {
5261 error = got_error_from_errno("strdup");
5262 goto done;
5264 } else {
5265 repo_path = strdup(cwd);
5266 if (repo_path == NULL) {
5267 error = got_error_from_errno("strdup");
5268 goto done;
5273 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5274 free(repo_path);
5275 if (error != NULL)
5276 goto done;
5278 if (show_diffstat) {
5279 dsa.paths = &diffstat_paths;
5280 dsa.force_text = force_text_diff;
5281 dsa.ignore_ws = ignore_whitespace;
5282 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5285 if (rflag || worktree == NULL || ncommit_args > 0) {
5286 if (force_path) {
5287 error = got_error_msg(GOT_ERR_NOT_IMPL,
5288 "-P option can only be used when diffing "
5289 "a work tree");
5290 goto done;
5292 if (diff_staged) {
5293 error = got_error_msg(GOT_ERR_NOT_IMPL,
5294 "-s option can only be used when diffing "
5295 "a work tree");
5296 goto done;
5300 error = apply_unveil(got_repo_get_path(repo), 1,
5301 worktree ? got_worktree_get_root_path(worktree) : NULL);
5302 if (error)
5303 goto done;
5305 if ((!force_path && argc == 2) || ncommit_args > 0) {
5306 int obj_type = (ncommit_args > 0 ?
5307 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5308 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5309 NULL);
5310 if (error)
5311 goto done;
5312 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5313 const char *arg;
5314 char *keyword_idstr = NULL;
5316 if (ncommit_args > 0)
5317 arg = commit_args[i];
5318 else
5319 arg = argv[i];
5321 error = got_keyword_to_idstr(&keyword_idstr, arg,
5322 repo, worktree);
5323 if (error != NULL)
5324 goto done;
5325 if (keyword_idstr != NULL)
5326 arg = keyword_idstr;
5328 error = got_repo_match_object_id(&ids[i], &labels[i],
5329 arg, obj_type, &refs, repo);
5330 free(keyword_idstr);
5331 if (error) {
5332 if (error->code != GOT_ERR_NOT_REF &&
5333 error->code != GOT_ERR_NO_OBJ)
5334 goto done;
5335 if (ncommit_args > 0)
5336 goto done;
5337 error = NULL;
5338 break;
5343 f1 = got_opentemp();
5344 if (f1 == NULL) {
5345 error = got_error_from_errno("got_opentemp");
5346 goto done;
5349 f2 = got_opentemp();
5350 if (f2 == NULL) {
5351 error = got_error_from_errno("got_opentemp");
5352 goto done;
5355 outfile = got_opentemp();
5356 if (outfile == NULL) {
5357 error = got_error_from_errno("got_opentemp");
5358 goto done;
5361 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5362 struct print_diff_arg arg;
5363 char *id_str;
5365 if (worktree == NULL) {
5366 if (argc == 2 && ids[0] == NULL) {
5367 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5368 goto done;
5369 } else if (argc == 2 && ids[1] == NULL) {
5370 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5371 goto done;
5372 } else if (argc > 0) {
5373 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5374 "%s", "specified paths cannot be resolved");
5375 goto done;
5376 } else {
5377 error = got_error(GOT_ERR_NOT_WORKTREE);
5378 goto done;
5382 error = get_worktree_paths_from_argv(&paths, argc, argv,
5383 worktree);
5384 if (error)
5385 goto done;
5387 error = got_object_id_str(&id_str,
5388 got_worktree_get_base_commit_id(worktree));
5389 if (error)
5390 goto done;
5391 arg.repo = repo;
5392 arg.worktree = worktree;
5393 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5394 arg.diff_context = diff_context;
5395 arg.id_str = id_str;
5396 arg.header_shown = 0;
5397 arg.diff_staged = diff_staged;
5398 arg.ignore_whitespace = ignore_whitespace;
5399 arg.force_text_diff = force_text_diff;
5400 arg.diffstat = show_diffstat ? &dsa : NULL;
5401 arg.f1 = f1;
5402 arg.f2 = f2;
5403 arg.outfile = outfile;
5405 error = got_worktree_status(worktree, &paths, repo, 0,
5406 print_diff, &arg, check_cancelled, NULL);
5407 free(id_str);
5408 if (error)
5409 goto done;
5411 if (show_diffstat && dsa.nfiles > 0) {
5412 char *header;
5414 if (asprintf(&header, "diffstat %s%s",
5415 diff_staged ? "-s " : "",
5416 got_worktree_get_root_path(worktree)) == -1) {
5417 error = got_error_from_errno("asprintf");
5418 goto done;
5421 error = print_diffstat(&dsa, header);
5422 free(header);
5423 if (error)
5424 goto done;
5427 error = printfile(outfile);
5428 goto done;
5431 if (ncommit_args == 1) {
5432 struct got_commit_object *commit;
5433 error = got_object_open_as_commit(&commit, repo, ids[0]);
5434 if (error)
5435 goto done;
5437 labels[1] = labels[0];
5438 ids[1] = ids[0];
5439 if (got_object_commit_get_nparents(commit) > 0) {
5440 const struct got_object_id_queue *pids;
5441 struct got_object_qid *pid;
5442 pids = got_object_commit_get_parent_ids(commit);
5443 pid = STAILQ_FIRST(pids);
5444 ids[0] = got_object_id_dup(&pid->id);
5445 if (ids[0] == NULL) {
5446 error = got_error_from_errno(
5447 "got_object_id_dup");
5448 got_object_commit_close(commit);
5449 goto done;
5451 error = got_object_id_str(&labels[0], ids[0]);
5452 if (error) {
5453 got_object_commit_close(commit);
5454 goto done;
5456 } else {
5457 ids[0] = NULL;
5458 labels[0] = strdup("/dev/null");
5459 if (labels[0] == NULL) {
5460 error = got_error_from_errno("strdup");
5461 got_object_commit_close(commit);
5462 goto done;
5466 got_object_commit_close(commit);
5469 if (ncommit_args == 0 && argc > 2) {
5470 error = got_error_msg(GOT_ERR_BAD_PATH,
5471 "path arguments cannot be used when diffing two objects");
5472 goto done;
5475 if (ids[0]) {
5476 error = got_object_get_type(&type1, repo, ids[0]);
5477 if (error)
5478 goto done;
5481 error = got_object_get_type(&type2, repo, ids[1]);
5482 if (error)
5483 goto done;
5484 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5485 error = got_error(GOT_ERR_OBJ_TYPE);
5486 goto done;
5488 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5489 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5490 "path arguments cannot be used when diffing blobs");
5491 goto done;
5494 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5495 char *in_repo_path;
5496 struct got_pathlist_entry *new;
5497 if (worktree) {
5498 const char *prefix;
5499 char *p;
5500 error = got_worktree_resolve_path(&p, worktree,
5501 argv[i]);
5502 if (error)
5503 goto done;
5504 prefix = got_worktree_get_path_prefix(worktree);
5505 while (prefix[0] == '/')
5506 prefix++;
5507 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5508 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5509 p) == -1) {
5510 error = got_error_from_errno("asprintf");
5511 free(p);
5512 goto done;
5514 free(p);
5515 } else {
5516 char *mapped_path, *s;
5517 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5518 if (error)
5519 goto done;
5520 s = mapped_path;
5521 while (s[0] == '/')
5522 s++;
5523 in_repo_path = strdup(s);
5524 if (in_repo_path == NULL) {
5525 error = got_error_from_errno("asprintf");
5526 free(mapped_path);
5527 goto done;
5529 free(mapped_path);
5532 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5533 if (error || new == NULL /* duplicate */)
5534 free(in_repo_path);
5535 if (error)
5536 goto done;
5539 if (worktree) {
5540 /* Release work tree lock. */
5541 got_worktree_close(worktree);
5542 worktree = NULL;
5545 fd1 = got_opentempfd();
5546 if (fd1 == -1) {
5547 error = got_error_from_errno("got_opentempfd");
5548 goto done;
5551 fd2 = got_opentempfd();
5552 if (fd2 == -1) {
5553 error = got_error_from_errno("got_opentempfd");
5554 goto done;
5557 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5558 case GOT_OBJ_TYPE_BLOB:
5559 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5560 fd1, fd2, ids[0], ids[1], NULL, NULL,
5561 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5562 ignore_whitespace, force_text_diff,
5563 show_diffstat ? &dsa : NULL, repo, outfile);
5564 break;
5565 case GOT_OBJ_TYPE_TREE:
5566 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5567 ids[0], ids[1], &paths, "", "",
5568 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5569 ignore_whitespace, force_text_diff,
5570 show_diffstat ? &dsa : NULL, repo, outfile);
5571 break;
5572 case GOT_OBJ_TYPE_COMMIT:
5573 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5574 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5575 fd1, fd2, ids[0], ids[1], &paths,
5576 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5577 ignore_whitespace, force_text_diff,
5578 show_diffstat ? &dsa : NULL, repo, outfile);
5579 break;
5580 default:
5581 error = got_error(GOT_ERR_OBJ_TYPE);
5583 if (error)
5584 goto done;
5586 if (show_diffstat && dsa.nfiles > 0) {
5587 char *header = NULL;
5589 if (asprintf(&header, "diffstat %s %s",
5590 labels[0], labels[1]) == -1) {
5591 error = got_error_from_errno("asprintf");
5592 goto done;
5595 error = print_diffstat(&dsa, header);
5596 free(header);
5597 if (error)
5598 goto done;
5601 error = printfile(outfile);
5603 done:
5604 free(labels[0]);
5605 free(labels[1]);
5606 free(ids[0]);
5607 free(ids[1]);
5608 if (worktree)
5609 got_worktree_close(worktree);
5610 if (repo) {
5611 const struct got_error *close_err = got_repo_close(repo);
5612 if (error == NULL)
5613 error = close_err;
5615 if (pack_fds) {
5616 const struct got_error *pack_err =
5617 got_repo_pack_fds_close(pack_fds);
5618 if (error == NULL)
5619 error = pack_err;
5621 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5622 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5623 got_ref_list_free(&refs);
5624 if (outfile && fclose(outfile) == EOF && error == NULL)
5625 error = got_error_from_errno("fclose");
5626 if (f1 && fclose(f1) == EOF && error == NULL)
5627 error = got_error_from_errno("fclose");
5628 if (f2 && fclose(f2) == EOF && error == NULL)
5629 error = got_error_from_errno("fclose");
5630 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5631 error = got_error_from_errno("close");
5632 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5633 error = got_error_from_errno("close");
5634 return error;
5637 __dead static void
5638 usage_blame(void)
5640 fprintf(stderr,
5641 "usage: %s blame [-c commit] [-r repository-path] path\n",
5642 getprogname());
5643 exit(1);
5646 struct blame_line {
5647 int annotated;
5648 char *id_str;
5649 char *committer;
5650 char datebuf[11]; /* YYYY-MM-DD + NUL */
5653 struct blame_cb_args {
5654 struct blame_line *lines;
5655 int nlines;
5656 int nlines_prec;
5657 int lineno_cur;
5658 off_t *line_offsets;
5659 FILE *f;
5660 struct got_repository *repo;
5663 static const struct got_error *
5664 blame_cb(void *arg, int nlines, int lineno,
5665 struct got_commit_object *commit, struct got_object_id *id)
5667 const struct got_error *err = NULL;
5668 struct blame_cb_args *a = arg;
5669 struct blame_line *bline;
5670 char *line = NULL;
5671 size_t linesize = 0;
5672 off_t offset;
5673 struct tm tm;
5674 time_t committer_time;
5676 if (nlines != a->nlines ||
5677 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5678 return got_error(GOT_ERR_RANGE);
5680 if (sigint_received)
5681 return got_error(GOT_ERR_ITER_COMPLETED);
5683 if (lineno == -1)
5684 return NULL; /* no change in this commit */
5686 /* Annotate this line. */
5687 bline = &a->lines[lineno - 1];
5688 if (bline->annotated)
5689 return NULL;
5690 err = got_object_id_str(&bline->id_str, id);
5691 if (err)
5692 return err;
5694 bline->committer = strdup(got_object_commit_get_committer(commit));
5695 if (bline->committer == NULL) {
5696 err = got_error_from_errno("strdup");
5697 goto done;
5700 committer_time = got_object_commit_get_committer_time(commit);
5701 if (gmtime_r(&committer_time, &tm) == NULL)
5702 return got_error_from_errno("gmtime_r");
5703 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5704 &tm) == 0) {
5705 err = got_error(GOT_ERR_NO_SPACE);
5706 goto done;
5708 bline->annotated = 1;
5710 /* Print lines annotated so far. */
5711 bline = &a->lines[a->lineno_cur - 1];
5712 if (!bline->annotated)
5713 goto done;
5715 offset = a->line_offsets[a->lineno_cur - 1];
5716 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5717 err = got_error_from_errno("fseeko");
5718 goto done;
5721 while (a->lineno_cur <= a->nlines && bline->annotated) {
5722 char *smallerthan, *at, *nl, *committer;
5723 size_t len;
5725 if (getline(&line, &linesize, a->f) == -1) {
5726 if (ferror(a->f))
5727 err = got_error_from_errno("getline");
5728 break;
5731 committer = bline->committer;
5732 smallerthan = strchr(committer, '<');
5733 if (smallerthan && smallerthan[1] != '\0')
5734 committer = smallerthan + 1;
5735 at = strchr(committer, '@');
5736 if (at)
5737 *at = '\0';
5738 len = strlen(committer);
5739 if (len >= 9)
5740 committer[8] = '\0';
5742 nl = strchr(line, '\n');
5743 if (nl)
5744 *nl = '\0';
5745 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5746 bline->id_str, bline->datebuf, committer, line);
5748 a->lineno_cur++;
5749 bline = &a->lines[a->lineno_cur - 1];
5751 done:
5752 free(line);
5753 return err;
5756 static const struct got_error *
5757 cmd_blame(int argc, char *argv[])
5759 const struct got_error *error;
5760 struct got_repository *repo = NULL;
5761 struct got_worktree *worktree = NULL;
5762 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5763 char *link_target = NULL;
5764 struct got_object_id *obj_id = NULL;
5765 struct got_object_id *commit_id = NULL;
5766 struct got_commit_object *commit = NULL;
5767 struct got_blob_object *blob = NULL;
5768 char *commit_id_str = NULL, *keyword_idstr = NULL;
5769 struct blame_cb_args bca;
5770 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5771 off_t filesize;
5772 int *pack_fds = NULL;
5773 FILE *f1 = NULL, *f2 = NULL;
5775 fd1 = got_opentempfd();
5776 if (fd1 == -1)
5777 return got_error_from_errno("got_opentempfd");
5779 memset(&bca, 0, sizeof(bca));
5781 #ifndef PROFILE
5782 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5783 NULL) == -1)
5784 err(1, "pledge");
5785 #endif
5787 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5788 switch (ch) {
5789 case 'c':
5790 commit_id_str = optarg;
5791 break;
5792 case 'r':
5793 repo_path = realpath(optarg, NULL);
5794 if (repo_path == NULL)
5795 return got_error_from_errno2("realpath",
5796 optarg);
5797 got_path_strip_trailing_slashes(repo_path);
5798 break;
5799 default:
5800 usage_blame();
5801 /* NOTREACHED */
5805 argc -= optind;
5806 argv += optind;
5808 if (argc == 1)
5809 path = argv[0];
5810 else
5811 usage_blame();
5813 cwd = getcwd(NULL, 0);
5814 if (cwd == NULL) {
5815 error = got_error_from_errno("getcwd");
5816 goto done;
5819 error = got_repo_pack_fds_open(&pack_fds);
5820 if (error != NULL)
5821 goto done;
5823 if (repo_path == NULL) {
5824 error = got_worktree_open(&worktree, cwd,
5825 GOT_WORKTREE_GOT_DIR);
5826 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5827 goto done;
5828 else
5829 error = NULL;
5830 if (worktree) {
5831 repo_path =
5832 strdup(got_worktree_get_repo_path(worktree));
5833 if (repo_path == NULL) {
5834 error = got_error_from_errno("strdup");
5835 if (error)
5836 goto done;
5838 } else {
5839 repo_path = strdup(cwd);
5840 if (repo_path == NULL) {
5841 error = got_error_from_errno("strdup");
5842 goto done;
5847 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5848 if (error != NULL)
5849 goto done;
5851 if (worktree) {
5852 const char *prefix = got_worktree_get_path_prefix(worktree);
5853 char *p;
5855 error = got_worktree_resolve_path(&p, worktree, path);
5856 if (error)
5857 goto done;
5858 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5859 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5860 p) == -1) {
5861 error = got_error_from_errno("asprintf");
5862 free(p);
5863 goto done;
5865 free(p);
5866 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5867 } else {
5868 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5869 if (error)
5870 goto done;
5871 error = got_repo_map_path(&in_repo_path, repo, path);
5873 if (error)
5874 goto done;
5876 if (commit_id_str == NULL) {
5877 struct got_reference *head_ref;
5878 error = got_ref_open(&head_ref, repo, worktree ?
5879 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5880 if (error != NULL)
5881 goto done;
5882 error = got_ref_resolve(&commit_id, repo, head_ref);
5883 got_ref_close(head_ref);
5884 if (error != NULL)
5885 goto done;
5886 } else {
5887 struct got_reflist_head refs;
5889 TAILQ_INIT(&refs);
5890 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5891 NULL);
5892 if (error)
5893 goto done;
5895 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5896 repo, worktree);
5897 if (error != NULL)
5898 goto done;
5899 if (keyword_idstr != NULL)
5900 commit_id_str = keyword_idstr;
5902 error = got_repo_match_object_id(&commit_id, NULL,
5903 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5904 got_ref_list_free(&refs);
5905 if (error)
5906 goto done;
5909 if (worktree) {
5910 /* Release work tree lock. */
5911 got_worktree_close(worktree);
5912 worktree = NULL;
5915 error = got_object_open_as_commit(&commit, repo, commit_id);
5916 if (error)
5917 goto done;
5919 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5920 commit, repo);
5921 if (error)
5922 goto done;
5924 error = got_object_id_by_path(&obj_id, repo, commit,
5925 link_target ? link_target : in_repo_path);
5926 if (error)
5927 goto done;
5929 error = got_object_get_type(&obj_type, repo, obj_id);
5930 if (error)
5931 goto done;
5933 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5934 error = got_error_path(link_target ? link_target : in_repo_path,
5935 GOT_ERR_OBJ_TYPE);
5936 goto done;
5939 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5940 if (error)
5941 goto done;
5942 bca.f = got_opentemp();
5943 if (bca.f == NULL) {
5944 error = got_error_from_errno("got_opentemp");
5945 goto done;
5947 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5948 &bca.line_offsets, bca.f, blob);
5949 if (error || bca.nlines == 0)
5950 goto done;
5952 /* Don't include \n at EOF in the blame line count. */
5953 if (bca.line_offsets[bca.nlines - 1] == filesize)
5954 bca.nlines--;
5956 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5957 if (bca.lines == NULL) {
5958 error = got_error_from_errno("calloc");
5959 goto done;
5961 bca.lineno_cur = 1;
5962 bca.nlines_prec = 0;
5963 i = bca.nlines;
5964 while (i > 0) {
5965 i /= 10;
5966 bca.nlines_prec++;
5968 bca.repo = repo;
5970 fd2 = got_opentempfd();
5971 if (fd2 == -1) {
5972 error = got_error_from_errno("got_opentempfd");
5973 goto done;
5975 fd3 = got_opentempfd();
5976 if (fd3 == -1) {
5977 error = got_error_from_errno("got_opentempfd");
5978 goto done;
5980 f1 = got_opentemp();
5981 if (f1 == NULL) {
5982 error = got_error_from_errno("got_opentemp");
5983 goto done;
5985 f2 = got_opentemp();
5986 if (f2 == NULL) {
5987 error = got_error_from_errno("got_opentemp");
5988 goto done;
5990 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5991 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5992 check_cancelled, NULL, fd2, fd3, f1, f2);
5993 done:
5994 free(keyword_idstr);
5995 free(in_repo_path);
5996 free(link_target);
5997 free(repo_path);
5998 free(cwd);
5999 free(commit_id);
6000 free(obj_id);
6001 if (commit)
6002 got_object_commit_close(commit);
6004 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6005 error = got_error_from_errno("close");
6006 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6007 error = got_error_from_errno("close");
6008 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6009 error = got_error_from_errno("close");
6010 if (f1 && fclose(f1) == EOF && error == NULL)
6011 error = got_error_from_errno("fclose");
6012 if (f2 && fclose(f2) == EOF && error == NULL)
6013 error = got_error_from_errno("fclose");
6015 if (blob)
6016 got_object_blob_close(blob);
6017 if (worktree)
6018 got_worktree_close(worktree);
6019 if (repo) {
6020 const struct got_error *close_err = got_repo_close(repo);
6021 if (error == NULL)
6022 error = close_err;
6024 if (pack_fds) {
6025 const struct got_error *pack_err =
6026 got_repo_pack_fds_close(pack_fds);
6027 if (error == NULL)
6028 error = pack_err;
6030 if (bca.lines) {
6031 for (i = 0; i < bca.nlines; i++) {
6032 struct blame_line *bline = &bca.lines[i];
6033 free(bline->id_str);
6034 free(bline->committer);
6036 free(bca.lines);
6038 free(bca.line_offsets);
6039 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6040 error = got_error_from_errno("fclose");
6041 return error;
6044 __dead static void
6045 usage_tree(void)
6047 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6048 "[path]\n", getprogname());
6049 exit(1);
6052 static const struct got_error *
6053 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6054 const char *root_path, struct got_repository *repo)
6056 const struct got_error *err = NULL;
6057 int is_root_path = (strcmp(path, root_path) == 0);
6058 const char *modestr = "";
6059 mode_t mode = got_tree_entry_get_mode(te);
6060 char *link_target = NULL;
6062 path += strlen(root_path);
6063 while (path[0] == '/')
6064 path++;
6066 if (got_object_tree_entry_is_submodule(te))
6067 modestr = "$";
6068 else if (S_ISLNK(mode)) {
6069 int i;
6071 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6072 if (err)
6073 return err;
6074 for (i = 0; link_target[i] != '\0'; i++) {
6075 if (!isprint((unsigned char)link_target[i]))
6076 link_target[i] = '?';
6079 modestr = "@";
6081 else if (S_ISDIR(mode))
6082 modestr = "/";
6083 else if (mode & S_IXUSR)
6084 modestr = "*";
6086 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6087 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6088 link_target ? " -> ": "", link_target ? link_target : "");
6090 free(link_target);
6091 return NULL;
6094 static const struct got_error *
6095 print_tree(const char *path, struct got_commit_object *commit,
6096 int show_ids, int recurse, const char *root_path,
6097 struct got_repository *repo)
6099 const struct got_error *err = NULL;
6100 struct got_object_id *tree_id = NULL;
6101 struct got_tree_object *tree = NULL;
6102 int nentries, i;
6104 err = got_object_id_by_path(&tree_id, repo, commit, path);
6105 if (err)
6106 goto done;
6108 err = got_object_open_as_tree(&tree, repo, tree_id);
6109 if (err)
6110 goto done;
6111 nentries = got_object_tree_get_nentries(tree);
6112 for (i = 0; i < nentries; i++) {
6113 struct got_tree_entry *te;
6114 char *id = NULL;
6116 if (sigint_received || sigpipe_received)
6117 break;
6119 te = got_object_tree_get_entry(tree, i);
6120 if (show_ids) {
6121 char *id_str;
6122 err = got_object_id_str(&id_str,
6123 got_tree_entry_get_id(te));
6124 if (err)
6125 goto done;
6126 if (asprintf(&id, "%s ", id_str) == -1) {
6127 err = got_error_from_errno("asprintf");
6128 free(id_str);
6129 goto done;
6131 free(id_str);
6133 err = print_entry(te, id, path, root_path, repo);
6134 free(id);
6135 if (err)
6136 goto done;
6138 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6139 char *child_path;
6140 if (asprintf(&child_path, "%s%s%s", path,
6141 path[0] == '/' && path[1] == '\0' ? "" : "/",
6142 got_tree_entry_get_name(te)) == -1) {
6143 err = got_error_from_errno("asprintf");
6144 goto done;
6146 err = print_tree(child_path, commit, show_ids, 1,
6147 root_path, repo);
6148 free(child_path);
6149 if (err)
6150 goto done;
6153 done:
6154 if (tree)
6155 got_object_tree_close(tree);
6156 free(tree_id);
6157 return err;
6160 static const struct got_error *
6161 cmd_tree(int argc, char *argv[])
6163 const struct got_error *error;
6164 struct got_repository *repo = NULL;
6165 struct got_worktree *worktree = NULL;
6166 const char *path, *refname = NULL;
6167 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6168 struct got_object_id *commit_id = NULL;
6169 struct got_commit_object *commit = NULL;
6170 char *commit_id_str = NULL, *keyword_idstr = NULL;
6171 int show_ids = 0, recurse = 0;
6172 int ch;
6173 int *pack_fds = NULL;
6175 #ifndef PROFILE
6176 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6177 NULL) == -1)
6178 err(1, "pledge");
6179 #endif
6181 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6182 switch (ch) {
6183 case 'c':
6184 commit_id_str = optarg;
6185 break;
6186 case 'i':
6187 show_ids = 1;
6188 break;
6189 case 'R':
6190 recurse = 1;
6191 break;
6192 case 'r':
6193 repo_path = realpath(optarg, NULL);
6194 if (repo_path == NULL)
6195 return got_error_from_errno2("realpath",
6196 optarg);
6197 got_path_strip_trailing_slashes(repo_path);
6198 break;
6199 default:
6200 usage_tree();
6201 /* NOTREACHED */
6205 argc -= optind;
6206 argv += optind;
6208 if (argc == 1)
6209 path = argv[0];
6210 else if (argc > 1)
6211 usage_tree();
6212 else
6213 path = NULL;
6215 cwd = getcwd(NULL, 0);
6216 if (cwd == NULL) {
6217 error = got_error_from_errno("getcwd");
6218 goto done;
6221 error = got_repo_pack_fds_open(&pack_fds);
6222 if (error != NULL)
6223 goto done;
6225 if (repo_path == NULL) {
6226 error = got_worktree_open(&worktree, cwd,
6227 GOT_WORKTREE_GOT_DIR);
6228 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6229 goto done;
6230 else
6231 error = NULL;
6232 if (worktree) {
6233 repo_path =
6234 strdup(got_worktree_get_repo_path(worktree));
6235 if (repo_path == NULL)
6236 error = got_error_from_errno("strdup");
6237 if (error)
6238 goto done;
6239 } else {
6240 repo_path = strdup(cwd);
6241 if (repo_path == NULL) {
6242 error = got_error_from_errno("strdup");
6243 goto done;
6248 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6249 if (error != NULL)
6250 goto done;
6252 if (worktree) {
6253 const char *prefix = got_worktree_get_path_prefix(worktree);
6254 char *p;
6256 if (path == NULL || got_path_is_root_dir(path))
6257 path = "";
6258 error = got_worktree_resolve_path(&p, worktree, path);
6259 if (error)
6260 goto done;
6261 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6262 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6263 p) == -1) {
6264 error = got_error_from_errno("asprintf");
6265 free(p);
6266 goto done;
6268 free(p);
6269 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6270 if (error)
6271 goto done;
6272 } else {
6273 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6274 if (error)
6275 goto done;
6276 if (path == NULL)
6277 path = "/";
6278 error = got_repo_map_path(&in_repo_path, repo, path);
6279 if (error != NULL)
6280 goto done;
6283 if (commit_id_str == NULL) {
6284 struct got_reference *head_ref;
6285 if (worktree)
6286 refname = got_worktree_get_head_ref_name(worktree);
6287 else
6288 refname = GOT_REF_HEAD;
6289 error = got_ref_open(&head_ref, repo, refname, 0);
6290 if (error != NULL)
6291 goto done;
6292 error = got_ref_resolve(&commit_id, repo, head_ref);
6293 got_ref_close(head_ref);
6294 if (error != NULL)
6295 goto done;
6296 } else {
6297 struct got_reflist_head refs;
6299 TAILQ_INIT(&refs);
6300 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6301 NULL);
6302 if (error)
6303 goto done;
6305 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6306 repo, worktree);
6307 if (error != NULL)
6308 goto done;
6309 if (keyword_idstr != NULL)
6310 commit_id_str = keyword_idstr;
6312 error = got_repo_match_object_id(&commit_id, NULL,
6313 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6314 got_ref_list_free(&refs);
6315 if (error)
6316 goto done;
6319 if (worktree) {
6320 /* Release work tree lock. */
6321 got_worktree_close(worktree);
6322 worktree = NULL;
6325 error = got_object_open_as_commit(&commit, repo, commit_id);
6326 if (error)
6327 goto done;
6329 error = print_tree(in_repo_path, commit, show_ids, recurse,
6330 in_repo_path, repo);
6331 done:
6332 free(keyword_idstr);
6333 free(in_repo_path);
6334 free(repo_path);
6335 free(cwd);
6336 free(commit_id);
6337 if (commit)
6338 got_object_commit_close(commit);
6339 if (worktree)
6340 got_worktree_close(worktree);
6341 if (repo) {
6342 const struct got_error *close_err = got_repo_close(repo);
6343 if (error == NULL)
6344 error = close_err;
6346 if (pack_fds) {
6347 const struct got_error *pack_err =
6348 got_repo_pack_fds_close(pack_fds);
6349 if (error == NULL)
6350 error = pack_err;
6352 return error;
6355 __dead static void
6356 usage_status(void)
6358 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6359 "[-s status-codes] [path ...]\n", getprogname());
6360 exit(1);
6363 struct got_status_arg {
6364 char *status_codes;
6365 int suppress;
6368 static const struct got_error *
6369 print_status(void *arg, unsigned char status, unsigned char staged_status,
6370 const char *path, struct got_object_id *blob_id,
6371 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6372 int dirfd, const char *de_name)
6374 struct got_status_arg *st = arg;
6376 if (status == staged_status && (status == GOT_STATUS_DELETE))
6377 status = GOT_STATUS_NO_CHANGE;
6378 if (st != NULL && st->status_codes) {
6379 size_t ncodes = strlen(st->status_codes);
6380 int i, j = 0;
6382 for (i = 0; i < ncodes ; i++) {
6383 if (st->suppress) {
6384 if (status == st->status_codes[i] ||
6385 staged_status == st->status_codes[i]) {
6386 j++;
6387 continue;
6389 } else {
6390 if (status == st->status_codes[i] ||
6391 staged_status == st->status_codes[i])
6392 break;
6396 if (st->suppress && j == 0)
6397 goto print;
6399 if (i == ncodes)
6400 return NULL;
6402 print:
6403 printf("%c%c %s\n", status, staged_status, path);
6404 return NULL;
6407 static const struct got_error *
6408 cmd_status(int argc, char *argv[])
6410 const struct got_error *close_err, *error = NULL;
6411 struct got_repository *repo = NULL;
6412 struct got_worktree *worktree = NULL;
6413 struct got_status_arg st;
6414 char *cwd = NULL;
6415 struct got_pathlist_head paths;
6416 int ch, i, no_ignores = 0;
6417 int *pack_fds = NULL;
6419 TAILQ_INIT(&paths);
6421 memset(&st, 0, sizeof(st));
6422 st.status_codes = NULL;
6423 st.suppress = 0;
6425 #ifndef PROFILE
6426 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6427 NULL) == -1)
6428 err(1, "pledge");
6429 #endif
6431 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6432 switch (ch) {
6433 case 'I':
6434 no_ignores = 1;
6435 break;
6436 case 'S':
6437 if (st.status_codes != NULL && st.suppress == 0)
6438 option_conflict('S', 's');
6439 st.suppress = 1;
6440 /* fallthrough */
6441 case 's':
6442 for (i = 0; optarg[i] != '\0'; i++) {
6443 switch (optarg[i]) {
6444 case GOT_STATUS_MODIFY:
6445 case GOT_STATUS_ADD:
6446 case GOT_STATUS_DELETE:
6447 case GOT_STATUS_CONFLICT:
6448 case GOT_STATUS_MISSING:
6449 case GOT_STATUS_OBSTRUCTED:
6450 case GOT_STATUS_UNVERSIONED:
6451 case GOT_STATUS_MODE_CHANGE:
6452 case GOT_STATUS_NONEXISTENT:
6453 break;
6454 default:
6455 errx(1, "invalid status code '%c'",
6456 optarg[i]);
6459 if (ch == 's' && st.suppress)
6460 option_conflict('s', 'S');
6461 st.status_codes = optarg;
6462 break;
6463 default:
6464 usage_status();
6465 /* NOTREACHED */
6469 argc -= optind;
6470 argv += optind;
6472 cwd = getcwd(NULL, 0);
6473 if (cwd == NULL) {
6474 error = got_error_from_errno("getcwd");
6475 goto done;
6478 error = got_repo_pack_fds_open(&pack_fds);
6479 if (error != NULL)
6480 goto done;
6482 error = got_worktree_open(&worktree, cwd,
6483 GOT_WORKTREE_GOT_DIR);
6484 if (error) {
6485 if (error->code == GOT_ERR_NOT_WORKTREE)
6486 error = wrap_not_worktree_error(error, "status", cwd);
6487 goto done;
6490 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6491 NULL, pack_fds);
6492 if (error != NULL)
6493 goto done;
6495 error = apply_unveil(got_repo_get_path(repo), 1,
6496 got_worktree_get_root_path(worktree));
6497 if (error)
6498 goto done;
6500 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6501 if (error)
6502 goto done;
6504 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6505 print_status, &st, check_cancelled, NULL);
6506 done:
6507 if (pack_fds) {
6508 const struct got_error *pack_err =
6509 got_repo_pack_fds_close(pack_fds);
6510 if (error == NULL)
6511 error = pack_err;
6513 if (repo) {
6514 close_err = got_repo_close(repo);
6515 if (error == NULL)
6516 error = close_err;
6518 if (worktree != NULL) {
6519 close_err = got_worktree_close(worktree);
6520 if (error == NULL)
6521 error = close_err;
6524 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6525 free(cwd);
6526 return error;
6529 __dead static void
6530 usage_ref(void)
6532 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6533 "[-s reference] [name]\n", getprogname());
6534 exit(1);
6537 static const struct got_error *
6538 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6540 static const struct got_error *err = NULL;
6541 struct got_reflist_head refs;
6542 struct got_reflist_entry *re;
6544 TAILQ_INIT(&refs);
6545 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6546 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6547 repo);
6548 if (err)
6549 return err;
6551 TAILQ_FOREACH(re, &refs, entry) {
6552 char *refstr;
6553 refstr = got_ref_to_str(re->ref);
6554 if (refstr == NULL) {
6555 err = got_error_from_errno("got_ref_to_str");
6556 break;
6558 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6559 free(refstr);
6562 got_ref_list_free(&refs);
6563 return err;
6566 static const struct got_error *
6567 delete_ref_by_name(struct got_repository *repo, const char *refname)
6569 const struct got_error *err;
6570 struct got_reference *ref;
6572 err = got_ref_open(&ref, repo, refname, 0);
6573 if (err)
6574 return err;
6576 err = delete_ref(repo, ref);
6577 got_ref_close(ref);
6578 return err;
6581 static const struct got_error *
6582 add_ref(struct got_repository *repo, const char *refname, const char *target)
6584 const struct got_error *err = NULL;
6585 struct got_object_id *id = NULL;
6586 struct got_reference *ref = NULL;
6587 struct got_reflist_head refs;
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 TAILQ_INIT(&refs);
6598 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6599 if (err)
6600 goto done;
6601 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6602 &refs, repo);
6603 got_ref_list_free(&refs);
6604 if (err)
6605 goto done;
6607 err = got_ref_alloc(&ref, refname, id);
6608 if (err)
6609 goto done;
6611 err = got_ref_write(ref, repo);
6612 done:
6613 if (ref)
6614 got_ref_close(ref);
6615 free(id);
6616 return err;
6619 static const struct got_error *
6620 add_symref(struct got_repository *repo, const char *refname, const char *target)
6622 const struct got_error *err = NULL;
6623 struct got_reference *ref = NULL;
6624 struct got_reference *target_ref = NULL;
6627 * Don't let the user create a reference name with a leading '-'.
6628 * While technically a valid reference name, this case is usually
6629 * an unintended typo.
6631 if (refname[0] == '-')
6632 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6634 err = got_ref_open(&target_ref, repo, target, 0);
6635 if (err)
6636 return err;
6638 err = got_ref_alloc_symref(&ref, refname, target_ref);
6639 if (err)
6640 goto done;
6642 err = got_ref_write(ref, repo);
6643 done:
6644 if (target_ref)
6645 got_ref_close(target_ref);
6646 if (ref)
6647 got_ref_close(ref);
6648 return err;
6651 static const struct got_error *
6652 cmd_ref(int argc, char *argv[])
6654 const struct got_error *error = NULL;
6655 struct got_repository *repo = NULL;
6656 struct got_worktree *worktree = NULL;
6657 char *cwd = NULL, *repo_path = NULL;
6658 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6659 const char *obj_arg = NULL, *symref_target= NULL;
6660 char *refname = NULL, *keyword_idstr = NULL;
6661 int *pack_fds = NULL;
6663 #ifndef PROFILE
6664 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6665 "sendfd unveil", NULL) == -1)
6666 err(1, "pledge");
6667 #endif
6669 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6670 switch (ch) {
6671 case 'c':
6672 obj_arg = optarg;
6673 break;
6674 case 'd':
6675 do_delete = 1;
6676 break;
6677 case 'l':
6678 do_list = 1;
6679 break;
6680 case 'r':
6681 repo_path = realpath(optarg, NULL);
6682 if (repo_path == NULL)
6683 return got_error_from_errno2("realpath",
6684 optarg);
6685 got_path_strip_trailing_slashes(repo_path);
6686 break;
6687 case 's':
6688 symref_target = optarg;
6689 break;
6690 case 't':
6691 sort_by_time = 1;
6692 break;
6693 default:
6694 usage_ref();
6695 /* NOTREACHED */
6699 if (obj_arg && do_list)
6700 option_conflict('c', 'l');
6701 if (obj_arg && do_delete)
6702 option_conflict('c', 'd');
6703 if (obj_arg && symref_target)
6704 option_conflict('c', 's');
6705 if (symref_target && do_delete)
6706 option_conflict('s', 'd');
6707 if (symref_target && do_list)
6708 option_conflict('s', 'l');
6709 if (do_delete && do_list)
6710 option_conflict('d', 'l');
6711 if (sort_by_time && !do_list)
6712 errx(1, "-t option requires -l option");
6714 argc -= optind;
6715 argv += optind;
6717 if (do_list) {
6718 if (argc != 0 && argc != 1)
6719 usage_ref();
6720 if (argc == 1) {
6721 refname = strdup(argv[0]);
6722 if (refname == NULL) {
6723 error = got_error_from_errno("strdup");
6724 goto done;
6727 } else {
6728 if (argc != 1)
6729 usage_ref();
6730 refname = strdup(argv[0]);
6731 if (refname == NULL) {
6732 error = got_error_from_errno("strdup");
6733 goto done;
6737 if (refname)
6738 got_path_strip_trailing_slashes(refname);
6740 cwd = getcwd(NULL, 0);
6741 if (cwd == NULL) {
6742 error = got_error_from_errno("getcwd");
6743 goto done;
6746 error = got_repo_pack_fds_open(&pack_fds);
6747 if (error != NULL)
6748 goto done;
6750 if (repo_path == NULL) {
6751 error = got_worktree_open(&worktree, cwd,
6752 GOT_WORKTREE_GOT_DIR);
6753 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6754 goto done;
6755 else
6756 error = NULL;
6757 if (worktree) {
6758 repo_path =
6759 strdup(got_worktree_get_repo_path(worktree));
6760 if (repo_path == NULL)
6761 error = got_error_from_errno("strdup");
6762 if (error)
6763 goto done;
6764 } else {
6765 repo_path = strdup(cwd);
6766 if (repo_path == NULL) {
6767 error = got_error_from_errno("strdup");
6768 goto done;
6773 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6774 if (error != NULL)
6775 goto done;
6777 #ifndef PROFILE
6778 if (do_list) {
6779 /* Remove "cpath" promise. */
6780 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6781 NULL) == -1)
6782 err(1, "pledge");
6784 #endif
6786 error = apply_unveil(got_repo_get_path(repo), do_list,
6787 worktree ? got_worktree_get_root_path(worktree) : NULL);
6788 if (error)
6789 goto done;
6791 if (do_list)
6792 error = list_refs(repo, refname, sort_by_time);
6793 else if (do_delete)
6794 error = delete_ref_by_name(repo, refname);
6795 else if (symref_target)
6796 error = add_symref(repo, refname, symref_target);
6797 else {
6798 if (obj_arg == NULL)
6799 usage_ref();
6801 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6802 repo, worktree);
6803 if (error != NULL)
6804 goto done;
6805 if (keyword_idstr != NULL)
6806 obj_arg = keyword_idstr;
6808 error = add_ref(repo, refname, obj_arg);
6810 done:
6811 free(refname);
6812 if (repo) {
6813 const struct got_error *close_err = got_repo_close(repo);
6814 if (error == NULL)
6815 error = close_err;
6817 if (worktree)
6818 got_worktree_close(worktree);
6819 if (pack_fds) {
6820 const struct got_error *pack_err =
6821 got_repo_pack_fds_close(pack_fds);
6822 if (error == NULL)
6823 error = pack_err;
6825 free(cwd);
6826 free(repo_path);
6827 free(keyword_idstr);
6828 return error;
6831 __dead static void
6832 usage_branch(void)
6834 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6835 "[-r repository-path] [name]\n", getprogname());
6836 exit(1);
6839 static const struct got_error *
6840 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6841 struct got_reference *ref)
6843 const struct got_error *err = NULL;
6844 const char *refname;
6845 char *refstr;
6846 char marker = ' ';
6848 refname = got_ref_get_name(ref);
6849 if (worktree && strcmp(refname,
6850 got_worktree_get_head_ref_name(worktree)) == 0) {
6851 err = got_worktree_get_state(&marker, repo, worktree,
6852 check_cancelled, NULL);
6853 if (err != NULL)
6854 return err;
6857 if (strncmp(refname, "refs/heads/", 11) == 0)
6858 refname += 11;
6859 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6860 refname += 18;
6861 if (strncmp(refname, "refs/remotes/", 13) == 0)
6862 refname += 13;
6864 refstr = got_ref_to_str(ref);
6865 if (refstr == NULL)
6866 return got_error_from_errno("got_ref_to_str");
6868 printf("%c %s: %s\n", marker, refname, refstr);
6869 free(refstr);
6870 return NULL;
6873 static const struct got_error *
6874 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6876 const char *refname;
6878 if (worktree == NULL)
6879 return got_error(GOT_ERR_NOT_WORKTREE);
6881 refname = got_worktree_get_head_ref_name(worktree);
6883 if (strncmp(refname, "refs/heads/", 11) == 0)
6884 refname += 11;
6885 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6886 refname += 18;
6888 printf("%s\n", refname);
6890 return NULL;
6893 static const struct got_error *
6894 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6895 int sort_by_time)
6897 static const struct got_error *err = NULL;
6898 struct got_reflist_head refs;
6899 struct got_reflist_entry *re;
6900 struct got_reference *temp_ref = NULL;
6901 int rebase_in_progress, histedit_in_progress;
6903 TAILQ_INIT(&refs);
6905 if (worktree) {
6906 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6907 worktree);
6908 if (err)
6909 return err;
6911 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6912 worktree);
6913 if (err)
6914 return err;
6916 if (rebase_in_progress || histedit_in_progress) {
6917 err = got_ref_open(&temp_ref, repo,
6918 got_worktree_get_head_ref_name(worktree), 0);
6919 if (err)
6920 return err;
6921 list_branch(repo, worktree, temp_ref);
6922 got_ref_close(temp_ref);
6926 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6927 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6928 repo);
6929 if (err)
6930 return err;
6932 TAILQ_FOREACH(re, &refs, entry)
6933 list_branch(repo, worktree, re->ref);
6935 got_ref_list_free(&refs);
6937 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6938 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6939 repo);
6940 if (err)
6941 return err;
6943 TAILQ_FOREACH(re, &refs, entry)
6944 list_branch(repo, worktree, re->ref);
6946 got_ref_list_free(&refs);
6948 return NULL;
6951 static const struct got_error *
6952 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6953 const char *branch_name)
6955 const struct got_error *err = NULL;
6956 struct got_reference *ref = NULL;
6957 char *refname, *remote_refname = NULL;
6959 if (strncmp(branch_name, "refs/", 5) == 0)
6960 branch_name += 5;
6961 if (strncmp(branch_name, "heads/", 6) == 0)
6962 branch_name += 6;
6963 else if (strncmp(branch_name, "remotes/", 8) == 0)
6964 branch_name += 8;
6966 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6967 return got_error_from_errno("asprintf");
6969 if (asprintf(&remote_refname, "refs/remotes/%s",
6970 branch_name) == -1) {
6971 err = got_error_from_errno("asprintf");
6972 goto done;
6975 err = got_ref_open(&ref, repo, refname, 0);
6976 if (err) {
6977 const struct got_error *err2;
6978 if (err->code != GOT_ERR_NOT_REF)
6979 goto done;
6981 * Keep 'err' intact such that if neither branch exists
6982 * we report "refs/heads" rather than "refs/remotes" in
6983 * our error message.
6985 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6986 if (err2)
6987 goto done;
6988 err = NULL;
6991 if (worktree &&
6992 strcmp(got_worktree_get_head_ref_name(worktree),
6993 got_ref_get_name(ref)) == 0) {
6994 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6995 "will not delete this work tree's current branch");
6996 goto done;
6999 err = delete_ref(repo, ref);
7000 done:
7001 if (ref)
7002 got_ref_close(ref);
7003 free(refname);
7004 free(remote_refname);
7005 return err;
7008 static const struct got_error *
7009 add_branch(struct got_repository *repo, const char *branch_name,
7010 struct got_object_id *base_commit_id)
7012 const struct got_error *err = NULL;
7013 struct got_reference *ref = NULL;
7014 char *refname = NULL;
7017 * Don't let the user create a branch name with a leading '-'.
7018 * While technically a valid reference name, this case is usually
7019 * an unintended typo.
7021 if (branch_name[0] == '-')
7022 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7024 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7025 branch_name += 11;
7027 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7028 err = got_error_from_errno("asprintf");
7029 goto done;
7032 err = got_ref_open(&ref, repo, refname, 0);
7033 if (err == NULL) {
7034 err = got_error(GOT_ERR_BRANCH_EXISTS);
7035 goto done;
7036 } else if (err->code != GOT_ERR_NOT_REF)
7037 goto done;
7039 err = got_ref_alloc(&ref, refname, base_commit_id);
7040 if (err)
7041 goto done;
7043 err = got_ref_write(ref, repo);
7044 done:
7045 if (ref)
7046 got_ref_close(ref);
7047 free(refname);
7048 return err;
7051 static const struct got_error *
7052 cmd_branch(int argc, char *argv[])
7054 const struct got_error *error = NULL;
7055 struct got_repository *repo = NULL;
7056 struct got_worktree *worktree = NULL;
7057 char *cwd = NULL, *repo_path = NULL;
7058 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7059 const char *delref = NULL, *commit_id_arg = NULL;
7060 struct got_reference *ref = NULL;
7061 struct got_pathlist_head paths;
7062 struct got_object_id *commit_id = NULL;
7063 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7064 int *pack_fds = NULL;
7066 TAILQ_INIT(&paths);
7068 #ifndef PROFILE
7069 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7070 "sendfd unveil", NULL) == -1)
7071 err(1, "pledge");
7072 #endif
7074 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7075 switch (ch) {
7076 case 'c':
7077 commit_id_arg = optarg;
7078 break;
7079 case 'd':
7080 delref = optarg;
7081 break;
7082 case 'l':
7083 do_list = 1;
7084 break;
7085 case 'n':
7086 do_update = 0;
7087 break;
7088 case 'r':
7089 repo_path = realpath(optarg, NULL);
7090 if (repo_path == NULL)
7091 return got_error_from_errno2("realpath",
7092 optarg);
7093 got_path_strip_trailing_slashes(repo_path);
7094 break;
7095 case 't':
7096 sort_by_time = 1;
7097 break;
7098 default:
7099 usage_branch();
7100 /* NOTREACHED */
7104 if (do_list && delref)
7105 option_conflict('l', 'd');
7106 if (sort_by_time && !do_list)
7107 errx(1, "-t option requires -l option");
7109 argc -= optind;
7110 argv += optind;
7112 if (!do_list && !delref && argc == 0)
7113 do_show = 1;
7115 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7116 errx(1, "-c option can only be used when creating a branch");
7118 if (do_list || delref) {
7119 if (argc > 0)
7120 usage_branch();
7121 } else if (!do_show && argc != 1)
7122 usage_branch();
7124 cwd = getcwd(NULL, 0);
7125 if (cwd == NULL) {
7126 error = got_error_from_errno("getcwd");
7127 goto done;
7130 error = got_repo_pack_fds_open(&pack_fds);
7131 if (error != NULL)
7132 goto done;
7134 if (repo_path == NULL) {
7135 error = got_worktree_open(&worktree, cwd,
7136 GOT_WORKTREE_GOT_DIR);
7137 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7138 goto done;
7139 else
7140 error = NULL;
7141 if (worktree) {
7142 repo_path =
7143 strdup(got_worktree_get_repo_path(worktree));
7144 if (repo_path == NULL)
7145 error = got_error_from_errno("strdup");
7146 if (error)
7147 goto done;
7148 } else {
7149 repo_path = strdup(cwd);
7150 if (repo_path == NULL) {
7151 error = got_error_from_errno("strdup");
7152 goto done;
7157 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7158 if (error != NULL)
7159 goto done;
7161 #ifndef PROFILE
7162 if (do_list || do_show) {
7163 /* Remove "cpath" promise. */
7164 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7165 NULL) == -1)
7166 err(1, "pledge");
7168 #endif
7170 error = apply_unveil(got_repo_get_path(repo), do_list,
7171 worktree ? got_worktree_get_root_path(worktree) : NULL);
7172 if (error)
7173 goto done;
7175 if (do_show)
7176 error = show_current_branch(repo, worktree);
7177 else if (do_list)
7178 error = list_branches(repo, worktree, sort_by_time);
7179 else if (delref)
7180 error = delete_branch(repo, worktree, delref);
7181 else {
7182 struct got_reflist_head refs;
7183 TAILQ_INIT(&refs);
7184 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7185 NULL);
7186 if (error)
7187 goto done;
7188 if (commit_id_arg == NULL)
7189 commit_id_arg = worktree ?
7190 got_worktree_get_head_ref_name(worktree) :
7191 GOT_REF_HEAD;
7192 else {
7193 error = got_keyword_to_idstr(&keyword_idstr,
7194 commit_id_arg, repo, worktree);
7195 if (error != NULL)
7196 goto done;
7197 if (keyword_idstr != NULL)
7198 commit_id_arg = keyword_idstr;
7200 error = got_repo_match_object_id(&commit_id, NULL,
7201 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7202 got_ref_list_free(&refs);
7203 if (error)
7204 goto done;
7205 error = add_branch(repo, argv[0], commit_id);
7206 if (error)
7207 goto done;
7208 if (worktree && do_update) {
7209 struct got_update_progress_arg upa;
7210 char *branch_refname = NULL;
7212 error = got_object_id_str(&commit_id_str, commit_id);
7213 if (error)
7214 goto done;
7215 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7216 worktree);
7217 if (error)
7218 goto done;
7219 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7220 == -1) {
7221 error = got_error_from_errno("asprintf");
7222 goto done;
7224 error = got_ref_open(&ref, repo, branch_refname, 0);
7225 free(branch_refname);
7226 if (error)
7227 goto done;
7228 error = switch_head_ref(ref, commit_id, worktree,
7229 repo);
7230 if (error)
7231 goto done;
7232 error = got_worktree_set_base_commit_id(worktree, repo,
7233 commit_id);
7234 if (error)
7235 goto done;
7236 memset(&upa, 0, sizeof(upa));
7237 error = got_worktree_checkout_files(worktree, &paths,
7238 repo, update_progress, &upa, check_cancelled,
7239 NULL);
7240 if (error)
7241 goto done;
7242 if (upa.did_something) {
7243 printf("Updated to %s: %s\n",
7244 got_worktree_get_head_ref_name(worktree),
7245 commit_id_str);
7247 print_update_progress_stats(&upa);
7250 done:
7251 free(keyword_idstr);
7252 if (ref)
7253 got_ref_close(ref);
7254 if (repo) {
7255 const struct got_error *close_err = got_repo_close(repo);
7256 if (error == NULL)
7257 error = close_err;
7259 if (worktree)
7260 got_worktree_close(worktree);
7261 if (pack_fds) {
7262 const struct got_error *pack_err =
7263 got_repo_pack_fds_close(pack_fds);
7264 if (error == NULL)
7265 error = pack_err;
7267 free(cwd);
7268 free(repo_path);
7269 free(commit_id);
7270 free(commit_id_str);
7271 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7272 return error;
7276 __dead static void
7277 usage_tag(void)
7279 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7280 "[-r repository-path] [-s signer-id] name\n", getprogname());
7281 exit(1);
7284 #if 0
7285 static const struct got_error *
7286 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7288 const struct got_error *err = NULL;
7289 struct got_reflist_entry *re, *se, *new;
7290 struct got_object_id *re_id, *se_id;
7291 struct got_tag_object *re_tag, *se_tag;
7292 time_t re_time, se_time;
7294 STAILQ_FOREACH(re, tags, entry) {
7295 se = STAILQ_FIRST(sorted);
7296 if (se == NULL) {
7297 err = got_reflist_entry_dup(&new, re);
7298 if (err)
7299 return err;
7300 STAILQ_INSERT_HEAD(sorted, new, entry);
7301 continue;
7302 } else {
7303 err = got_ref_resolve(&re_id, repo, re->ref);
7304 if (err)
7305 break;
7306 err = got_object_open_as_tag(&re_tag, repo, re_id);
7307 free(re_id);
7308 if (err)
7309 break;
7310 re_time = got_object_tag_get_tagger_time(re_tag);
7311 got_object_tag_close(re_tag);
7314 while (se) {
7315 err = got_ref_resolve(&se_id, repo, re->ref);
7316 if (err)
7317 break;
7318 err = got_object_open_as_tag(&se_tag, repo, se_id);
7319 free(se_id);
7320 if (err)
7321 break;
7322 se_time = got_object_tag_get_tagger_time(se_tag);
7323 got_object_tag_close(se_tag);
7325 if (se_time > re_time) {
7326 err = got_reflist_entry_dup(&new, re);
7327 if (err)
7328 return err;
7329 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7330 break;
7332 se = STAILQ_NEXT(se, entry);
7333 continue;
7336 done:
7337 return err;
7339 #endif
7341 static const struct got_error *
7342 get_tag_refname(char **refname, const char *tag_name)
7344 const struct got_error *err;
7346 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7347 *refname = strdup(tag_name);
7348 if (*refname == NULL)
7349 return got_error_from_errno("strdup");
7350 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7351 err = got_error_from_errno("asprintf");
7352 *refname = NULL;
7353 return err;
7356 return NULL;
7359 static const struct got_error *
7360 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7361 const char *allowed_signers, const char *revoked_signers, int verbosity)
7363 static const struct got_error *err = NULL;
7364 struct got_reflist_head refs;
7365 struct got_reflist_entry *re;
7366 char *wanted_refname = NULL;
7367 int bad_sigs = 0;
7369 TAILQ_INIT(&refs);
7371 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7372 if (err)
7373 return err;
7375 if (tag_name) {
7376 struct got_reference *ref;
7377 err = get_tag_refname(&wanted_refname, tag_name);
7378 if (err)
7379 goto done;
7380 /* Wanted tag reference should exist. */
7381 err = got_ref_open(&ref, repo, wanted_refname, 0);
7382 if (err)
7383 goto done;
7384 got_ref_close(ref);
7387 TAILQ_FOREACH(re, &refs, entry) {
7388 const char *refname;
7389 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7390 char datebuf[26];
7391 const char *tagger, *ssh_sig = NULL;
7392 char *sig_msg = NULL;
7393 time_t tagger_time;
7394 struct got_object_id *id;
7395 struct got_tag_object *tag;
7396 struct got_commit_object *commit = NULL;
7398 refname = got_ref_get_name(re->ref);
7399 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7400 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7401 continue;
7402 refname += 10;
7403 refstr = got_ref_to_str(re->ref);
7404 if (refstr == NULL) {
7405 err = got_error_from_errno("got_ref_to_str");
7406 break;
7409 err = got_ref_resolve(&id, repo, re->ref);
7410 if (err)
7411 break;
7412 err = got_object_open_as_tag(&tag, repo, id);
7413 if (err) {
7414 if (err->code != GOT_ERR_OBJ_TYPE) {
7415 free(id);
7416 break;
7418 /* "lightweight" tag */
7419 err = got_object_open_as_commit(&commit, repo, id);
7420 if (err) {
7421 free(id);
7422 break;
7424 tagger = got_object_commit_get_committer(commit);
7425 tagger_time =
7426 got_object_commit_get_committer_time(commit);
7427 err = got_object_id_str(&id_str, id);
7428 free(id);
7429 if (err)
7430 break;
7431 } else {
7432 free(id);
7433 tagger = got_object_tag_get_tagger(tag);
7434 tagger_time = got_object_tag_get_tagger_time(tag);
7435 err = got_object_id_str(&id_str,
7436 got_object_tag_get_object_id(tag));
7437 if (err)
7438 break;
7441 if (tag && verify_tags) {
7442 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7443 got_object_tag_get_message(tag));
7444 if (ssh_sig && allowed_signers == NULL) {
7445 err = got_error_msg(
7446 GOT_ERR_VERIFY_TAG_SIGNATURE,
7447 "SSH signature verification requires "
7448 "setting allowed_signers in "
7449 "got.conf(5)");
7450 break;
7454 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7455 free(refstr);
7456 printf("from: %s\n", tagger);
7457 datestr = get_datestr(&tagger_time, datebuf);
7458 if (datestr)
7459 printf("date: %s UTC\n", datestr);
7460 if (commit)
7461 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7462 else {
7463 switch (got_object_tag_get_object_type(tag)) {
7464 case GOT_OBJ_TYPE_BLOB:
7465 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7466 id_str);
7467 break;
7468 case GOT_OBJ_TYPE_TREE:
7469 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7470 id_str);
7471 break;
7472 case GOT_OBJ_TYPE_COMMIT:
7473 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7474 id_str);
7475 break;
7476 case GOT_OBJ_TYPE_TAG:
7477 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7478 id_str);
7479 break;
7480 default:
7481 break;
7484 free(id_str);
7486 if (ssh_sig) {
7487 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7488 allowed_signers, revoked_signers, verbosity);
7489 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7490 bad_sigs = 1;
7491 else if (err)
7492 break;
7493 printf("signature: %s", sig_msg);
7494 free(sig_msg);
7495 sig_msg = NULL;
7498 if (commit) {
7499 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7500 if (err)
7501 break;
7502 got_object_commit_close(commit);
7503 } else {
7504 tagmsg0 = strdup(got_object_tag_get_message(tag));
7505 got_object_tag_close(tag);
7506 if (tagmsg0 == NULL) {
7507 err = got_error_from_errno("strdup");
7508 break;
7512 tagmsg = tagmsg0;
7513 do {
7514 line = strsep(&tagmsg, "\n");
7515 if (line)
7516 printf(" %s\n", line);
7517 } while (line);
7518 free(tagmsg0);
7520 done:
7521 got_ref_list_free(&refs);
7522 free(wanted_refname);
7524 if (err == NULL && bad_sigs)
7525 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7526 return err;
7529 static const struct got_error *
7530 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7531 const char *tag_name, const char *repo_path)
7533 const struct got_error *err = NULL;
7534 char *template = NULL, *initial_content = NULL;
7535 char *editor = NULL;
7536 int initial_content_len;
7537 int fd = -1;
7539 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7540 err = got_error_from_errno("asprintf");
7541 goto done;
7544 initial_content_len = asprintf(&initial_content,
7545 "\n# tagging commit %s as %s\n",
7546 commit_id_str, tag_name);
7547 if (initial_content_len == -1) {
7548 err = got_error_from_errno("asprintf");
7549 goto done;
7552 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7553 if (err)
7554 goto done;
7556 if (write(fd, initial_content, initial_content_len) == -1) {
7557 err = got_error_from_errno2("write", *tagmsg_path);
7558 goto done;
7560 if (close(fd) == -1) {
7561 err = got_error_from_errno2("close", *tagmsg_path);
7562 goto done;
7564 fd = -1;
7566 err = get_editor(&editor);
7567 if (err)
7568 goto done;
7569 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7570 initial_content_len, 1);
7571 done:
7572 free(initial_content);
7573 free(template);
7574 free(editor);
7576 if (fd != -1 && close(fd) == -1 && err == NULL)
7577 err = got_error_from_errno2("close", *tagmsg_path);
7579 if (err) {
7580 free(*tagmsg);
7581 *tagmsg = NULL;
7583 return err;
7586 static const struct got_error *
7587 add_tag(struct got_repository *repo, const char *tagger,
7588 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7589 const char *signer_id, int verbosity)
7591 const struct got_error *err = NULL;
7592 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7593 char *label = NULL, *commit_id_str = NULL;
7594 struct got_reference *ref = NULL;
7595 char *refname = NULL, *tagmsg = NULL;
7596 char *tagmsg_path = NULL, *tag_id_str = NULL;
7597 int preserve_tagmsg = 0;
7598 struct got_reflist_head refs;
7600 TAILQ_INIT(&refs);
7603 * Don't let the user create a tag name with a leading '-'.
7604 * While technically a valid reference name, this case is usually
7605 * an unintended typo.
7607 if (tag_name[0] == '-')
7608 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7610 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7611 if (err)
7612 goto done;
7614 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7615 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7616 if (err)
7617 goto done;
7619 err = got_object_id_str(&commit_id_str, commit_id);
7620 if (err)
7621 goto done;
7623 err = get_tag_refname(&refname, tag_name);
7624 if (err)
7625 goto done;
7626 if (strncmp("refs/tags/", tag_name, 10) == 0)
7627 tag_name += 10;
7629 err = got_ref_open(&ref, repo, refname, 0);
7630 if (err == NULL) {
7631 err = got_error(GOT_ERR_TAG_EXISTS);
7632 goto done;
7633 } else if (err->code != GOT_ERR_NOT_REF)
7634 goto done;
7636 if (tagmsg_arg == NULL) {
7637 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7638 tag_name, got_repo_get_path(repo));
7639 if (err) {
7640 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7641 tagmsg_path != NULL)
7642 preserve_tagmsg = 1;
7643 goto done;
7645 /* Editor is done; we can now apply unveil(2) */
7646 err = got_sigs_apply_unveil();
7647 if (err)
7648 goto done;
7649 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7650 if (err)
7651 goto done;
7654 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7655 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7656 verbosity);
7657 if (err) {
7658 if (tagmsg_path)
7659 preserve_tagmsg = 1;
7660 goto done;
7663 err = got_ref_alloc(&ref, refname, tag_id);
7664 if (err) {
7665 if (tagmsg_path)
7666 preserve_tagmsg = 1;
7667 goto done;
7670 err = got_ref_write(ref, repo);
7671 if (err) {
7672 if (tagmsg_path)
7673 preserve_tagmsg = 1;
7674 goto done;
7677 err = got_object_id_str(&tag_id_str, tag_id);
7678 if (err) {
7679 if (tagmsg_path)
7680 preserve_tagmsg = 1;
7681 goto done;
7683 printf("Created tag %s\n", tag_id_str);
7684 done:
7685 if (preserve_tagmsg) {
7686 fprintf(stderr, "%s: tag message preserved in %s\n",
7687 getprogname(), tagmsg_path);
7688 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7689 err = got_error_from_errno2("unlink", tagmsg_path);
7690 free(tag_id_str);
7691 if (ref)
7692 got_ref_close(ref);
7693 free(commit_id);
7694 free(commit_id_str);
7695 free(refname);
7696 free(tagmsg);
7697 free(tagmsg_path);
7698 got_ref_list_free(&refs);
7699 return err;
7702 static const struct got_error *
7703 cmd_tag(int argc, char *argv[])
7705 const struct got_error *error = NULL;
7706 struct got_repository *repo = NULL;
7707 struct got_worktree *worktree = NULL;
7708 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7709 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7710 char *allowed_signers = NULL, *revoked_signers = NULL;
7711 const char *signer_id = NULL;
7712 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7713 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7714 int *pack_fds = NULL;
7716 #ifndef PROFILE
7717 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7718 "sendfd unveil", NULL) == -1)
7719 err(1, "pledge");
7720 #endif
7722 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7723 switch (ch) {
7724 case 'c':
7725 commit_id_arg = optarg;
7726 break;
7727 case 'l':
7728 do_list = 1;
7729 break;
7730 case 'm':
7731 tagmsg = optarg;
7732 break;
7733 case 'r':
7734 repo_path = realpath(optarg, NULL);
7735 if (repo_path == NULL) {
7736 error = got_error_from_errno2("realpath",
7737 optarg);
7738 goto done;
7740 got_path_strip_trailing_slashes(repo_path);
7741 break;
7742 case 's':
7743 signer_id = optarg;
7744 break;
7745 case 'V':
7746 verify_tags = 1;
7747 break;
7748 case 'v':
7749 if (verbosity < 0)
7750 verbosity = 0;
7751 else if (verbosity < 3)
7752 verbosity++;
7753 break;
7754 default:
7755 usage_tag();
7756 /* NOTREACHED */
7760 argc -= optind;
7761 argv += optind;
7763 if (do_list || verify_tags) {
7764 if (commit_id_arg != NULL)
7765 errx(1,
7766 "-c option can only be used when creating a tag");
7767 if (tagmsg) {
7768 if (do_list)
7769 option_conflict('l', 'm');
7770 else
7771 option_conflict('V', 'm');
7773 if (signer_id) {
7774 if (do_list)
7775 option_conflict('l', 's');
7776 else
7777 option_conflict('V', 's');
7779 if (argc > 1)
7780 usage_tag();
7781 } else if (argc != 1)
7782 usage_tag();
7784 if (argc == 1)
7785 tag_name = argv[0];
7787 cwd = getcwd(NULL, 0);
7788 if (cwd == NULL) {
7789 error = got_error_from_errno("getcwd");
7790 goto done;
7793 error = got_repo_pack_fds_open(&pack_fds);
7794 if (error != NULL)
7795 goto done;
7797 if (repo_path == NULL) {
7798 error = got_worktree_open(&worktree, cwd,
7799 GOT_WORKTREE_GOT_DIR);
7800 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7801 goto done;
7802 else
7803 error = NULL;
7804 if (worktree) {
7805 repo_path =
7806 strdup(got_worktree_get_repo_path(worktree));
7807 if (repo_path == NULL)
7808 error = got_error_from_errno("strdup");
7809 if (error)
7810 goto done;
7811 } else {
7812 repo_path = strdup(cwd);
7813 if (repo_path == NULL) {
7814 error = got_error_from_errno("strdup");
7815 goto done;
7820 if (do_list || verify_tags) {
7821 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7822 if (error != NULL)
7823 goto done;
7824 error = get_allowed_signers(&allowed_signers, repo, worktree);
7825 if (error)
7826 goto done;
7827 error = get_revoked_signers(&revoked_signers, repo, worktree);
7828 if (error)
7829 goto done;
7830 if (worktree) {
7831 /* Release work tree lock. */
7832 got_worktree_close(worktree);
7833 worktree = NULL;
7837 * Remove "cpath" promise unless needed for signature tmpfile
7838 * creation.
7840 if (verify_tags)
7841 got_sigs_apply_unveil();
7842 else {
7843 #ifndef PROFILE
7844 if (pledge("stdio rpath wpath flock proc exec sendfd "
7845 "unveil", NULL) == -1)
7846 err(1, "pledge");
7847 #endif
7849 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7850 if (error)
7851 goto done;
7852 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7853 revoked_signers, verbosity);
7854 } else {
7855 error = get_gitconfig_path(&gitconfig_path);
7856 if (error)
7857 goto done;
7858 error = got_repo_open(&repo, repo_path, gitconfig_path,
7859 pack_fds);
7860 if (error != NULL)
7861 goto done;
7863 error = get_author(&tagger, repo, worktree);
7864 if (error)
7865 goto done;
7866 if (signer_id == NULL)
7867 signer_id = get_signer_id(repo, worktree);
7869 if (tagmsg) {
7870 if (signer_id) {
7871 error = got_sigs_apply_unveil();
7872 if (error)
7873 goto done;
7875 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7876 if (error)
7877 goto done;
7880 if (commit_id_arg == NULL) {
7881 struct got_reference *head_ref;
7882 struct got_object_id *commit_id;
7883 error = got_ref_open(&head_ref, repo,
7884 worktree ? got_worktree_get_head_ref_name(worktree)
7885 : GOT_REF_HEAD, 0);
7886 if (error)
7887 goto done;
7888 error = got_ref_resolve(&commit_id, repo, head_ref);
7889 got_ref_close(head_ref);
7890 if (error)
7891 goto done;
7892 error = got_object_id_str(&commit_id_str, commit_id);
7893 free(commit_id);
7894 if (error)
7895 goto done;
7896 } else {
7897 error = got_keyword_to_idstr(&keyword_idstr,
7898 commit_id_arg, repo, worktree);
7899 if (error != NULL)
7900 goto done;
7901 commit_id_str = keyword_idstr;
7904 if (worktree) {
7905 /* Release work tree lock. */
7906 got_worktree_close(worktree);
7907 worktree = NULL;
7910 error = add_tag(repo, tagger, tag_name,
7911 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7912 signer_id, verbosity);
7914 done:
7915 if (repo) {
7916 const struct got_error *close_err = got_repo_close(repo);
7917 if (error == NULL)
7918 error = close_err;
7920 if (worktree)
7921 got_worktree_close(worktree);
7922 if (pack_fds) {
7923 const struct got_error *pack_err =
7924 got_repo_pack_fds_close(pack_fds);
7925 if (error == NULL)
7926 error = pack_err;
7928 free(cwd);
7929 free(repo_path);
7930 free(gitconfig_path);
7931 free(commit_id_str);
7932 free(tagger);
7933 free(allowed_signers);
7934 free(revoked_signers);
7935 return error;
7938 __dead static void
7939 usage_add(void)
7941 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7942 exit(1);
7945 static const struct got_error *
7946 add_progress(void *arg, unsigned char status, const char *path)
7948 while (path[0] == '/')
7949 path++;
7950 printf("%c %s\n", status, path);
7951 return NULL;
7954 static const struct got_error *
7955 cmd_add(int argc, char *argv[])
7957 const struct got_error *error = NULL;
7958 struct got_repository *repo = NULL;
7959 struct got_worktree *worktree = NULL;
7960 char *cwd = NULL;
7961 struct got_pathlist_head paths;
7962 struct got_pathlist_entry *pe;
7963 int ch, can_recurse = 0, no_ignores = 0;
7964 int *pack_fds = NULL;
7966 TAILQ_INIT(&paths);
7968 #ifndef PROFILE
7969 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7970 NULL) == -1)
7971 err(1, "pledge");
7972 #endif
7974 while ((ch = getopt(argc, argv, "IR")) != -1) {
7975 switch (ch) {
7976 case 'I':
7977 no_ignores = 1;
7978 break;
7979 case 'R':
7980 can_recurse = 1;
7981 break;
7982 default:
7983 usage_add();
7984 /* NOTREACHED */
7988 argc -= optind;
7989 argv += optind;
7991 if (argc < 1)
7992 usage_add();
7994 cwd = getcwd(NULL, 0);
7995 if (cwd == NULL) {
7996 error = got_error_from_errno("getcwd");
7997 goto done;
8000 error = got_repo_pack_fds_open(&pack_fds);
8001 if (error != NULL)
8002 goto done;
8004 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8005 if (error) {
8006 if (error->code == GOT_ERR_NOT_WORKTREE)
8007 error = wrap_not_worktree_error(error, "add", cwd);
8008 goto done;
8011 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8012 NULL, pack_fds);
8013 if (error != NULL)
8014 goto done;
8016 error = apply_unveil(got_repo_get_path(repo), 1,
8017 got_worktree_get_root_path(worktree));
8018 if (error)
8019 goto done;
8021 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8022 if (error)
8023 goto done;
8025 if (!can_recurse) {
8026 char *ondisk_path;
8027 struct stat sb;
8028 TAILQ_FOREACH(pe, &paths, entry) {
8029 if (asprintf(&ondisk_path, "%s/%s",
8030 got_worktree_get_root_path(worktree),
8031 pe->path) == -1) {
8032 error = got_error_from_errno("asprintf");
8033 goto done;
8035 if (lstat(ondisk_path, &sb) == -1) {
8036 if (errno == ENOENT) {
8037 free(ondisk_path);
8038 continue;
8040 error = got_error_from_errno2("lstat",
8041 ondisk_path);
8042 free(ondisk_path);
8043 goto done;
8045 free(ondisk_path);
8046 if (S_ISDIR(sb.st_mode)) {
8047 error = got_error_msg(GOT_ERR_BAD_PATH,
8048 "adding directories requires -R option");
8049 goto done;
8054 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8055 NULL, repo, no_ignores);
8056 done:
8057 if (repo) {
8058 const struct got_error *close_err = got_repo_close(repo);
8059 if (error == NULL)
8060 error = close_err;
8062 if (worktree)
8063 got_worktree_close(worktree);
8064 if (pack_fds) {
8065 const struct got_error *pack_err =
8066 got_repo_pack_fds_close(pack_fds);
8067 if (error == NULL)
8068 error = pack_err;
8070 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8071 free(cwd);
8072 return error;
8075 __dead static void
8076 usage_remove(void)
8078 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8079 getprogname());
8080 exit(1);
8083 static const struct got_error *
8084 print_remove_status(void *arg, unsigned char status,
8085 unsigned char staged_status, const char *path)
8087 while (path[0] == '/')
8088 path++;
8089 if (status == GOT_STATUS_NONEXISTENT)
8090 return NULL;
8091 if (status == staged_status && (status == GOT_STATUS_DELETE))
8092 status = GOT_STATUS_NO_CHANGE;
8093 printf("%c%c %s\n", status, staged_status, path);
8094 return NULL;
8097 static const struct got_error *
8098 cmd_remove(int argc, char *argv[])
8100 const struct got_error *error = NULL;
8101 struct got_worktree *worktree = NULL;
8102 struct got_repository *repo = NULL;
8103 const char *status_codes = NULL;
8104 char *cwd = NULL;
8105 struct got_pathlist_head paths;
8106 struct got_pathlist_entry *pe;
8107 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8108 int ignore_missing_paths = 0;
8109 int *pack_fds = NULL;
8111 TAILQ_INIT(&paths);
8113 #ifndef PROFILE
8114 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8115 NULL) == -1)
8116 err(1, "pledge");
8117 #endif
8119 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8120 switch (ch) {
8121 case 'f':
8122 delete_local_mods = 1;
8123 ignore_missing_paths = 1;
8124 break;
8125 case 'k':
8126 keep_on_disk = 1;
8127 break;
8128 case 'R':
8129 can_recurse = 1;
8130 break;
8131 case 's':
8132 for (i = 0; optarg[i] != '\0'; i++) {
8133 switch (optarg[i]) {
8134 case GOT_STATUS_MODIFY:
8135 delete_local_mods = 1;
8136 break;
8137 case GOT_STATUS_MISSING:
8138 ignore_missing_paths = 1;
8139 break;
8140 default:
8141 errx(1, "invalid status code '%c'",
8142 optarg[i]);
8145 status_codes = optarg;
8146 break;
8147 default:
8148 usage_remove();
8149 /* NOTREACHED */
8153 argc -= optind;
8154 argv += optind;
8156 if (argc < 1)
8157 usage_remove();
8159 cwd = getcwd(NULL, 0);
8160 if (cwd == NULL) {
8161 error = got_error_from_errno("getcwd");
8162 goto done;
8165 error = got_repo_pack_fds_open(&pack_fds);
8166 if (error != NULL)
8167 goto done;
8169 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8170 if (error) {
8171 if (error->code == GOT_ERR_NOT_WORKTREE)
8172 error = wrap_not_worktree_error(error, "remove", cwd);
8173 goto done;
8176 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8177 NULL, pack_fds);
8178 if (error)
8179 goto done;
8181 error = apply_unveil(got_repo_get_path(repo), 1,
8182 got_worktree_get_root_path(worktree));
8183 if (error)
8184 goto done;
8186 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8187 if (error)
8188 goto done;
8190 if (!can_recurse) {
8191 char *ondisk_path;
8192 struct stat sb;
8193 TAILQ_FOREACH(pe, &paths, entry) {
8194 if (asprintf(&ondisk_path, "%s/%s",
8195 got_worktree_get_root_path(worktree),
8196 pe->path) == -1) {
8197 error = got_error_from_errno("asprintf");
8198 goto done;
8200 if (lstat(ondisk_path, &sb) == -1) {
8201 if (errno == ENOENT) {
8202 free(ondisk_path);
8203 continue;
8205 error = got_error_from_errno2("lstat",
8206 ondisk_path);
8207 free(ondisk_path);
8208 goto done;
8210 free(ondisk_path);
8211 if (S_ISDIR(sb.st_mode)) {
8212 error = got_error_msg(GOT_ERR_BAD_PATH,
8213 "removing directories requires -R option");
8214 goto done;
8219 error = got_worktree_schedule_delete(worktree, &paths,
8220 delete_local_mods, status_codes, print_remove_status, NULL,
8221 repo, keep_on_disk, ignore_missing_paths);
8222 done:
8223 if (repo) {
8224 const struct got_error *close_err = got_repo_close(repo);
8225 if (error == NULL)
8226 error = close_err;
8228 if (worktree)
8229 got_worktree_close(worktree);
8230 if (pack_fds) {
8231 const struct got_error *pack_err =
8232 got_repo_pack_fds_close(pack_fds);
8233 if (error == NULL)
8234 error = pack_err;
8236 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8237 free(cwd);
8238 return error;
8241 __dead static void
8242 usage_patch(void)
8244 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8245 "[patchfile]\n", getprogname());
8246 exit(1);
8249 static const struct got_error *
8250 patch_from_stdin(int *patchfd)
8252 const struct got_error *err = NULL;
8253 ssize_t r;
8254 char buf[BUFSIZ];
8255 sig_t sighup, sigint, sigquit;
8257 *patchfd = got_opentempfd();
8258 if (*patchfd == -1)
8259 return got_error_from_errno("got_opentempfd");
8261 sighup = signal(SIGHUP, SIG_DFL);
8262 sigint = signal(SIGINT, SIG_DFL);
8263 sigquit = signal(SIGQUIT, SIG_DFL);
8265 for (;;) {
8266 r = read(0, buf, sizeof(buf));
8267 if (r == -1) {
8268 err = got_error_from_errno("read");
8269 break;
8271 if (r == 0)
8272 break;
8273 if (write(*patchfd, buf, r) == -1) {
8274 err = got_error_from_errno("write");
8275 break;
8279 signal(SIGHUP, sighup);
8280 signal(SIGINT, sigint);
8281 signal(SIGQUIT, sigquit);
8283 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8284 err = got_error_from_errno("lseek");
8286 if (err != NULL) {
8287 close(*patchfd);
8288 *patchfd = -1;
8291 return err;
8294 struct got_patch_progress_arg {
8295 int did_something;
8296 int conflicts;
8297 int rejects;
8300 static const struct got_error *
8301 patch_progress(void *arg, const char *old, const char *new,
8302 unsigned char status, const struct got_error *error, int old_from,
8303 int old_lines, int new_from, int new_lines, int offset,
8304 int ws_mangled, const struct got_error *hunk_err)
8306 const char *path = new == NULL ? old : new;
8307 struct got_patch_progress_arg *a = arg;
8309 while (*path == '/')
8310 path++;
8312 if (status != GOT_STATUS_NO_CHANGE &&
8313 status != 0 /* per-hunk progress */) {
8314 printf("%c %s\n", status, path);
8315 a->did_something = 1;
8318 if (hunk_err == NULL) {
8319 if (status == GOT_STATUS_CANNOT_UPDATE)
8320 a->rejects++;
8321 else if (status == GOT_STATUS_CONFLICT)
8322 a->conflicts++;
8325 if (error != NULL)
8326 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8328 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8329 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8330 old_lines, new_from, new_lines);
8331 if (hunk_err != NULL)
8332 printf("%s\n", hunk_err->msg);
8333 else if (offset != 0)
8334 printf("applied with offset %d\n", offset);
8335 else
8336 printf("hunk contains mangled whitespace\n");
8339 return NULL;
8342 static void
8343 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8345 if (!ppa->did_something)
8346 return;
8348 if (ppa->conflicts > 0)
8349 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8351 if (ppa->rejects > 0) {
8352 printf("Files where patch failed to apply: %d\n",
8353 ppa->rejects);
8357 static const struct got_error *
8358 cmd_patch(int argc, char *argv[])
8360 const struct got_error *error = NULL, *close_error = NULL;
8361 struct got_worktree *worktree = NULL;
8362 struct got_repository *repo = NULL;
8363 struct got_reflist_head refs;
8364 struct got_object_id *commit_id = NULL;
8365 const char *commit_id_str = NULL;
8366 struct stat sb;
8367 const char *errstr;
8368 char *cwd = NULL, *keyword_idstr = NULL;
8369 int ch, nop = 0, strip = -1, reverse = 0;
8370 int patchfd;
8371 int *pack_fds = NULL;
8372 struct got_patch_progress_arg ppa;
8374 TAILQ_INIT(&refs);
8376 #ifndef PROFILE
8377 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8378 "unveil", NULL) == -1)
8379 err(1, "pledge");
8380 #endif
8382 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8383 switch (ch) {
8384 case 'c':
8385 commit_id_str = optarg;
8386 break;
8387 case 'n':
8388 nop = 1;
8389 break;
8390 case 'p':
8391 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8392 if (errstr != NULL)
8393 errx(1, "pathname strip count is %s: %s",
8394 errstr, optarg);
8395 break;
8396 case 'R':
8397 reverse = 1;
8398 break;
8399 default:
8400 usage_patch();
8401 /* NOTREACHED */
8405 argc -= optind;
8406 argv += optind;
8408 if (argc == 0) {
8409 error = patch_from_stdin(&patchfd);
8410 if (error)
8411 return error;
8412 } else if (argc == 1) {
8413 patchfd = open(argv[0], O_RDONLY);
8414 if (patchfd == -1) {
8415 error = got_error_from_errno2("open", argv[0]);
8416 return error;
8418 if (fstat(patchfd, &sb) == -1) {
8419 error = got_error_from_errno2("fstat", argv[0]);
8420 goto done;
8422 if (!S_ISREG(sb.st_mode)) {
8423 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8424 goto done;
8426 } else
8427 usage_patch();
8429 if ((cwd = getcwd(NULL, 0)) == NULL) {
8430 error = got_error_from_errno("getcwd");
8431 goto done;
8434 error = got_repo_pack_fds_open(&pack_fds);
8435 if (error != NULL)
8436 goto done;
8438 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8439 if (error != NULL)
8440 goto done;
8442 const char *repo_path = got_worktree_get_repo_path(worktree);
8443 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8444 if (error != NULL)
8445 goto done;
8447 error = apply_unveil(got_repo_get_path(repo), 0,
8448 got_worktree_get_root_path(worktree));
8449 if (error != NULL)
8450 goto done;
8452 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8453 if (error)
8454 goto done;
8456 if (commit_id_str != NULL) {
8457 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8458 repo, worktree);
8459 if (error != NULL)
8460 goto done;
8462 error = got_repo_match_object_id(&commit_id, NULL,
8463 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8464 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8465 if (error)
8466 goto done;
8469 memset(&ppa, 0, sizeof(ppa));
8470 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8471 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8472 print_patch_progress_stats(&ppa);
8473 done:
8474 got_ref_list_free(&refs);
8475 free(keyword_idstr);
8476 free(commit_id);
8477 if (repo) {
8478 close_error = got_repo_close(repo);
8479 if (error == NULL)
8480 error = close_error;
8482 if (worktree != NULL) {
8483 close_error = got_worktree_close(worktree);
8484 if (error == NULL)
8485 error = close_error;
8487 if (pack_fds) {
8488 const struct got_error *pack_err =
8489 got_repo_pack_fds_close(pack_fds);
8490 if (error == NULL)
8491 error = pack_err;
8493 free(cwd);
8494 return error;
8497 __dead static void
8498 usage_revert(void)
8500 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8501 getprogname());
8502 exit(1);
8505 static const struct got_error *
8506 revert_progress(void *arg, unsigned char status, const char *path)
8508 if (status == GOT_STATUS_UNVERSIONED)
8509 return NULL;
8511 while (path[0] == '/')
8512 path++;
8513 printf("%c %s\n", status, path);
8514 return NULL;
8517 struct choose_patch_arg {
8518 FILE *patch_script_file;
8519 const char *action;
8522 static const struct got_error *
8523 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8524 int nchanges, const char *action)
8526 const struct got_error *err;
8527 char *line = NULL;
8528 size_t linesize = 0;
8529 ssize_t linelen;
8531 switch (status) {
8532 case GOT_STATUS_ADD:
8533 printf("A %s\n%s this addition? [y/n] ", path, action);
8534 break;
8535 case GOT_STATUS_DELETE:
8536 printf("D %s\n%s this deletion? [y/n] ", path, action);
8537 break;
8538 case GOT_STATUS_MODIFY:
8539 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8540 return got_error_from_errno("fseek");
8541 printf(GOT_COMMIT_SEP_STR);
8542 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8543 printf("%s", line);
8544 if (linelen == -1 && ferror(patch_file)) {
8545 err = got_error_from_errno("getline");
8546 free(line);
8547 return err;
8549 free(line);
8550 printf(GOT_COMMIT_SEP_STR);
8551 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8552 path, n, nchanges, action);
8553 break;
8554 default:
8555 return got_error_path(path, GOT_ERR_FILE_STATUS);
8558 fflush(stdout);
8559 return NULL;
8562 static const struct got_error *
8563 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8564 FILE *patch_file, int n, int nchanges)
8566 const struct got_error *err = NULL;
8567 char *line = NULL;
8568 size_t linesize = 0;
8569 ssize_t linelen;
8570 int resp = ' ';
8571 struct choose_patch_arg *a = arg;
8573 *choice = GOT_PATCH_CHOICE_NONE;
8575 if (a->patch_script_file) {
8576 char *nl;
8577 err = show_change(status, path, patch_file, n, nchanges,
8578 a->action);
8579 if (err)
8580 return err;
8581 linelen = getline(&line, &linesize, a->patch_script_file);
8582 if (linelen == -1) {
8583 if (ferror(a->patch_script_file))
8584 return got_error_from_errno("getline");
8585 return NULL;
8587 nl = strchr(line, '\n');
8588 if (nl)
8589 *nl = '\0';
8590 if (strcmp(line, "y") == 0) {
8591 *choice = GOT_PATCH_CHOICE_YES;
8592 printf("y\n");
8593 } else if (strcmp(line, "n") == 0) {
8594 *choice = GOT_PATCH_CHOICE_NO;
8595 printf("n\n");
8596 } else if (strcmp(line, "q") == 0 &&
8597 status == GOT_STATUS_MODIFY) {
8598 *choice = GOT_PATCH_CHOICE_QUIT;
8599 printf("q\n");
8600 } else
8601 printf("invalid response '%s'\n", line);
8602 free(line);
8603 return NULL;
8606 while (resp != 'y' && resp != 'n' && resp != 'q') {
8607 err = show_change(status, path, patch_file, n, nchanges,
8608 a->action);
8609 if (err)
8610 return err;
8611 resp = getchar();
8612 if (resp == '\n')
8613 resp = getchar();
8614 if (status == GOT_STATUS_MODIFY) {
8615 if (resp != 'y' && resp != 'n' && resp != 'q') {
8616 printf("invalid response '%c'\n", resp);
8617 resp = ' ';
8619 } else if (resp != 'y' && resp != 'n') {
8620 printf("invalid response '%c'\n", resp);
8621 resp = ' ';
8625 if (resp == 'y')
8626 *choice = GOT_PATCH_CHOICE_YES;
8627 else if (resp == 'n')
8628 *choice = GOT_PATCH_CHOICE_NO;
8629 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8630 *choice = GOT_PATCH_CHOICE_QUIT;
8632 return NULL;
8635 struct wt_commitable_path_arg {
8636 struct got_pathlist_head *commit_paths;
8637 int *has_changes;
8641 * Shortcut work tree status callback to determine if the set of paths scanned
8642 * has at least one versioned path that is being modified and, if not NULL, is
8643 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8644 * soon as a path is passed with a status that satisfies this criteria.
8646 static const struct got_error *
8647 worktree_has_commitable_path(void *arg, unsigned char status,
8648 unsigned char staged_status, const char *path,
8649 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8650 struct got_object_id *commit_id, int dirfd, const char *de_name)
8652 struct wt_commitable_path_arg *a = arg;
8654 if (status == staged_status && (status == GOT_STATUS_DELETE))
8655 status = GOT_STATUS_NO_CHANGE;
8657 if (!(status == GOT_STATUS_NO_CHANGE ||
8658 status == GOT_STATUS_UNVERSIONED) ||
8659 staged_status != GOT_STATUS_NO_CHANGE) {
8660 if (a->commit_paths != NULL) {
8661 struct got_pathlist_entry *pe;
8663 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8664 if (strncmp(path, pe->path,
8665 pe->path_len) == 0) {
8666 *a->has_changes = 1;
8667 break;
8670 } else
8671 *a->has_changes = 1;
8673 if (*a->has_changes)
8674 return got_error(GOT_ERR_FILE_MODIFIED);
8677 return NULL;
8681 * Check that the changeset of the commit identified by id is
8682 * comprised of at least one modified path that is being committed.
8684 static const struct got_error *
8685 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8686 struct got_object_id *id, struct got_worktree *worktree,
8687 struct got_repository *repo)
8689 const struct got_error *err;
8690 struct got_pathlist_head paths;
8691 struct got_commit_object *commit = NULL, *pcommit = NULL;
8692 struct got_tree_object *tree = NULL, *ptree = NULL;
8693 struct got_object_qid *pid;
8695 TAILQ_INIT(&paths);
8697 err = got_object_open_as_commit(&commit, repo, id);
8698 if (err)
8699 goto done;
8701 err = got_object_open_as_tree(&tree, repo,
8702 got_object_commit_get_tree_id(commit));
8703 if (err)
8704 goto done;
8706 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8707 if (pid != NULL) {
8708 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8709 if (err)
8710 goto done;
8712 err = got_object_open_as_tree(&ptree, repo,
8713 got_object_commit_get_tree_id(pcommit));
8714 if (err)
8715 goto done;
8718 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8719 got_diff_tree_collect_changed_paths, &paths, 0);
8720 if (err)
8721 goto done;
8723 err = got_worktree_status(worktree, &paths, repo, 0,
8724 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8725 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8727 * At least one changed path in the referenced commit is
8728 * modified in the work tree, that's all we need to know!
8730 err = NULL;
8733 done:
8734 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8735 if (commit)
8736 got_object_commit_close(commit);
8737 if (pcommit)
8738 got_object_commit_close(pcommit);
8739 if (tree)
8740 got_object_tree_close(tree);
8741 if (ptree)
8742 got_object_tree_close(ptree);
8743 return err;
8747 * Remove any "logmsg" reference comprised entirely of paths that have
8748 * been reverted in this work tree. If any path in the logmsg ref changeset
8749 * remains in a changed state in the worktree, do not remove the reference.
8751 static const struct got_error *
8752 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8754 const struct got_error *err;
8755 struct got_reflist_head refs;
8756 struct got_reflist_entry *re;
8757 struct got_commit_object *commit = NULL;
8758 struct got_object_id *commit_id = NULL;
8759 struct wt_commitable_path_arg wcpa;
8760 char *uuidstr = NULL;
8762 TAILQ_INIT(&refs);
8764 err = got_worktree_get_uuid(&uuidstr, worktree);
8765 if (err)
8766 goto done;
8768 err = got_ref_list(&refs, repo, "refs/got/worktree",
8769 got_ref_cmp_by_name, repo);
8770 if (err)
8771 goto done;
8773 TAILQ_FOREACH(re, &refs, entry) {
8774 const char *refname;
8775 int has_changes = 0;
8777 refname = got_ref_get_name(re->ref);
8779 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8780 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8781 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8782 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8783 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8784 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8785 else
8786 continue;
8788 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8789 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8790 else
8791 continue;
8793 err = got_repo_match_object_id(&commit_id, NULL, refname,
8794 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8795 if (err)
8796 goto done;
8798 err = got_object_open_as_commit(&commit, repo, commit_id);
8799 if (err)
8800 goto done;
8802 wcpa.commit_paths = NULL;
8803 wcpa.has_changes = &has_changes;
8805 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8806 worktree, repo);
8807 if (err)
8808 goto done;
8810 if (!has_changes) {
8811 err = got_ref_delete(re->ref, repo);
8812 if (err)
8813 goto done;
8816 got_object_commit_close(commit);
8817 commit = NULL;
8818 free(commit_id);
8819 commit_id = NULL;
8822 done:
8823 free(uuidstr);
8824 free(commit_id);
8825 got_ref_list_free(&refs);
8826 if (commit)
8827 got_object_commit_close(commit);
8828 return err;
8831 static const struct got_error *
8832 cmd_revert(int argc, char *argv[])
8834 const struct got_error *error = NULL;
8835 struct got_worktree *worktree = NULL;
8836 struct got_repository *repo = NULL;
8837 char *cwd = NULL, *path = NULL;
8838 struct got_pathlist_head paths;
8839 struct got_pathlist_entry *pe;
8840 int ch, can_recurse = 0, pflag = 0;
8841 FILE *patch_script_file = NULL;
8842 const char *patch_script_path = NULL;
8843 struct choose_patch_arg cpa;
8844 int *pack_fds = NULL;
8846 TAILQ_INIT(&paths);
8848 #ifndef PROFILE
8849 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8850 "unveil", NULL) == -1)
8851 err(1, "pledge");
8852 #endif
8854 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8855 switch (ch) {
8856 case 'F':
8857 patch_script_path = optarg;
8858 break;
8859 case 'p':
8860 pflag = 1;
8861 break;
8862 case 'R':
8863 can_recurse = 1;
8864 break;
8865 default:
8866 usage_revert();
8867 /* NOTREACHED */
8871 argc -= optind;
8872 argv += optind;
8874 if (argc < 1)
8875 usage_revert();
8876 if (patch_script_path && !pflag)
8877 errx(1, "-F option can only be used together with -p option");
8879 cwd = getcwd(NULL, 0);
8880 if (cwd == NULL) {
8881 error = got_error_from_errno("getcwd");
8882 goto done;
8885 error = got_repo_pack_fds_open(&pack_fds);
8886 if (error != NULL)
8887 goto done;
8889 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8890 if (error) {
8891 if (error->code == GOT_ERR_NOT_WORKTREE)
8892 error = wrap_not_worktree_error(error, "revert", cwd);
8893 goto done;
8896 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8897 NULL, pack_fds);
8898 if (error != NULL)
8899 goto done;
8901 if (patch_script_path) {
8902 patch_script_file = fopen(patch_script_path, "re");
8903 if (patch_script_file == NULL) {
8904 error = got_error_from_errno2("fopen",
8905 patch_script_path);
8906 goto done;
8911 * XXX "c" perm needed on repo dir to delete merge references.
8913 error = apply_unveil(got_repo_get_path(repo), 0,
8914 got_worktree_get_root_path(worktree));
8915 if (error)
8916 goto done;
8918 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8919 if (error)
8920 goto done;
8922 if (!can_recurse) {
8923 char *ondisk_path;
8924 struct stat sb;
8925 TAILQ_FOREACH(pe, &paths, entry) {
8926 if (asprintf(&ondisk_path, "%s/%s",
8927 got_worktree_get_root_path(worktree),
8928 pe->path) == -1) {
8929 error = got_error_from_errno("asprintf");
8930 goto done;
8932 if (lstat(ondisk_path, &sb) == -1) {
8933 if (errno == ENOENT) {
8934 free(ondisk_path);
8935 continue;
8937 error = got_error_from_errno2("lstat",
8938 ondisk_path);
8939 free(ondisk_path);
8940 goto done;
8942 free(ondisk_path);
8943 if (S_ISDIR(sb.st_mode)) {
8944 error = got_error_msg(GOT_ERR_BAD_PATH,
8945 "reverting directories requires -R option");
8946 goto done;
8951 cpa.patch_script_file = patch_script_file;
8952 cpa.action = "revert";
8953 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8954 pflag ? choose_patch : NULL, &cpa, repo);
8956 error = rm_logmsg_ref(worktree, repo);
8957 done:
8958 if (patch_script_file && fclose(patch_script_file) == EOF &&
8959 error == NULL)
8960 error = got_error_from_errno2("fclose", patch_script_path);
8961 if (repo) {
8962 const struct got_error *close_err = got_repo_close(repo);
8963 if (error == NULL)
8964 error = close_err;
8966 if (worktree)
8967 got_worktree_close(worktree);
8968 if (pack_fds) {
8969 const struct got_error *pack_err =
8970 got_repo_pack_fds_close(pack_fds);
8971 if (error == NULL)
8972 error = pack_err;
8974 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8975 free(path);
8976 free(cwd);
8977 return error;
8980 __dead static void
8981 usage_commit(void)
8983 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8984 "[-m message] [path ...]\n", getprogname());
8985 exit(1);
8988 struct collect_commit_logmsg_arg {
8989 const char *cmdline_log;
8990 const char *prepared_log;
8991 const char *merged_log;
8992 int non_interactive;
8993 const char *editor;
8994 const char *worktree_path;
8995 const char *branch_name;
8996 const char *repo_path;
8997 char *logmsg_path;
9001 static const struct got_error *
9002 read_prepared_logmsg(char **logmsg, const char *path)
9004 const struct got_error *err = NULL;
9005 FILE *f = NULL;
9006 struct stat sb;
9007 size_t r;
9009 *logmsg = NULL;
9010 memset(&sb, 0, sizeof(sb));
9012 f = fopen(path, "re");
9013 if (f == NULL)
9014 return got_error_from_errno2("fopen", path);
9016 if (fstat(fileno(f), &sb) == -1) {
9017 err = got_error_from_errno2("fstat", path);
9018 goto done;
9020 if (sb.st_size == 0) {
9021 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9022 goto done;
9025 *logmsg = malloc(sb.st_size + 1);
9026 if (*logmsg == NULL) {
9027 err = got_error_from_errno("malloc");
9028 goto done;
9031 r = fread(*logmsg, 1, sb.st_size, f);
9032 if (r != sb.st_size) {
9033 if (ferror(f))
9034 err = got_error_from_errno2("fread", path);
9035 else
9036 err = got_error(GOT_ERR_IO);
9037 goto done;
9039 (*logmsg)[sb.st_size] = '\0';
9040 done:
9041 if (fclose(f) == EOF && err == NULL)
9042 err = got_error_from_errno2("fclose", path);
9043 if (err) {
9044 free(*logmsg);
9045 *logmsg = NULL;
9047 return err;
9050 static const struct got_error *
9051 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9052 const char *diff_path, char **logmsg, void *arg)
9054 char *initial_content = NULL;
9055 struct got_pathlist_entry *pe;
9056 const struct got_error *err = NULL;
9057 char *template = NULL;
9058 char *prepared_msg = NULL, *merged_msg = NULL;
9059 struct collect_commit_logmsg_arg *a = arg;
9060 int initial_content_len;
9061 int fd = -1;
9062 size_t len;
9064 /* if a message was specified on the command line, just use it */
9065 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9066 len = strlen(a->cmdline_log) + 1;
9067 *logmsg = malloc(len + 1);
9068 if (*logmsg == NULL)
9069 return got_error_from_errno("malloc");
9070 strlcpy(*logmsg, a->cmdline_log, len);
9071 return NULL;
9072 } else if (a->prepared_log != NULL && a->non_interactive)
9073 return read_prepared_logmsg(logmsg, a->prepared_log);
9075 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9076 return got_error_from_errno("asprintf");
9078 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9079 if (err)
9080 goto done;
9082 if (a->prepared_log) {
9083 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9084 if (err)
9085 goto done;
9086 } else if (a->merged_log) {
9087 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9088 if (err)
9089 goto done;
9092 initial_content_len = asprintf(&initial_content,
9093 "%s%s\n# changes to be committed on branch %s:\n",
9094 prepared_msg ? prepared_msg : "",
9095 merged_msg ? merged_msg : "", a->branch_name);
9096 if (initial_content_len == -1) {
9097 err = got_error_from_errno("asprintf");
9098 goto done;
9101 if (write(fd, initial_content, initial_content_len) == -1) {
9102 err = got_error_from_errno2("write", a->logmsg_path);
9103 goto done;
9106 TAILQ_FOREACH(pe, commitable_paths, entry) {
9107 struct got_commitable *ct = pe->data;
9108 dprintf(fd, "# %c %s\n",
9109 got_commitable_get_status(ct),
9110 got_commitable_get_path(ct));
9113 if (diff_path) {
9114 dprintf(fd, "# detailed changes can be viewed in %s\n",
9115 diff_path);
9118 if (close(fd) == -1) {
9119 err = got_error_from_errno2("close", a->logmsg_path);
9120 goto done;
9122 fd = -1;
9124 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9125 initial_content_len, a->prepared_log ? 0 : 1);
9126 done:
9127 free(initial_content);
9128 free(template);
9129 free(prepared_msg);
9130 free(merged_msg);
9132 if (fd != -1 && close(fd) == -1 && err == NULL)
9133 err = got_error_from_errno2("close", a->logmsg_path);
9135 /* Editor is done; we can now apply unveil(2) */
9136 if (err == NULL)
9137 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9138 if (err) {
9139 free(*logmsg);
9140 *logmsg = NULL;
9142 return err;
9145 static const struct got_error *
9146 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9147 const char *type, int has_content)
9149 const struct got_error *err = NULL;
9150 char *logmsg = NULL;
9152 err = got_object_commit_get_logmsg(&logmsg, commit);
9153 if (err)
9154 return err;
9156 if (fprintf(f, "%s# log message of %s commit %s:%s",
9157 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9158 err = got_ferror(f, GOT_ERR_IO);
9160 free(logmsg);
9161 return err;
9165 * Lookup "logmsg" references of backed-out and cherrypicked commits
9166 * belonging to the current work tree. If found, and the worktree has
9167 * at least one modified file that was changed in the referenced commit,
9168 * add its log message to a new temporary file at *logmsg_path.
9169 * Add all refs found to matched_refs to be scheduled for removal on
9170 * successful commit.
9172 static const struct got_error *
9173 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9174 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9175 struct got_repository *repo)
9177 const struct got_error *err;
9178 struct got_commit_object *commit = NULL;
9179 struct got_object_id *id = NULL;
9180 struct got_reflist_head refs;
9181 struct got_reflist_entry *re, *re_match;
9182 FILE *f = NULL;
9183 char *uuidstr = NULL;
9184 int added_logmsg = 0;
9186 TAILQ_INIT(&refs);
9188 *logmsg_path = NULL;
9190 err = got_worktree_get_uuid(&uuidstr, worktree);
9191 if (err)
9192 goto done;
9194 err = got_ref_list(&refs, repo, "refs/got/worktree",
9195 got_ref_cmp_by_name, repo);
9196 if (err)
9197 goto done;
9199 TAILQ_FOREACH(re, &refs, entry) {
9200 const char *refname, *type;
9201 struct wt_commitable_path_arg wcpa;
9202 int add_logmsg = 0;
9204 refname = got_ref_get_name(re->ref);
9206 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9207 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9208 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9209 type = "cherrypicked";
9210 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9211 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9212 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9213 type = "backed-out";
9214 } else
9215 continue;
9217 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9218 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9219 else
9220 continue;
9222 err = got_repo_match_object_id(&id, NULL, refname,
9223 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9224 if (err)
9225 goto done;
9227 err = got_object_open_as_commit(&commit, repo, id);
9228 if (err)
9229 goto done;
9231 wcpa.commit_paths = paths;
9232 wcpa.has_changes = &add_logmsg;
9234 err = commit_path_changed_in_worktree(&wcpa, id,
9235 worktree, repo);
9236 if (err)
9237 goto done;
9239 if (add_logmsg) {
9240 if (f == NULL) {
9241 err = got_opentemp_named(logmsg_path, &f,
9242 "got-commit-logmsg", "");
9243 if (err)
9244 goto done;
9246 err = cat_logmsg(f, commit, refname, type,
9247 added_logmsg);
9248 if (err)
9249 goto done;
9250 if (!added_logmsg)
9251 ++added_logmsg;
9253 err = got_reflist_entry_dup(&re_match, re);
9254 if (err)
9255 goto done;
9256 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9259 got_object_commit_close(commit);
9260 commit = NULL;
9261 free(id);
9262 id = NULL;
9265 done:
9266 free(id);
9267 free(uuidstr);
9268 got_ref_list_free(&refs);
9269 if (commit)
9270 got_object_commit_close(commit);
9271 if (f && fclose(f) == EOF && err == NULL)
9272 err = got_error_from_errno("fclose");
9273 if (!added_logmsg) {
9274 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9275 err = got_error_from_errno2("unlink", *logmsg_path);
9276 *logmsg_path = NULL;
9278 return err;
9281 static const struct got_error *
9282 cmd_commit(int argc, char *argv[])
9284 const struct got_error *error = NULL;
9285 struct got_worktree *worktree = NULL;
9286 struct got_repository *repo = NULL;
9287 char *cwd = NULL, *id_str = NULL;
9288 struct got_object_id *id = NULL;
9289 const char *logmsg = NULL;
9290 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9291 struct collect_commit_logmsg_arg cl_arg;
9292 const char *author = NULL;
9293 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9294 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9295 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9296 int show_diff = 1, commit_conflicts = 0;
9297 struct got_pathlist_head paths;
9298 struct got_reflist_head refs;
9299 struct got_reflist_entry *re;
9300 int *pack_fds = NULL;
9302 TAILQ_INIT(&refs);
9303 TAILQ_INIT(&paths);
9304 cl_arg.logmsg_path = NULL;
9306 #ifndef PROFILE
9307 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9308 "unveil", NULL) == -1)
9309 err(1, "pledge");
9310 #endif
9312 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9313 switch (ch) {
9314 case 'A':
9315 author = optarg;
9316 error = valid_author(author);
9317 if (error)
9318 return error;
9319 break;
9320 case 'C':
9321 commit_conflicts = 1;
9322 break;
9323 case 'F':
9324 if (logmsg != NULL)
9325 option_conflict('F', 'm');
9326 prepared_logmsg = realpath(optarg, NULL);
9327 if (prepared_logmsg == NULL)
9328 return got_error_from_errno2("realpath",
9329 optarg);
9330 break;
9331 case 'm':
9332 if (prepared_logmsg)
9333 option_conflict('m', 'F');
9334 logmsg = optarg;
9335 break;
9336 case 'N':
9337 non_interactive = 1;
9338 break;
9339 case 'n':
9340 show_diff = 0;
9341 break;
9342 case 'S':
9343 allow_bad_symlinks = 1;
9344 break;
9345 default:
9346 usage_commit();
9347 /* NOTREACHED */
9351 argc -= optind;
9352 argv += optind;
9354 cwd = getcwd(NULL, 0);
9355 if (cwd == NULL) {
9356 error = got_error_from_errno("getcwd");
9357 goto done;
9360 error = got_repo_pack_fds_open(&pack_fds);
9361 if (error != NULL)
9362 goto done;
9364 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9365 if (error) {
9366 if (error->code == GOT_ERR_NOT_WORKTREE)
9367 error = wrap_not_worktree_error(error, "commit", cwd);
9368 goto done;
9371 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9372 if (error)
9373 goto done;
9374 if (rebase_in_progress) {
9375 error = got_error(GOT_ERR_REBASING);
9376 goto done;
9379 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9380 worktree);
9381 if (error)
9382 goto done;
9384 error = get_gitconfig_path(&gitconfig_path);
9385 if (error)
9386 goto done;
9387 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9388 gitconfig_path, pack_fds);
9389 if (error != NULL)
9390 goto done;
9392 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9393 if (error)
9394 goto done;
9395 if (merge_in_progress) {
9396 error = got_error(GOT_ERR_MERGE_BUSY);
9397 goto done;
9400 error = get_author(&committer, repo, worktree);
9401 if (error)
9402 goto done;
9404 if (author == NULL)
9405 author = committer;
9408 * unveil(2) traverses exec(2); if an editor is used we have
9409 * to apply unveil after the log message has been written.
9411 if (logmsg == NULL || strlen(logmsg) == 0)
9412 error = get_editor(&editor);
9413 else
9414 error = apply_unveil(got_repo_get_path(repo), 0,
9415 got_worktree_get_root_path(worktree));
9416 if (error)
9417 goto done;
9419 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9420 if (error)
9421 goto done;
9423 if (prepared_logmsg == NULL) {
9424 error = lookup_logmsg_ref(&merged_logmsg,
9425 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9426 if (error)
9427 goto done;
9430 cl_arg.editor = editor;
9431 cl_arg.cmdline_log = logmsg;
9432 cl_arg.prepared_log = prepared_logmsg;
9433 cl_arg.merged_log = merged_logmsg;
9434 cl_arg.non_interactive = non_interactive;
9435 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9436 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9437 if (!histedit_in_progress) {
9438 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9439 error = got_error(GOT_ERR_COMMIT_BRANCH);
9440 goto done;
9442 cl_arg.branch_name += 11;
9444 cl_arg.repo_path = got_repo_get_path(repo);
9445 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9446 allow_bad_symlinks, show_diff, commit_conflicts,
9447 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9448 if (error) {
9449 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9450 cl_arg.logmsg_path != NULL)
9451 preserve_logmsg = 1;
9452 goto done;
9455 error = got_object_id_str(&id_str, id);
9456 if (error)
9457 goto done;
9458 printf("Created commit %s\n", id_str);
9460 TAILQ_FOREACH(re, &refs, entry) {
9461 error = got_ref_delete(re->ref, repo);
9462 if (error)
9463 goto done;
9466 done:
9467 if (preserve_logmsg) {
9468 fprintf(stderr, "%s: log message preserved in %s\n",
9469 getprogname(), cl_arg.logmsg_path);
9470 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9471 error == NULL)
9472 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9473 free(cl_arg.logmsg_path);
9474 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9475 error = got_error_from_errno2("unlink", merged_logmsg);
9476 free(merged_logmsg);
9477 if (repo) {
9478 const struct got_error *close_err = got_repo_close(repo);
9479 if (error == NULL)
9480 error = close_err;
9482 if (worktree)
9483 got_worktree_close(worktree);
9484 if (pack_fds) {
9485 const struct got_error *pack_err =
9486 got_repo_pack_fds_close(pack_fds);
9487 if (error == NULL)
9488 error = pack_err;
9490 got_ref_list_free(&refs);
9491 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9492 free(cwd);
9493 free(id_str);
9494 free(gitconfig_path);
9495 free(editor);
9496 free(committer);
9497 free(prepared_logmsg);
9498 return error;
9501 __dead static void
9502 usage_send(void)
9504 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9505 "[-r repository-path] [-t tag] [remote-repository]\n",
9506 getprogname());
9507 exit(1);
9510 static void
9511 print_load_info(int print_colored, int print_found, int print_trees,
9512 int ncolored, int nfound, int ntrees)
9514 if (print_colored) {
9515 printf("%d commit%s colored", ncolored,
9516 ncolored == 1 ? "" : "s");
9518 if (print_found) {
9519 printf("%s%d object%s found",
9520 ncolored > 0 ? "; " : "",
9521 nfound, nfound == 1 ? "" : "s");
9523 if (print_trees) {
9524 printf("; %d tree%s scanned", ntrees,
9525 ntrees == 1 ? "" : "s");
9529 struct got_send_progress_arg {
9530 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9531 int verbosity;
9532 int last_ncolored;
9533 int last_nfound;
9534 int last_ntrees;
9535 int loading_done;
9536 int last_ncommits;
9537 int last_nobj_total;
9538 int last_p_deltify;
9539 int last_p_written;
9540 int last_p_sent;
9541 int printed_something;
9542 int sent_something;
9543 struct got_pathlist_head *delete_branches;
9546 static const struct got_error *
9547 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9548 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9549 int nobj_written, off_t bytes_sent, const char *refname,
9550 const char *errmsg, int success)
9552 struct got_send_progress_arg *a = arg;
9553 char scaled_packsize[FMT_SCALED_STRSIZE];
9554 char scaled_sent[FMT_SCALED_STRSIZE];
9555 int p_deltify = 0, p_written = 0, p_sent = 0;
9556 int print_colored = 0, print_found = 0, print_trees = 0;
9557 int print_searching = 0, print_total = 0;
9558 int print_deltify = 0, print_written = 0, print_sent = 0;
9560 if (a->verbosity < 0)
9561 return NULL;
9563 if (refname) {
9564 const char *status = success ? "accepted" : "rejected";
9566 if (success) {
9567 struct got_pathlist_entry *pe;
9568 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9569 const char *branchname = pe->path;
9570 if (got_path_cmp(branchname, refname,
9571 strlen(branchname), strlen(refname)) == 0) {
9572 status = "deleted";
9573 a->sent_something = 1;
9574 break;
9579 if (a->printed_something)
9580 putchar('\n');
9581 printf("Server has %s %s", status, refname);
9582 if (errmsg)
9583 printf(": %s", errmsg);
9584 a->printed_something = 1;
9585 return NULL;
9588 if (a->last_ncolored != ncolored) {
9589 print_colored = 1;
9590 a->last_ncolored = ncolored;
9593 if (a->last_nfound != nfound) {
9594 print_colored = 1;
9595 print_found = 1;
9596 a->last_nfound = nfound;
9599 if (a->last_ntrees != ntrees) {
9600 print_colored = 1;
9601 print_found = 1;
9602 print_trees = 1;
9603 a->last_ntrees = ntrees;
9606 if ((print_colored || print_found || print_trees) &&
9607 !a->loading_done) {
9608 printf("\r");
9609 print_load_info(print_colored, print_found, print_trees,
9610 ncolored, nfound, ntrees);
9611 a->printed_something = 1;
9612 fflush(stdout);
9613 return NULL;
9614 } else if (!a->loading_done) {
9615 printf("\r");
9616 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9617 printf("\n");
9618 a->loading_done = 1;
9621 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9622 return got_error_from_errno("fmt_scaled");
9623 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9624 return got_error_from_errno("fmt_scaled");
9626 if (a->last_ncommits != ncommits) {
9627 print_searching = 1;
9628 a->last_ncommits = ncommits;
9631 if (a->last_nobj_total != nobj_total) {
9632 print_searching = 1;
9633 print_total = 1;
9634 a->last_nobj_total = nobj_total;
9637 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9638 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9639 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9640 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9641 return got_error(GOT_ERR_NO_SPACE);
9644 if (nobj_deltify > 0 || nobj_written > 0) {
9645 if (nobj_deltify > 0) {
9646 p_deltify = (nobj_deltify * 100) / nobj_total;
9647 if (p_deltify != a->last_p_deltify) {
9648 a->last_p_deltify = p_deltify;
9649 print_searching = 1;
9650 print_total = 1;
9651 print_deltify = 1;
9654 if (nobj_written > 0) {
9655 p_written = (nobj_written * 100) / nobj_total;
9656 if (p_written != a->last_p_written) {
9657 a->last_p_written = p_written;
9658 print_searching = 1;
9659 print_total = 1;
9660 print_deltify = 1;
9661 print_written = 1;
9666 if (bytes_sent > 0) {
9667 p_sent = (bytes_sent * 100) / packfile_size;
9668 if (p_sent != a->last_p_sent) {
9669 a->last_p_sent = p_sent;
9670 print_searching = 1;
9671 print_total = 1;
9672 print_deltify = 1;
9673 print_written = 1;
9674 print_sent = 1;
9676 a->sent_something = 1;
9679 if (print_searching || print_total || print_deltify || print_written ||
9680 print_sent)
9681 printf("\r");
9682 if (print_searching)
9683 printf("packing %d reference%s", ncommits,
9684 ncommits == 1 ? "" : "s");
9685 if (print_total)
9686 printf("; %d object%s", nobj_total,
9687 nobj_total == 1 ? "" : "s");
9688 if (print_deltify)
9689 printf("; deltify: %d%%", p_deltify);
9690 if (print_sent)
9691 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9692 scaled_packsize, p_sent);
9693 else if (print_written)
9694 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9695 scaled_packsize, p_written);
9696 if (print_searching || print_total || print_deltify ||
9697 print_written || print_sent) {
9698 a->printed_something = 1;
9699 fflush(stdout);
9701 return NULL;
9704 static const struct got_error *
9705 cmd_send(int argc, char *argv[])
9707 const struct got_error *error = NULL;
9708 char *cwd = NULL, *repo_path = NULL;
9709 const char *remote_name;
9710 char *proto = NULL, *host = NULL, *port = NULL;
9711 char *repo_name = NULL, *server_path = NULL;
9712 const struct got_remote_repo *remotes;
9713 struct got_remote_repo *remote = NULL;
9714 int nremotes, nbranches = 0, ndelete_branches = 0;
9715 struct got_repository *repo = NULL;
9716 struct got_worktree *worktree = NULL;
9717 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9718 struct got_pathlist_head branches;
9719 struct got_pathlist_head tags;
9720 struct got_reflist_head all_branches;
9721 struct got_reflist_head all_tags;
9722 struct got_pathlist_head delete_args;
9723 struct got_pathlist_head delete_branches;
9724 struct got_reflist_entry *re;
9725 struct got_pathlist_entry *pe;
9726 int i, ch, sendfd = -1, sendstatus;
9727 pid_t sendpid = -1;
9728 struct got_send_progress_arg spa;
9729 int verbosity = 0, overwrite_refs = 0;
9730 int send_all_branches = 0, send_all_tags = 0;
9731 struct got_reference *ref = NULL;
9732 int *pack_fds = NULL;
9734 TAILQ_INIT(&branches);
9735 TAILQ_INIT(&tags);
9736 TAILQ_INIT(&all_branches);
9737 TAILQ_INIT(&all_tags);
9738 TAILQ_INIT(&delete_args);
9739 TAILQ_INIT(&delete_branches);
9741 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9742 switch (ch) {
9743 case 'a':
9744 send_all_branches = 1;
9745 break;
9746 case 'b':
9747 error = got_pathlist_append(&branches, optarg, NULL);
9748 if (error)
9749 return error;
9750 nbranches++;
9751 break;
9752 case 'd':
9753 error = got_pathlist_append(&delete_args, optarg, NULL);
9754 if (error)
9755 return error;
9756 break;
9757 case 'f':
9758 overwrite_refs = 1;
9759 break;
9760 case 'q':
9761 verbosity = -1;
9762 break;
9763 case 'r':
9764 repo_path = realpath(optarg, NULL);
9765 if (repo_path == NULL)
9766 return got_error_from_errno2("realpath",
9767 optarg);
9768 got_path_strip_trailing_slashes(repo_path);
9769 break;
9770 case 'T':
9771 send_all_tags = 1;
9772 break;
9773 case 't':
9774 error = got_pathlist_append(&tags, optarg, NULL);
9775 if (error)
9776 return error;
9777 break;
9778 case 'v':
9779 if (verbosity < 0)
9780 verbosity = 0;
9781 else if (verbosity < 3)
9782 verbosity++;
9783 break;
9784 default:
9785 usage_send();
9786 /* NOTREACHED */
9789 argc -= optind;
9790 argv += optind;
9792 if (send_all_branches && !TAILQ_EMPTY(&branches))
9793 option_conflict('a', 'b');
9794 if (send_all_tags && !TAILQ_EMPTY(&tags))
9795 option_conflict('T', 't');
9798 if (argc == 0)
9799 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9800 else if (argc == 1)
9801 remote_name = argv[0];
9802 else
9803 usage_send();
9805 cwd = getcwd(NULL, 0);
9806 if (cwd == NULL) {
9807 error = got_error_from_errno("getcwd");
9808 goto done;
9811 error = got_repo_pack_fds_open(&pack_fds);
9812 if (error != NULL)
9813 goto done;
9815 if (repo_path == NULL) {
9816 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9817 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9818 goto done;
9819 else
9820 error = NULL;
9821 if (worktree) {
9822 repo_path =
9823 strdup(got_worktree_get_repo_path(worktree));
9824 if (repo_path == NULL)
9825 error = got_error_from_errno("strdup");
9826 if (error)
9827 goto done;
9828 } else {
9829 repo_path = strdup(cwd);
9830 if (repo_path == NULL) {
9831 error = got_error_from_errno("strdup");
9832 goto done;
9837 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9838 if (error)
9839 goto done;
9841 if (worktree) {
9842 worktree_conf = got_worktree_get_gotconfig(worktree);
9843 if (worktree_conf) {
9844 got_gotconfig_get_remotes(&nremotes, &remotes,
9845 worktree_conf);
9846 for (i = 0; i < nremotes; i++) {
9847 if (strcmp(remotes[i].name, remote_name) == 0) {
9848 error = got_repo_remote_repo_dup(&remote,
9849 &remotes[i]);
9850 if (error)
9851 goto done;
9852 break;
9857 if (remote == NULL) {
9858 repo_conf = got_repo_get_gotconfig(repo);
9859 if (repo_conf) {
9860 got_gotconfig_get_remotes(&nremotes, &remotes,
9861 repo_conf);
9862 for (i = 0; i < nremotes; i++) {
9863 if (strcmp(remotes[i].name, remote_name) == 0) {
9864 error = got_repo_remote_repo_dup(&remote,
9865 &remotes[i]);
9866 if (error)
9867 goto done;
9868 break;
9873 if (remote == NULL) {
9874 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9875 for (i = 0; i < nremotes; i++) {
9876 if (strcmp(remotes[i].name, remote_name) == 0) {
9877 error = got_repo_remote_repo_dup(&remote,
9878 &remotes[i]);
9879 if (error)
9880 goto done;
9881 break;
9885 if (remote == NULL) {
9886 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9887 goto done;
9890 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9891 &repo_name, remote->send_url);
9892 if (error)
9893 goto done;
9895 if (strcmp(proto, "git") == 0) {
9896 #ifndef PROFILE
9897 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9898 "sendfd dns inet unveil", NULL) == -1)
9899 err(1, "pledge");
9900 #endif
9901 } else if (strcmp(proto, "git+ssh") == 0 ||
9902 strcmp(proto, "ssh") == 0) {
9903 #ifndef PROFILE
9904 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9905 "sendfd unveil", NULL) == -1)
9906 err(1, "pledge");
9907 #endif
9908 } else if (strcmp(proto, "http") == 0 ||
9909 strcmp(proto, "git+http") == 0) {
9910 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9911 goto done;
9912 } else {
9913 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9914 goto done;
9917 error = got_dial_apply_unveil(proto);
9918 if (error)
9919 goto done;
9921 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9922 if (error)
9923 goto done;
9925 if (send_all_branches) {
9926 error = got_ref_list(&all_branches, repo, "refs/heads",
9927 got_ref_cmp_by_name, NULL);
9928 if (error)
9929 goto done;
9930 TAILQ_FOREACH(re, &all_branches, entry) {
9931 const char *branchname = got_ref_get_name(re->ref);
9932 error = got_pathlist_append(&branches,
9933 branchname, NULL);
9934 if (error)
9935 goto done;
9936 nbranches++;
9938 } else if (nbranches == 0) {
9939 for (i = 0; i < remote->nsend_branches; i++) {
9940 error = got_pathlist_append(&branches,
9941 remote->send_branches[i], NULL);
9942 if (error)
9943 goto done;
9947 if (send_all_tags) {
9948 error = got_ref_list(&all_tags, repo, "refs/tags",
9949 got_ref_cmp_by_name, NULL);
9950 if (error)
9951 goto done;
9952 TAILQ_FOREACH(re, &all_tags, entry) {
9953 const char *tagname = got_ref_get_name(re->ref);
9954 error = got_pathlist_append(&tags,
9955 tagname, NULL);
9956 if (error)
9957 goto done;
9962 * To prevent accidents only branches in refs/heads/ can be deleted
9963 * with 'got send -d'.
9964 * Deleting anything else requires local repository access or Git.
9966 TAILQ_FOREACH(pe, &delete_args, entry) {
9967 const char *branchname = pe->path;
9968 char *s;
9969 struct got_pathlist_entry *new;
9970 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9971 s = strdup(branchname);
9972 if (s == NULL) {
9973 error = got_error_from_errno("strdup");
9974 goto done;
9976 } else {
9977 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9978 error = got_error_from_errno("asprintf");
9979 goto done;
9982 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9983 if (error || new == NULL /* duplicate */)
9984 free(s);
9985 if (error)
9986 goto done;
9987 ndelete_branches++;
9990 if (nbranches == 0 && ndelete_branches == 0) {
9991 struct got_reference *head_ref;
9992 if (worktree)
9993 error = got_ref_open(&head_ref, repo,
9994 got_worktree_get_head_ref_name(worktree), 0);
9995 else
9996 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9997 if (error)
9998 goto done;
9999 if (got_ref_is_symbolic(head_ref)) {
10000 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10001 got_ref_close(head_ref);
10002 if (error)
10003 goto done;
10004 } else
10005 ref = head_ref;
10006 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10007 NULL);
10008 if (error)
10009 goto done;
10010 nbranches++;
10013 if (worktree) {
10014 /* Release work tree lock. */
10015 got_worktree_close(worktree);
10016 worktree = NULL;
10019 if (verbosity >= 0) {
10020 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10021 remote->name, proto, host,
10022 port ? ":" : "", port ? port : "",
10023 *server_path == '/' ? "" : "/", server_path);
10026 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10027 server_path, verbosity);
10028 if (error)
10029 goto done;
10031 memset(&spa, 0, sizeof(spa));
10032 spa.last_scaled_packsize[0] = '\0';
10033 spa.last_p_deltify = -1;
10034 spa.last_p_written = -1;
10035 spa.verbosity = verbosity;
10036 spa.delete_branches = &delete_branches;
10037 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10038 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10039 check_cancelled, NULL);
10040 if (spa.printed_something)
10041 putchar('\n');
10042 if (error)
10043 goto done;
10044 if (!spa.sent_something && verbosity >= 0)
10045 printf("Already up-to-date\n");
10046 done:
10047 if (sendpid > 0) {
10048 if (kill(sendpid, SIGTERM) == -1)
10049 error = got_error_from_errno("kill");
10050 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10051 error = got_error_from_errno("waitpid");
10053 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10054 error = got_error_from_errno("close");
10055 if (repo) {
10056 const struct got_error *close_err = got_repo_close(repo);
10057 if (error == NULL)
10058 error = close_err;
10060 if (worktree)
10061 got_worktree_close(worktree);
10062 if (pack_fds) {
10063 const struct got_error *pack_err =
10064 got_repo_pack_fds_close(pack_fds);
10065 if (error == NULL)
10066 error = pack_err;
10068 if (ref)
10069 got_ref_close(ref);
10070 got_repo_free_remote_repo_data(remote);
10071 free(remote);
10072 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10073 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10074 got_ref_list_free(&all_branches);
10075 got_ref_list_free(&all_tags);
10076 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10077 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10078 free(cwd);
10079 free(repo_path);
10080 free(proto);
10081 free(host);
10082 free(port);
10083 free(server_path);
10084 free(repo_name);
10085 return error;
10089 * Print and if delete is set delete all ref_prefix references.
10090 * If wanted_ref is not NULL, only print or delete this reference.
10092 static const struct got_error *
10093 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10094 const char *wanted_ref, int delete, struct got_worktree *worktree,
10095 struct got_repository *repo)
10097 const struct got_error *err;
10098 struct got_pathlist_head paths;
10099 struct got_reflist_head refs;
10100 struct got_reflist_entry *re;
10101 struct got_reflist_object_id_map *refs_idmap = NULL;
10102 struct got_commit_object *commit = NULL;
10103 struct got_object_id *id = NULL;
10104 const char *header_prefix;
10105 char *uuidstr = NULL;
10106 int found = 0;
10108 TAILQ_INIT(&refs);
10109 TAILQ_INIT(&paths);
10111 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10112 if (err)
10113 goto done;
10115 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10116 if (err)
10117 goto done;
10119 if (worktree != NULL) {
10120 err = got_worktree_get_uuid(&uuidstr, worktree);
10121 if (err)
10122 goto done;
10125 if (wanted_ref) {
10126 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10127 wanted_ref += 11;
10130 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10131 header_prefix = "backout";
10132 else
10133 header_prefix = "cherrypick";
10135 TAILQ_FOREACH(re, &refs, entry) {
10136 const char *refname, *wt;
10138 refname = got_ref_get_name(re->ref);
10140 err = check_cancelled(NULL);
10141 if (err)
10142 goto done;
10144 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10145 refname += prefix_len + 1; /* skip '-' delimiter */
10146 else
10147 continue;
10149 wt = refname;
10151 if (worktree == NULL || strncmp(refname, uuidstr,
10152 GOT_WORKTREE_UUID_STRLEN) == 0)
10153 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10154 else
10155 continue;
10157 err = got_repo_match_object_id(&id, NULL, refname,
10158 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10159 if (err)
10160 goto done;
10162 err = got_object_open_as_commit(&commit, repo, id);
10163 if (err)
10164 goto done;
10166 if (wanted_ref)
10167 found = strncmp(wanted_ref, refname,
10168 strlen(wanted_ref)) == 0;
10169 if (wanted_ref && !found) {
10170 struct got_reflist_head *ci_refs;
10172 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10173 id);
10175 if (ci_refs) {
10176 char *refs_str = NULL;
10177 char const *r = NULL;
10179 err = build_refs_str(&refs_str, ci_refs, id,
10180 repo, 1);
10181 if (err)
10182 goto done;
10184 r = refs_str;
10185 while (r) {
10186 if (strncmp(r, wanted_ref,
10187 strlen(wanted_ref)) == 0) {
10188 found = 1;
10189 break;
10191 r = strchr(r, ' ');
10192 if (r)
10193 ++r;
10195 free(refs_str);
10199 if (wanted_ref == NULL || found) {
10200 if (delete) {
10201 err = got_ref_delete(re->ref, repo);
10202 if (err)
10203 goto done;
10204 printf("Deleted: ");
10205 err = print_commit_oneline(commit, id, repo,
10206 refs_idmap);
10207 } else {
10209 * Print paths modified by commit to help
10210 * associate commits with worktree changes.
10212 err = get_changed_paths(&paths, commit,
10213 repo, NULL);
10214 if (err)
10215 goto done;
10217 err = print_commit(commit, id, repo, NULL,
10218 &paths, NULL, 0, 0, refs_idmap, NULL,
10219 header_prefix);
10220 got_pathlist_free(&paths,
10221 GOT_PATHLIST_FREE_ALL);
10223 if (worktree == NULL)
10224 printf("work tree: %.*s\n\n",
10225 GOT_WORKTREE_UUID_STRLEN, wt);
10227 if (err || found)
10228 goto done;
10231 got_object_commit_close(commit);
10232 commit = NULL;
10233 free(id);
10234 id = NULL;
10237 if (wanted_ref != NULL && !found)
10238 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10240 done:
10241 free(id);
10242 free(uuidstr);
10243 got_ref_list_free(&refs);
10244 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10245 if (refs_idmap)
10246 got_reflist_object_id_map_free(refs_idmap);
10247 if (commit)
10248 got_object_commit_close(commit);
10249 return err;
10253 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10254 * identified by id for log messages to prepopulate the editor on commit.
10256 static const struct got_error *
10257 logmsg_ref(struct got_object_id *id, const char *prefix,
10258 struct got_worktree *worktree, struct got_repository *repo)
10260 const struct got_error *err = NULL;
10261 char *idstr, *ref = NULL, *refname = NULL;
10262 int histedit_in_progress;
10263 int rebase_in_progress, merge_in_progress;
10266 * Silenty refuse to create merge reference if any histedit, merge,
10267 * or rebase operation is in progress.
10269 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10270 worktree);
10271 if (err)
10272 return err;
10273 if (histedit_in_progress)
10274 return NULL;
10276 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10277 if (err)
10278 return err;
10279 if (rebase_in_progress)
10280 return NULL;
10282 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10283 repo);
10284 if (err)
10285 return err;
10286 if (merge_in_progress)
10287 return NULL;
10289 err = got_object_id_str(&idstr, id);
10290 if (err)
10291 return err;
10293 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10294 if (err)
10295 goto done;
10297 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10298 err = got_error_from_errno("asprintf");
10299 goto done;
10302 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10303 -1, repo);
10304 done:
10305 free(ref);
10306 free(idstr);
10307 free(refname);
10308 return err;
10311 __dead static void
10312 usage_cherrypick(void)
10314 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10315 getprogname());
10316 exit(1);
10319 static const struct got_error *
10320 cmd_cherrypick(int argc, char *argv[])
10322 const struct got_error *error = NULL;
10323 struct got_worktree *worktree = NULL;
10324 struct got_repository *repo = NULL;
10325 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10326 struct got_object_id *commit_id = NULL;
10327 struct got_commit_object *commit = NULL;
10328 struct got_object_qid *pid;
10329 int ch, list_refs = 0, remove_refs = 0;
10330 struct got_update_progress_arg upa;
10331 int *pack_fds = NULL;
10333 #ifndef PROFILE
10334 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10335 "unveil", NULL) == -1)
10336 err(1, "pledge");
10337 #endif
10339 while ((ch = getopt(argc, argv, "lX")) != -1) {
10340 switch (ch) {
10341 case 'l':
10342 list_refs = 1;
10343 break;
10344 case 'X':
10345 remove_refs = 1;
10346 break;
10347 default:
10348 usage_cherrypick();
10349 /* NOTREACHED */
10353 argc -= optind;
10354 argv += optind;
10356 if (list_refs || remove_refs) {
10357 if (argc != 0 && argc != 1)
10358 usage_cherrypick();
10359 } else if (argc != 1)
10360 usage_cherrypick();
10361 if (list_refs && remove_refs)
10362 option_conflict('l', 'X');
10364 cwd = getcwd(NULL, 0);
10365 if (cwd == NULL) {
10366 error = got_error_from_errno("getcwd");
10367 goto done;
10370 error = got_repo_pack_fds_open(&pack_fds);
10371 if (error != NULL)
10372 goto done;
10374 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10375 if (error) {
10376 if (list_refs || remove_refs) {
10377 if (error->code != GOT_ERR_NOT_WORKTREE)
10378 goto done;
10379 } else {
10380 if (error->code == GOT_ERR_NOT_WORKTREE)
10381 error = wrap_not_worktree_error(error,
10382 "cherrypick", cwd);
10383 goto done;
10387 error = got_repo_open(&repo,
10388 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10389 NULL, pack_fds);
10390 if (error != NULL)
10391 goto done;
10393 error = apply_unveil(got_repo_get_path(repo), 0,
10394 worktree ? got_worktree_get_root_path(worktree) : NULL);
10395 if (error)
10396 goto done;
10398 if (list_refs || remove_refs) {
10399 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10400 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10401 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10402 goto done;
10405 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10406 if (error != NULL)
10407 goto done;
10409 error = got_repo_match_object_id(&commit_id, NULL,
10410 keyword_idstr != NULL ? keyword_idstr : argv[0],
10411 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10412 if (error)
10413 goto done;
10414 error = got_object_id_str(&commit_id_str, commit_id);
10415 if (error)
10416 goto done;
10418 error = got_object_open_as_commit(&commit, repo, commit_id);
10419 if (error)
10420 goto done;
10421 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10422 memset(&upa, 0, sizeof(upa));
10423 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10424 commit_id, repo, update_progress, &upa, check_cancelled,
10425 NULL);
10426 if (error != NULL)
10427 goto done;
10429 if (upa.did_something) {
10430 error = logmsg_ref(commit_id,
10431 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10432 if (error)
10433 goto done;
10434 printf("Merged commit %s\n", commit_id_str);
10436 print_merge_progress_stats(&upa);
10437 done:
10438 free(cwd);
10439 free(keyword_idstr);
10440 if (commit)
10441 got_object_commit_close(commit);
10442 free(commit_id_str);
10443 if (worktree)
10444 got_worktree_close(worktree);
10445 if (repo) {
10446 const struct got_error *close_err = got_repo_close(repo);
10447 if (error == NULL)
10448 error = close_err;
10450 if (pack_fds) {
10451 const struct got_error *pack_err =
10452 got_repo_pack_fds_close(pack_fds);
10453 if (error == NULL)
10454 error = pack_err;
10457 return error;
10460 __dead static void
10461 usage_backout(void)
10463 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10464 exit(1);
10467 static const struct got_error *
10468 cmd_backout(int argc, char *argv[])
10470 const struct got_error *error = NULL;
10471 struct got_worktree *worktree = NULL;
10472 struct got_repository *repo = NULL;
10473 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10474 struct got_object_id *commit_id = NULL;
10475 struct got_commit_object *commit = NULL;
10476 struct got_object_qid *pid;
10477 int ch, list_refs = 0, remove_refs = 0;
10478 struct got_update_progress_arg upa;
10479 int *pack_fds = NULL;
10481 #ifndef PROFILE
10482 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10483 "unveil", NULL) == -1)
10484 err(1, "pledge");
10485 #endif
10487 while ((ch = getopt(argc, argv, "lX")) != -1) {
10488 switch (ch) {
10489 case 'l':
10490 list_refs = 1;
10491 break;
10492 case 'X':
10493 remove_refs = 1;
10494 break;
10495 default:
10496 usage_backout();
10497 /* NOTREACHED */
10501 argc -= optind;
10502 argv += optind;
10504 if (list_refs || remove_refs) {
10505 if (argc != 0 && argc != 1)
10506 usage_backout();
10507 } else if (argc != 1)
10508 usage_backout();
10509 if (list_refs && remove_refs)
10510 option_conflict('l', 'X');
10512 cwd = getcwd(NULL, 0);
10513 if (cwd == NULL) {
10514 error = got_error_from_errno("getcwd");
10515 goto done;
10518 error = got_repo_pack_fds_open(&pack_fds);
10519 if (error != NULL)
10520 goto done;
10522 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10523 if (error) {
10524 if (list_refs || remove_refs) {
10525 if (error->code != GOT_ERR_NOT_WORKTREE)
10526 goto done;
10527 } else {
10528 if (error->code == GOT_ERR_NOT_WORKTREE)
10529 error = wrap_not_worktree_error(error,
10530 "backout", cwd);
10531 goto done;
10535 error = got_repo_open(&repo,
10536 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10537 NULL, pack_fds);
10538 if (error != NULL)
10539 goto done;
10541 error = apply_unveil(got_repo_get_path(repo), 0,
10542 worktree ? got_worktree_get_root_path(worktree) : NULL);
10543 if (error)
10544 goto done;
10546 if (list_refs || remove_refs) {
10547 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10548 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10549 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10550 goto done;
10553 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10554 if (error != NULL)
10555 goto done;
10557 error = got_repo_match_object_id(&commit_id, NULL,
10558 keyword_idstr != NULL ? keyword_idstr : argv[0],
10559 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10560 if (error)
10561 goto done;
10562 error = got_object_id_str(&commit_id_str, commit_id);
10563 if (error)
10564 goto done;
10566 error = got_object_open_as_commit(&commit, repo, commit_id);
10567 if (error)
10568 goto done;
10569 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10570 if (pid == NULL) {
10571 error = got_error(GOT_ERR_ROOT_COMMIT);
10572 goto done;
10575 memset(&upa, 0, sizeof(upa));
10576 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10577 repo, update_progress, &upa, check_cancelled, NULL);
10578 if (error != NULL)
10579 goto done;
10581 if (upa.did_something) {
10582 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10583 worktree, repo);
10584 if (error)
10585 goto done;
10586 printf("Backed out commit %s\n", commit_id_str);
10588 print_merge_progress_stats(&upa);
10589 done:
10590 free(cwd);
10591 free(keyword_idstr);
10592 if (commit)
10593 got_object_commit_close(commit);
10594 free(commit_id_str);
10595 if (worktree)
10596 got_worktree_close(worktree);
10597 if (repo) {
10598 const struct got_error *close_err = got_repo_close(repo);
10599 if (error == NULL)
10600 error = close_err;
10602 if (pack_fds) {
10603 const struct got_error *pack_err =
10604 got_repo_pack_fds_close(pack_fds);
10605 if (error == NULL)
10606 error = pack_err;
10608 return error;
10611 __dead static void
10612 usage_rebase(void)
10614 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10615 exit(1);
10618 static void
10619 trim_logmsg(char *logmsg, int limit)
10621 char *nl;
10622 size_t len;
10624 len = strlen(logmsg);
10625 if (len > limit)
10626 len = limit;
10627 logmsg[len] = '\0';
10628 nl = strchr(logmsg, '\n');
10629 if (nl)
10630 *nl = '\0';
10633 static const struct got_error *
10634 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10636 const struct got_error *err;
10637 char *logmsg0 = NULL;
10638 const char *s;
10640 err = got_object_commit_get_logmsg(&logmsg0, commit);
10641 if (err)
10642 return err;
10644 s = logmsg0;
10645 while (isspace((unsigned char)s[0]))
10646 s++;
10648 *logmsg = strdup(s);
10649 if (*logmsg == NULL) {
10650 err = got_error_from_errno("strdup");
10651 goto done;
10654 trim_logmsg(*logmsg, limit);
10655 done:
10656 free(logmsg0);
10657 return err;
10660 static const struct got_error *
10661 show_rebase_merge_conflict(struct got_object_id *id,
10662 struct got_repository *repo)
10664 const struct got_error *err;
10665 struct got_commit_object *commit = NULL;
10666 char *id_str = NULL, *logmsg = NULL;
10668 err = got_object_open_as_commit(&commit, repo, id);
10669 if (err)
10670 return err;
10672 err = got_object_id_str(&id_str, id);
10673 if (err)
10674 goto done;
10676 id_str[12] = '\0';
10678 err = get_short_logmsg(&logmsg, 42, commit);
10679 if (err)
10680 goto done;
10682 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10683 done:
10684 free(id_str);
10685 got_object_commit_close(commit);
10686 free(logmsg);
10687 return err;
10690 static const struct got_error *
10691 show_rebase_progress(struct got_commit_object *commit,
10692 struct got_object_id *old_id, struct got_object_id *new_id)
10694 const struct got_error *err;
10695 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10697 err = got_object_id_str(&old_id_str, old_id);
10698 if (err)
10699 goto done;
10701 if (new_id) {
10702 err = got_object_id_str(&new_id_str, new_id);
10703 if (err)
10704 goto done;
10707 old_id_str[12] = '\0';
10708 if (new_id_str)
10709 new_id_str[12] = '\0';
10711 err = get_short_logmsg(&logmsg, 42, commit);
10712 if (err)
10713 goto done;
10715 printf("%s -> %s: %s\n", old_id_str,
10716 new_id_str ? new_id_str : "no-op change", logmsg);
10717 done:
10718 free(old_id_str);
10719 free(new_id_str);
10720 free(logmsg);
10721 return err;
10724 static const struct got_error *
10725 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10726 struct got_reference *branch, struct got_reference *tmp_branch,
10727 struct got_repository *repo, int create_backup)
10729 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10730 return got_worktree_rebase_complete(worktree, fileindex,
10731 tmp_branch, branch, repo, create_backup);
10734 static const struct got_error *
10735 rebase_commit(struct got_pathlist_head *merged_paths,
10736 struct got_worktree *worktree, struct got_fileindex *fileindex,
10737 struct got_reference *tmp_branch, const char *committer,
10738 struct got_object_id *commit_id, int allow_conflict,
10739 struct got_repository *repo)
10741 const struct got_error *error;
10742 struct got_commit_object *commit;
10743 struct got_object_id *new_commit_id;
10745 error = got_object_open_as_commit(&commit, repo, commit_id);
10746 if (error)
10747 return error;
10749 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10750 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10751 allow_conflict, repo);
10752 if (error) {
10753 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10754 goto done;
10755 error = show_rebase_progress(commit, commit_id, NULL);
10756 } else {
10757 error = show_rebase_progress(commit, commit_id, new_commit_id);
10758 free(new_commit_id);
10760 done:
10761 got_object_commit_close(commit);
10762 return error;
10765 struct check_path_prefix_arg {
10766 const char *path_prefix;
10767 size_t len;
10768 int errcode;
10771 static const struct got_error *
10772 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10773 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10774 struct got_object_id *id1, struct got_object_id *id2,
10775 const char *path1, const char *path2,
10776 mode_t mode1, mode_t mode2, struct got_repository *repo)
10778 struct check_path_prefix_arg *a = arg;
10780 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10781 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10782 return got_error(a->errcode);
10784 return NULL;
10787 static const struct got_error *
10788 check_path_prefix(struct got_object_id *parent_id,
10789 struct got_object_id *commit_id, const char *path_prefix,
10790 int errcode, struct got_repository *repo)
10792 const struct got_error *err;
10793 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10794 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10795 struct check_path_prefix_arg cpp_arg;
10797 if (got_path_is_root_dir(path_prefix))
10798 return NULL;
10800 err = got_object_open_as_commit(&commit, repo, commit_id);
10801 if (err)
10802 goto done;
10804 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10805 if (err)
10806 goto done;
10808 err = got_object_open_as_tree(&tree1, repo,
10809 got_object_commit_get_tree_id(parent_commit));
10810 if (err)
10811 goto done;
10813 err = got_object_open_as_tree(&tree2, repo,
10814 got_object_commit_get_tree_id(commit));
10815 if (err)
10816 goto done;
10818 cpp_arg.path_prefix = path_prefix;
10819 while (cpp_arg.path_prefix[0] == '/')
10820 cpp_arg.path_prefix++;
10821 cpp_arg.len = strlen(cpp_arg.path_prefix);
10822 cpp_arg.errcode = errcode;
10823 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10824 check_path_prefix_in_diff, &cpp_arg, 0);
10825 done:
10826 if (tree1)
10827 got_object_tree_close(tree1);
10828 if (tree2)
10829 got_object_tree_close(tree2);
10830 if (commit)
10831 got_object_commit_close(commit);
10832 if (parent_commit)
10833 got_object_commit_close(parent_commit);
10834 return err;
10837 static const struct got_error *
10838 collect_commits(struct got_object_id_queue *commits,
10839 struct got_object_id *initial_commit_id,
10840 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10841 const char *path_prefix, int path_prefix_errcode,
10842 struct got_repository *repo)
10844 const struct got_error *err = NULL;
10845 struct got_commit_graph *graph = NULL;
10846 struct got_object_id parent_id, commit_id;
10847 struct got_object_qid *qid;
10849 err = got_commit_graph_open(&graph, "/", 1);
10850 if (err)
10851 return err;
10853 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10854 check_cancelled, NULL);
10855 if (err)
10856 goto done;
10858 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10859 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10860 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10861 check_cancelled, NULL);
10862 if (err) {
10863 if (err->code == GOT_ERR_ITER_COMPLETED) {
10864 err = got_error_msg(GOT_ERR_ANCESTRY,
10865 "ran out of commits to rebase before "
10866 "youngest common ancestor commit has "
10867 "been reached?!?");
10869 goto done;
10870 } else {
10871 err = check_path_prefix(&parent_id, &commit_id,
10872 path_prefix, path_prefix_errcode, repo);
10873 if (err)
10874 goto done;
10876 err = got_object_qid_alloc(&qid, &commit_id);
10877 if (err)
10878 goto done;
10879 STAILQ_INSERT_HEAD(commits, qid, entry);
10881 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10884 done:
10885 got_commit_graph_close(graph);
10886 return err;
10889 static const struct got_error *
10890 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10892 const struct got_error *err = NULL;
10893 time_t committer_time;
10894 struct tm tm;
10895 char datebuf[11]; /* YYYY-MM-DD + NUL */
10896 char *author0 = NULL, *author, *smallerthan;
10897 char *logmsg0 = NULL, *logmsg, *newline;
10899 committer_time = got_object_commit_get_committer_time(commit);
10900 if (gmtime_r(&committer_time, &tm) == NULL)
10901 return got_error_from_errno("gmtime_r");
10902 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10903 return got_error(GOT_ERR_NO_SPACE);
10905 author0 = strdup(got_object_commit_get_author(commit));
10906 if (author0 == NULL)
10907 return got_error_from_errno("strdup");
10908 author = author0;
10909 smallerthan = strchr(author, '<');
10910 if (smallerthan && smallerthan[1] != '\0')
10911 author = smallerthan + 1;
10912 author[strcspn(author, "@>")] = '\0';
10914 err = got_object_commit_get_logmsg(&logmsg0, commit);
10915 if (err)
10916 goto done;
10917 logmsg = logmsg0;
10918 while (*logmsg == '\n')
10919 logmsg++;
10920 newline = strchr(logmsg, '\n');
10921 if (newline)
10922 *newline = '\0';
10924 if (asprintf(brief_str, "%s %s %s",
10925 datebuf, author, logmsg) == -1)
10926 err = got_error_from_errno("asprintf");
10927 done:
10928 free(author0);
10929 free(logmsg0);
10930 return err;
10933 static const struct got_error *
10934 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10935 struct got_repository *repo)
10937 const struct got_error *err;
10938 char *id_str;
10940 err = got_object_id_str(&id_str, id);
10941 if (err)
10942 return err;
10944 err = got_ref_delete(ref, repo);
10945 if (err)
10946 goto done;
10948 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10949 done:
10950 free(id_str);
10951 return err;
10954 static const struct got_error *
10955 print_backup_ref(const char *branch_name, const char *new_id_str,
10956 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10957 struct got_reflist_object_id_map *refs_idmap,
10958 struct got_repository *repo)
10960 const struct got_error *err = NULL;
10961 struct got_reflist_head *refs;
10962 char *refs_str = NULL;
10963 struct got_object_id *new_commit_id = NULL;
10964 struct got_commit_object *new_commit = NULL;
10965 char *new_commit_brief_str = NULL;
10966 struct got_object_id *yca_id = NULL;
10967 struct got_commit_object *yca_commit = NULL;
10968 char *yca_id_str = NULL, *yca_brief_str = NULL;
10969 char *custom_refs_str;
10971 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10972 return got_error_from_errno("asprintf");
10974 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10975 0, 0, refs_idmap, custom_refs_str, NULL);
10976 if (err)
10977 goto done;
10979 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10980 if (err)
10981 goto done;
10983 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10984 if (refs) {
10985 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10986 if (err)
10987 goto done;
10990 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10991 if (err)
10992 goto done;
10994 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10995 if (err)
10996 goto done;
10998 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10999 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
11000 if (err)
11001 goto done;
11003 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11004 refs_str ? " (" : "", refs_str ? refs_str : "",
11005 refs_str ? ")" : "", new_commit_brief_str);
11006 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11007 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11008 free(refs_str);
11009 refs_str = NULL;
11011 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11012 if (err)
11013 goto done;
11015 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11016 if (err)
11017 goto done;
11019 err = got_object_id_str(&yca_id_str, yca_id);
11020 if (err)
11021 goto done;
11023 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11024 if (refs) {
11025 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11026 if (err)
11027 goto done;
11029 printf("history forked at %s%s%s%s\n %s\n",
11030 yca_id_str,
11031 refs_str ? " (" : "", refs_str ? refs_str : "",
11032 refs_str ? ")" : "", yca_brief_str);
11034 done:
11035 free(custom_refs_str);
11036 free(new_commit_id);
11037 free(refs_str);
11038 free(yca_id);
11039 free(yca_id_str);
11040 free(yca_brief_str);
11041 if (new_commit)
11042 got_object_commit_close(new_commit);
11043 if (yca_commit)
11044 got_object_commit_close(yca_commit);
11046 return err;
11049 static const struct got_error *
11050 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11051 struct got_repository *repo)
11053 const struct got_error *err;
11054 struct got_reflist_head refs;
11055 struct got_reflist_entry *re;
11056 char *uuidstr = NULL;
11057 static char msg[160];
11059 TAILQ_INIT(&refs);
11061 err = got_worktree_get_uuid(&uuidstr, worktree);
11062 if (err)
11063 goto done;
11065 err = got_ref_list(&refs, repo, "refs/got/worktree",
11066 got_ref_cmp_by_name, repo);
11067 if (err)
11068 goto done;
11070 TAILQ_FOREACH(re, &refs, entry) {
11071 const char *cmd, *refname, *type;
11073 refname = got_ref_get_name(re->ref);
11075 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11076 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11077 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11078 cmd = "cherrypick";
11079 type = "cherrypicked";
11080 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11081 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11082 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11083 cmd = "backout";
11084 type = "backed-out";
11085 } else
11086 continue;
11088 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11089 continue;
11091 snprintf(msg, sizeof(msg),
11092 "work tree has references created by %s commits which "
11093 "must be removed with 'got %s -X' before running the %s "
11094 "command", type, cmd, caller);
11095 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11096 goto done;
11099 done:
11100 free(uuidstr);
11101 got_ref_list_free(&refs);
11102 return err;
11105 static const struct got_error *
11106 process_backup_refs(const char *backup_ref_prefix,
11107 const char *wanted_branch_name,
11108 int delete, struct got_repository *repo)
11110 const struct got_error *err;
11111 struct got_reflist_head refs, backup_refs;
11112 struct got_reflist_entry *re;
11113 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11114 struct got_object_id *old_commit_id = NULL;
11115 char *branch_name = NULL;
11116 struct got_commit_object *old_commit = NULL;
11117 struct got_reflist_object_id_map *refs_idmap = NULL;
11118 int wanted_branch_found = 0;
11120 TAILQ_INIT(&refs);
11121 TAILQ_INIT(&backup_refs);
11123 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11124 if (err)
11125 return err;
11127 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11128 if (err)
11129 goto done;
11131 if (wanted_branch_name) {
11132 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11133 wanted_branch_name += 11;
11136 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11137 got_ref_cmp_by_commit_timestamp_descending, repo);
11138 if (err)
11139 goto done;
11141 TAILQ_FOREACH(re, &backup_refs, entry) {
11142 const char *refname = got_ref_get_name(re->ref);
11143 char *slash;
11145 err = check_cancelled(NULL);
11146 if (err)
11147 break;
11149 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11150 if (err)
11151 break;
11153 err = got_object_open_as_commit(&old_commit, repo,
11154 old_commit_id);
11155 if (err)
11156 break;
11158 if (strncmp(backup_ref_prefix, refname,
11159 backup_ref_prefix_len) == 0)
11160 refname += backup_ref_prefix_len;
11162 while (refname[0] == '/')
11163 refname++;
11165 branch_name = strdup(refname);
11166 if (branch_name == NULL) {
11167 err = got_error_from_errno("strdup");
11168 break;
11170 slash = strrchr(branch_name, '/');
11171 if (slash) {
11172 *slash = '\0';
11173 refname += strlen(branch_name) + 1;
11176 if (wanted_branch_name == NULL ||
11177 strcmp(wanted_branch_name, branch_name) == 0) {
11178 wanted_branch_found = 1;
11179 if (delete) {
11180 err = delete_backup_ref(re->ref,
11181 old_commit_id, repo);
11182 } else {
11183 err = print_backup_ref(branch_name, refname,
11184 old_commit_id, old_commit, refs_idmap,
11185 repo);
11187 if (err)
11188 break;
11191 free(old_commit_id);
11192 old_commit_id = NULL;
11193 free(branch_name);
11194 branch_name = NULL;
11195 got_object_commit_close(old_commit);
11196 old_commit = NULL;
11199 if (wanted_branch_name && !wanted_branch_found) {
11200 err = got_error_fmt(GOT_ERR_NOT_REF,
11201 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11203 done:
11204 if (refs_idmap)
11205 got_reflist_object_id_map_free(refs_idmap);
11206 got_ref_list_free(&refs);
11207 got_ref_list_free(&backup_refs);
11208 free(old_commit_id);
11209 free(branch_name);
11210 if (old_commit)
11211 got_object_commit_close(old_commit);
11212 return err;
11215 static const struct got_error *
11216 abort_progress(void *arg, unsigned char status, const char *path)
11219 * Unversioned files should not clutter progress output when
11220 * an operation is aborted.
11222 if (status == GOT_STATUS_UNVERSIONED)
11223 return NULL;
11225 return update_progress(arg, status, path);
11228 static const struct got_error *
11229 cmd_rebase(int argc, char *argv[])
11231 const struct got_error *error = NULL;
11232 struct got_worktree *worktree = NULL;
11233 struct got_repository *repo = NULL;
11234 struct got_fileindex *fileindex = NULL;
11235 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11236 struct got_reference *branch = NULL;
11237 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11238 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11239 struct got_object_id *resume_commit_id = NULL;
11240 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11241 struct got_object_id *head_commit_id = NULL;
11242 struct got_reference *head_ref = NULL;
11243 struct got_commit_object *commit = NULL;
11244 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11245 int histedit_in_progress = 0, merge_in_progress = 0;
11246 int create_backup = 1, list_backups = 0, delete_backups = 0;
11247 int allow_conflict = 0;
11248 struct got_object_id_queue commits;
11249 struct got_pathlist_head merged_paths;
11250 const struct got_object_id_queue *parent_ids;
11251 struct got_object_qid *qid, *pid;
11252 struct got_update_progress_arg upa;
11253 int *pack_fds = NULL;
11255 STAILQ_INIT(&commits);
11256 TAILQ_INIT(&merged_paths);
11257 memset(&upa, 0, sizeof(upa));
11259 #ifndef PROFILE
11260 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11261 "unveil", NULL) == -1)
11262 err(1, "pledge");
11263 #endif
11265 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11266 switch (ch) {
11267 case 'a':
11268 abort_rebase = 1;
11269 break;
11270 case 'C':
11271 allow_conflict = 1;
11272 break;
11273 case 'c':
11274 continue_rebase = 1;
11275 break;
11276 case 'l':
11277 list_backups = 1;
11278 break;
11279 case 'X':
11280 delete_backups = 1;
11281 break;
11282 default:
11283 usage_rebase();
11284 /* NOTREACHED */
11288 argc -= optind;
11289 argv += optind;
11291 if (list_backups) {
11292 if (abort_rebase)
11293 option_conflict('l', 'a');
11294 if (allow_conflict)
11295 option_conflict('l', 'C');
11296 if (continue_rebase)
11297 option_conflict('l', 'c');
11298 if (delete_backups)
11299 option_conflict('l', 'X');
11300 if (argc != 0 && argc != 1)
11301 usage_rebase();
11302 } else if (delete_backups) {
11303 if (abort_rebase)
11304 option_conflict('X', 'a');
11305 if (allow_conflict)
11306 option_conflict('X', 'C');
11307 if (continue_rebase)
11308 option_conflict('X', 'c');
11309 if (list_backups)
11310 option_conflict('l', 'X');
11311 if (argc != 0 && argc != 1)
11312 usage_rebase();
11313 } else if (allow_conflict) {
11314 if (abort_rebase)
11315 option_conflict('C', 'a');
11316 if (!continue_rebase)
11317 errx(1, "-C option requires -c");
11318 } else {
11319 if (abort_rebase && continue_rebase)
11320 usage_rebase();
11321 else if (abort_rebase || continue_rebase) {
11322 if (argc != 0)
11323 usage_rebase();
11324 } else if (argc != 1)
11325 usage_rebase();
11328 cwd = getcwd(NULL, 0);
11329 if (cwd == NULL) {
11330 error = got_error_from_errno("getcwd");
11331 goto done;
11334 error = got_repo_pack_fds_open(&pack_fds);
11335 if (error != NULL)
11336 goto done;
11338 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11339 if (error) {
11340 if (list_backups || delete_backups) {
11341 if (error->code != GOT_ERR_NOT_WORKTREE)
11342 goto done;
11343 } else {
11344 if (error->code == GOT_ERR_NOT_WORKTREE)
11345 error = wrap_not_worktree_error(error,
11346 "rebase", cwd);
11347 goto done;
11351 error = get_gitconfig_path(&gitconfig_path);
11352 if (error)
11353 goto done;
11354 error = got_repo_open(&repo,
11355 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11356 gitconfig_path, pack_fds);
11357 if (error != NULL)
11358 goto done;
11360 if (worktree != NULL && !list_backups && !delete_backups) {
11361 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11362 if (error)
11363 goto done;
11366 error = get_author(&committer, repo, worktree);
11367 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11368 goto done;
11370 error = apply_unveil(got_repo_get_path(repo), 0,
11371 worktree ? got_worktree_get_root_path(worktree) : NULL);
11372 if (error)
11373 goto done;
11375 if (list_backups || delete_backups) {
11376 error = process_backup_refs(
11377 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11378 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11379 goto done; /* nothing else to do */
11382 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11383 worktree);
11384 if (error)
11385 goto done;
11386 if (histedit_in_progress) {
11387 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11388 goto done;
11391 error = got_worktree_merge_in_progress(&merge_in_progress,
11392 worktree, repo);
11393 if (error)
11394 goto done;
11395 if (merge_in_progress) {
11396 error = got_error(GOT_ERR_MERGE_BUSY);
11397 goto done;
11400 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11401 if (error)
11402 goto done;
11404 if (abort_rebase) {
11405 if (!rebase_in_progress) {
11406 error = got_error(GOT_ERR_NOT_REBASING);
11407 goto done;
11409 error = got_worktree_rebase_continue(&resume_commit_id,
11410 &new_base_branch, &tmp_branch, &branch, &fileindex,
11411 worktree, repo);
11412 if (error)
11413 goto done;
11414 printf("Switching work tree to %s\n",
11415 got_ref_get_symref_target(new_base_branch));
11416 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11417 new_base_branch, abort_progress, &upa);
11418 if (error)
11419 goto done;
11420 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11421 print_merge_progress_stats(&upa);
11422 goto done; /* nothing else to do */
11425 if (continue_rebase) {
11426 if (!rebase_in_progress) {
11427 error = got_error(GOT_ERR_NOT_REBASING);
11428 goto done;
11430 error = got_worktree_rebase_continue(&resume_commit_id,
11431 &new_base_branch, &tmp_branch, &branch, &fileindex,
11432 worktree, repo);
11433 if (error)
11434 goto done;
11436 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11437 committer, resume_commit_id, allow_conflict, repo);
11438 if (error)
11439 goto done;
11441 yca_id = got_object_id_dup(resume_commit_id);
11442 if (yca_id == NULL) {
11443 error = got_error_from_errno("got_object_id_dup");
11444 goto done;
11446 } else {
11447 error = got_ref_open(&branch, repo, argv[0], 0);
11448 if (error != NULL)
11449 goto done;
11450 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11451 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11452 "will not rebase a branch which lives outside "
11453 "the \"refs/heads/\" reference namespace");
11454 goto done;
11458 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11459 if (error)
11460 goto done;
11462 if (!continue_rebase) {
11463 struct got_object_id *base_commit_id;
11465 error = got_ref_open(&head_ref, repo,
11466 got_worktree_get_head_ref_name(worktree), 0);
11467 if (error)
11468 goto done;
11469 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11470 if (error)
11471 goto done;
11472 base_commit_id = got_worktree_get_base_commit_id(worktree);
11473 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11474 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11475 goto done;
11478 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11479 base_commit_id, branch_head_commit_id, 1, repo,
11480 check_cancelled, NULL);
11481 if (error) {
11482 if (error->code == GOT_ERR_ANCESTRY) {
11483 error = got_error_msg(GOT_ERR_ANCESTRY,
11484 "specified branch shares no common "
11485 "ancestry with work tree's branch");
11487 goto done;
11490 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11491 struct got_pathlist_head paths;
11492 printf("%s is already based on %s\n",
11493 got_ref_get_name(branch),
11494 got_worktree_get_head_ref_name(worktree));
11495 error = switch_head_ref(branch, branch_head_commit_id,
11496 worktree, repo);
11497 if (error)
11498 goto done;
11499 error = got_worktree_set_base_commit_id(worktree, repo,
11500 branch_head_commit_id);
11501 if (error)
11502 goto done;
11503 TAILQ_INIT(&paths);
11504 error = got_pathlist_append(&paths, "", NULL);
11505 if (error)
11506 goto done;
11507 error = got_worktree_checkout_files(worktree,
11508 &paths, repo, update_progress, &upa,
11509 check_cancelled, NULL);
11510 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11511 if (error)
11512 goto done;
11513 if (upa.did_something) {
11514 char *id_str;
11515 error = got_object_id_str(&id_str,
11516 branch_head_commit_id);
11517 if (error)
11518 goto done;
11519 printf("Updated to %s: %s\n",
11520 got_worktree_get_head_ref_name(worktree),
11521 id_str);
11522 free(id_str);
11523 } else
11524 printf("Already up-to-date\n");
11525 print_update_progress_stats(&upa);
11526 goto done;
11530 commit_id = branch_head_commit_id;
11531 error = got_object_open_as_commit(&commit, repo, commit_id);
11532 if (error)
11533 goto done;
11535 parent_ids = got_object_commit_get_parent_ids(commit);
11536 pid = STAILQ_FIRST(parent_ids);
11537 if (pid) {
11538 error = collect_commits(&commits, commit_id, &pid->id,
11539 yca_id, got_worktree_get_path_prefix(worktree),
11540 GOT_ERR_REBASE_PATH, repo);
11541 if (error)
11542 goto done;
11545 got_object_commit_close(commit);
11546 commit = NULL;
11548 if (!continue_rebase) {
11549 error = got_worktree_rebase_prepare(&new_base_branch,
11550 &tmp_branch, &fileindex, worktree, branch, repo);
11551 if (error)
11552 goto done;
11555 if (STAILQ_EMPTY(&commits)) {
11556 if (continue_rebase) {
11557 error = rebase_complete(worktree, fileindex,
11558 branch, tmp_branch, repo, create_backup);
11559 goto done;
11560 } else {
11561 /* Fast-forward the reference of the branch. */
11562 struct got_object_id *new_head_commit_id;
11563 char *id_str;
11564 error = got_ref_resolve(&new_head_commit_id, repo,
11565 new_base_branch);
11566 if (error)
11567 goto done;
11568 error = got_object_id_str(&id_str, new_head_commit_id);
11569 if (error)
11570 goto done;
11571 printf("Forwarding %s to commit %s\n",
11572 got_ref_get_name(branch), id_str);
11573 free(id_str);
11574 error = got_ref_change_ref(branch,
11575 new_head_commit_id);
11576 if (error)
11577 goto done;
11578 /* No backup needed since objects did not change. */
11579 create_backup = 0;
11583 pid = NULL;
11584 STAILQ_FOREACH(qid, &commits, entry) {
11586 commit_id = &qid->id;
11587 parent_id = pid ? &pid->id : yca_id;
11588 pid = qid;
11590 memset(&upa, 0, sizeof(upa));
11591 error = got_worktree_rebase_merge_files(&merged_paths,
11592 worktree, fileindex, parent_id, commit_id, repo,
11593 update_progress, &upa, check_cancelled, NULL);
11594 if (error)
11595 goto done;
11597 print_merge_progress_stats(&upa);
11598 if (upa.conflicts > 0 || upa.missing > 0 ||
11599 upa.not_deleted > 0 || upa.unversioned > 0) {
11600 if (upa.conflicts > 0) {
11601 error = show_rebase_merge_conflict(&qid->id,
11602 repo);
11603 if (error)
11604 goto done;
11606 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11607 break;
11610 error = rebase_commit(&merged_paths, worktree, fileindex,
11611 tmp_branch, committer, commit_id, 0, repo);
11612 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11613 if (error)
11614 goto done;
11617 if (upa.conflicts > 0 || upa.missing > 0 ||
11618 upa.not_deleted > 0 || upa.unversioned > 0) {
11619 error = got_worktree_rebase_postpone(worktree, fileindex);
11620 if (error)
11621 goto done;
11622 if (upa.conflicts > 0 && upa.missing == 0 &&
11623 upa.not_deleted == 0 && upa.unversioned == 0) {
11624 error = got_error_msg(GOT_ERR_CONFLICTS,
11625 "conflicts must be resolved before rebasing "
11626 "can continue");
11627 } else if (upa.conflicts > 0) {
11628 error = got_error_msg(GOT_ERR_CONFLICTS,
11629 "conflicts must be resolved before rebasing "
11630 "can continue; changes destined for some "
11631 "files were not yet merged and should be "
11632 "merged manually if required before the "
11633 "rebase operation is continued");
11634 } else {
11635 error = got_error_msg(GOT_ERR_CONFLICTS,
11636 "changes destined for some files were not "
11637 "yet merged and should be merged manually "
11638 "if required before the rebase operation "
11639 "is continued");
11641 } else
11642 error = rebase_complete(worktree, fileindex, branch,
11643 tmp_branch, repo, create_backup);
11644 done:
11645 free(cwd);
11646 free(committer);
11647 free(gitconfig_path);
11648 got_object_id_queue_free(&commits);
11649 free(branch_head_commit_id);
11650 free(resume_commit_id);
11651 free(head_commit_id);
11652 free(yca_id);
11653 if (commit)
11654 got_object_commit_close(commit);
11655 if (branch)
11656 got_ref_close(branch);
11657 if (new_base_branch)
11658 got_ref_close(new_base_branch);
11659 if (tmp_branch)
11660 got_ref_close(tmp_branch);
11661 if (head_ref)
11662 got_ref_close(head_ref);
11663 if (worktree)
11664 got_worktree_close(worktree);
11665 if (repo) {
11666 const struct got_error *close_err = got_repo_close(repo);
11667 if (error == NULL)
11668 error = close_err;
11670 if (pack_fds) {
11671 const struct got_error *pack_err =
11672 got_repo_pack_fds_close(pack_fds);
11673 if (error == NULL)
11674 error = pack_err;
11676 return error;
11679 __dead static void
11680 usage_histedit(void)
11682 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11683 "[branch]\n", getprogname());
11684 exit(1);
11687 #define GOT_HISTEDIT_PICK 'p'
11688 #define GOT_HISTEDIT_EDIT 'e'
11689 #define GOT_HISTEDIT_FOLD 'f'
11690 #define GOT_HISTEDIT_DROP 'd'
11691 #define GOT_HISTEDIT_MESG 'm'
11693 static const struct got_histedit_cmd {
11694 unsigned char code;
11695 const char *name;
11696 const char *desc;
11697 } got_histedit_cmds[] = {
11698 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11699 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11700 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11701 "be used" },
11702 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11703 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11706 struct got_histedit_list_entry {
11707 TAILQ_ENTRY(got_histedit_list_entry) entry;
11708 struct got_object_id *commit_id;
11709 const struct got_histedit_cmd *cmd;
11710 char *logmsg;
11712 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11714 static const struct got_error *
11715 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11716 FILE *f, struct got_repository *repo)
11718 const struct got_error *err = NULL;
11719 char *logmsg = NULL, *id_str = NULL;
11720 struct got_commit_object *commit = NULL;
11721 int n;
11723 err = got_object_open_as_commit(&commit, repo, commit_id);
11724 if (err)
11725 goto done;
11727 err = get_short_logmsg(&logmsg, 34, commit);
11728 if (err)
11729 goto done;
11731 err = got_object_id_str(&id_str, commit_id);
11732 if (err)
11733 goto done;
11735 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11736 if (n < 0)
11737 err = got_ferror(f, GOT_ERR_IO);
11738 done:
11739 if (commit)
11740 got_object_commit_close(commit);
11741 free(id_str);
11742 free(logmsg);
11743 return err;
11746 static const struct got_error *
11747 histedit_write_commit_list(struct got_object_id_queue *commits,
11748 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11749 int edit_only, struct got_repository *repo)
11751 const struct got_error *err = NULL;
11752 struct got_object_qid *qid;
11753 const char *histedit_cmd = NULL;
11755 if (STAILQ_EMPTY(commits))
11756 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11758 STAILQ_FOREACH(qid, commits, entry) {
11759 histedit_cmd = got_histedit_cmds[0].name;
11760 if (drop_only)
11761 histedit_cmd = "drop";
11762 else if (edit_only)
11763 histedit_cmd = "edit";
11764 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11765 histedit_cmd = "fold";
11766 else if (edit_logmsg_only)
11767 histedit_cmd = "mesg";
11768 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11769 if (err)
11770 break;
11773 return err;
11776 static const struct got_error *
11777 write_cmd_list(FILE *f, const char *branch_name,
11778 struct got_object_id_queue *commits)
11780 const struct got_error *err = NULL;
11781 size_t i;
11782 int n;
11783 char *id_str;
11784 struct got_object_qid *qid;
11786 qid = STAILQ_FIRST(commits);
11787 err = got_object_id_str(&id_str, &qid->id);
11788 if (err)
11789 return err;
11791 n = fprintf(f,
11792 "# Editing the history of branch '%s' starting at\n"
11793 "# commit %s\n"
11794 "# Commits will be processed in order from top to "
11795 "bottom of this file.\n", branch_name, id_str);
11796 if (n < 0) {
11797 err = got_ferror(f, GOT_ERR_IO);
11798 goto done;
11801 n = fprintf(f, "# Available histedit commands:\n");
11802 if (n < 0) {
11803 err = got_ferror(f, GOT_ERR_IO);
11804 goto done;
11807 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11808 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11809 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11810 cmd->desc);
11811 if (n < 0) {
11812 err = got_ferror(f, GOT_ERR_IO);
11813 break;
11816 done:
11817 free(id_str);
11818 return err;
11821 static const struct got_error *
11822 histedit_syntax_error(int lineno)
11824 static char msg[42];
11825 int ret;
11827 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11828 lineno);
11829 if (ret < 0 || (size_t)ret >= sizeof(msg))
11830 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11832 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11835 static const struct got_error *
11836 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11837 char *logmsg, struct got_repository *repo)
11839 const struct got_error *err;
11840 struct got_commit_object *folded_commit = NULL;
11841 char *id_str, *folded_logmsg = NULL;
11843 err = got_object_id_str(&id_str, hle->commit_id);
11844 if (err)
11845 return err;
11847 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11848 if (err)
11849 goto done;
11851 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11852 if (err)
11853 goto done;
11854 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11855 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11856 folded_logmsg) == -1) {
11857 err = got_error_from_errno("asprintf");
11859 done:
11860 if (folded_commit)
11861 got_object_commit_close(folded_commit);
11862 free(id_str);
11863 free(folded_logmsg);
11864 return err;
11867 static struct got_histedit_list_entry *
11868 get_folded_commits(struct got_histedit_list_entry *hle)
11870 struct got_histedit_list_entry *prev, *folded = NULL;
11872 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11873 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11874 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11875 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11876 folded = prev;
11877 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11880 return folded;
11883 static const struct got_error *
11884 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11885 struct got_repository *repo)
11887 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11888 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11889 const struct got_error *err = NULL;
11890 struct got_commit_object *commit = NULL;
11891 int logmsg_len;
11892 int fd = -1;
11893 struct got_histedit_list_entry *folded = NULL;
11895 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11896 if (err)
11897 return err;
11899 folded = get_folded_commits(hle);
11900 if (folded) {
11901 while (folded != hle) {
11902 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11903 folded = TAILQ_NEXT(folded, entry);
11904 continue;
11906 err = append_folded_commit_msg(&new_msg, folded,
11907 logmsg, repo);
11908 if (err)
11909 goto done;
11910 free(logmsg);
11911 logmsg = new_msg;
11912 folded = TAILQ_NEXT(folded, entry);
11916 err = got_object_id_str(&id_str, hle->commit_id);
11917 if (err)
11918 goto done;
11919 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11920 if (err)
11921 goto done;
11922 logmsg_len = asprintf(&new_msg,
11923 "%s\n# original log message of commit %s: %s",
11924 logmsg ? logmsg : "", id_str, orig_logmsg);
11925 if (logmsg_len == -1) {
11926 err = got_error_from_errno("asprintf");
11927 goto done;
11929 free(logmsg);
11930 logmsg = new_msg;
11932 err = got_object_id_str(&id_str, hle->commit_id);
11933 if (err)
11934 goto done;
11936 err = got_opentemp_named_fd(&logmsg_path, &fd,
11937 GOT_TMPDIR_STR "/got-logmsg", "");
11938 if (err)
11939 goto done;
11941 if (write(fd, logmsg, logmsg_len) == -1) {
11942 err = got_error_from_errno2("write", logmsg_path);
11943 goto done;
11945 if (close(fd) == -1) {
11946 err = got_error_from_errno2("close", logmsg_path);
11947 goto done;
11949 fd = -1;
11951 err = get_editor(&editor);
11952 if (err)
11953 goto done;
11955 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11956 logmsg_len, 0);
11957 if (err) {
11958 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11959 goto done;
11960 err = NULL;
11961 hle->logmsg = strdup(new_msg);
11962 if (hle->logmsg == NULL)
11963 err = got_error_from_errno("strdup");
11965 done:
11966 if (fd != -1 && close(fd) == -1 && err == NULL)
11967 err = got_error_from_errno2("close", logmsg_path);
11968 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11969 err = got_error_from_errno2("unlink", logmsg_path);
11970 free(logmsg_path);
11971 free(logmsg);
11972 free(orig_logmsg);
11973 free(editor);
11974 if (commit)
11975 got_object_commit_close(commit);
11976 return err;
11979 static const struct got_error *
11980 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11981 FILE *f, struct got_repository *repo)
11983 const struct got_error *err = NULL;
11984 char *line = NULL, *p, *end;
11985 size_t i, linesize = 0;
11986 ssize_t linelen;
11987 int lineno = 0;
11988 const struct got_histedit_cmd *cmd;
11989 struct got_object_id *commit_id = NULL;
11990 struct got_histedit_list_entry *hle = NULL;
11992 for (;;) {
11993 linelen = getline(&line, &linesize, f);
11994 if (linelen == -1) {
11995 const struct got_error *getline_err;
11996 if (feof(f))
11997 break;
11998 getline_err = got_error_from_errno("getline");
11999 err = got_ferror(f, getline_err->code);
12000 break;
12002 lineno++;
12003 p = line;
12004 while (isspace((unsigned char)p[0]))
12005 p++;
12006 if (p[0] == '#' || p[0] == '\0')
12007 continue;
12008 cmd = NULL;
12009 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12010 cmd = &got_histedit_cmds[i];
12011 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12012 isspace((unsigned char)p[strlen(cmd->name)])) {
12013 p += strlen(cmd->name);
12014 break;
12016 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12017 p++;
12018 break;
12021 if (i == nitems(got_histedit_cmds)) {
12022 err = histedit_syntax_error(lineno);
12023 break;
12025 while (isspace((unsigned char)p[0]))
12026 p++;
12027 end = p;
12028 while (end[0] && !isspace((unsigned char)end[0]))
12029 end++;
12030 *end = '\0';
12031 err = got_object_resolve_id_str(&commit_id, repo, p);
12032 if (err) {
12033 /* override error code */
12034 err = histedit_syntax_error(lineno);
12035 break;
12037 hle = malloc(sizeof(*hle));
12038 if (hle == NULL) {
12039 err = got_error_from_errno("malloc");
12040 break;
12042 hle->cmd = cmd;
12043 hle->commit_id = commit_id;
12044 hle->logmsg = NULL;
12045 commit_id = NULL;
12046 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12049 free(line);
12050 free(commit_id);
12051 return err;
12054 static const struct got_error *
12055 histedit_check_script(struct got_histedit_list *histedit_cmds,
12056 struct got_object_id_queue *commits, struct got_repository *repo)
12058 const struct got_error *err = NULL;
12059 struct got_object_qid *qid;
12060 struct got_histedit_list_entry *hle;
12061 static char msg[92];
12062 char *id_str;
12064 if (TAILQ_EMPTY(histedit_cmds))
12065 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12066 "histedit script contains no commands");
12067 if (STAILQ_EMPTY(commits))
12068 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12070 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12071 struct got_histedit_list_entry *hle2;
12072 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12073 if (hle == hle2)
12074 continue;
12075 if (got_object_id_cmp(hle->commit_id,
12076 hle2->commit_id) != 0)
12077 continue;
12078 err = got_object_id_str(&id_str, hle->commit_id);
12079 if (err)
12080 return err;
12081 snprintf(msg, sizeof(msg), "commit %s is listed "
12082 "more than once in histedit script", id_str);
12083 free(id_str);
12084 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12088 STAILQ_FOREACH(qid, commits, entry) {
12089 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12090 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12091 break;
12093 if (hle == NULL) {
12094 err = got_object_id_str(&id_str, &qid->id);
12095 if (err)
12096 return err;
12097 snprintf(msg, sizeof(msg),
12098 "commit %s missing from histedit script", id_str);
12099 free(id_str);
12100 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12104 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12105 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12106 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12107 "last commit in histedit script cannot be folded");
12109 return NULL;
12112 static const struct got_error *
12113 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12114 const char *path, struct got_object_id_queue *commits,
12115 struct got_repository *repo)
12117 const struct got_error *err = NULL;
12118 struct stat st, st2;
12119 struct timespec timeout;
12120 char *editor;
12121 FILE *f = NULL;
12123 err = get_editor(&editor);
12124 if (err)
12125 return err;
12127 if (stat(path, &st) == -1) {
12128 err = got_error_from_errno2("stat", path);
12129 goto done;
12132 if (spawn_editor(editor, path) == -1) {
12133 err = got_error_from_errno("failed spawning editor");
12134 goto done;
12137 timeout.tv_sec = 0;
12138 timeout.tv_nsec = 1;
12139 nanosleep(&timeout, NULL);
12141 if (stat(path, &st2) == -1) {
12142 err = got_error_from_errno2("stat", path);
12143 goto done;
12146 if (st.st_size == st2.st_size &&
12147 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12148 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12149 "no changes made to histedit script, aborting");
12150 goto done;
12153 f = fopen(path, "re");
12154 if (f == NULL) {
12155 err = got_error_from_errno("fopen");
12156 goto done;
12158 err = histedit_parse_list(histedit_cmds, f, repo);
12159 if (err)
12160 goto done;
12162 err = histedit_check_script(histedit_cmds, commits, repo);
12163 done:
12164 if (f && fclose(f) == EOF && err == NULL)
12165 err = got_error_from_errno("fclose");
12166 free(editor);
12167 return err;
12170 static const struct got_error *
12171 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12172 struct got_object_id_queue *, const char *, const char *,
12173 struct got_repository *);
12175 static const struct got_error *
12176 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12177 struct got_object_id_queue *commits, const char *branch_name,
12178 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12179 struct got_repository *repo)
12181 const struct got_error *err;
12182 FILE *f = NULL;
12183 char *path = NULL;
12185 err = got_opentemp_named(&path, &f, "got-histedit", "");
12186 if (err)
12187 return err;
12189 err = write_cmd_list(f, branch_name, commits);
12190 if (err)
12191 goto done;
12193 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12194 fold_only, drop_only, edit_only, repo);
12195 if (err)
12196 goto done;
12198 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12199 rewind(f);
12200 err = histedit_parse_list(histedit_cmds, f, repo);
12201 } else {
12202 if (fclose(f) == EOF) {
12203 err = got_error_from_errno("fclose");
12204 goto done;
12206 f = NULL;
12207 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12208 if (err) {
12209 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12210 err->code != GOT_ERR_HISTEDIT_CMD)
12211 goto done;
12212 err = histedit_edit_list_retry(histedit_cmds, err,
12213 commits, path, branch_name, repo);
12216 done:
12217 if (f && fclose(f) == EOF && err == NULL)
12218 err = got_error_from_errno("fclose");
12219 if (path && unlink(path) != 0 && err == NULL)
12220 err = got_error_from_errno2("unlink", path);
12221 free(path);
12222 return err;
12225 static const struct got_error *
12226 histedit_save_list(struct got_histedit_list *histedit_cmds,
12227 struct got_worktree *worktree, struct got_repository *repo)
12229 const struct got_error *err = NULL;
12230 char *path = NULL;
12231 FILE *f = NULL;
12232 struct got_histedit_list_entry *hle;
12234 err = got_worktree_get_histedit_script_path(&path, worktree);
12235 if (err)
12236 return err;
12238 f = fopen(path, "we");
12239 if (f == NULL) {
12240 err = got_error_from_errno2("fopen", path);
12241 goto done;
12243 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12244 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12245 repo);
12246 if (err)
12247 break;
12249 done:
12250 if (f && fclose(f) == EOF && err == NULL)
12251 err = got_error_from_errno("fclose");
12252 free(path);
12253 return err;
12256 static void
12257 histedit_free_list(struct got_histedit_list *histedit_cmds)
12259 struct got_histedit_list_entry *hle;
12261 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12262 TAILQ_REMOVE(histedit_cmds, hle, entry);
12263 free(hle);
12267 static const struct got_error *
12268 histedit_load_list(struct got_histedit_list *histedit_cmds,
12269 const char *path, struct got_repository *repo)
12271 const struct got_error *err = NULL;
12272 FILE *f = NULL;
12274 f = fopen(path, "re");
12275 if (f == NULL) {
12276 err = got_error_from_errno2("fopen", path);
12277 goto done;
12280 err = histedit_parse_list(histedit_cmds, f, repo);
12281 done:
12282 if (f && fclose(f) == EOF && err == NULL)
12283 err = got_error_from_errno("fclose");
12284 return err;
12287 static const struct got_error *
12288 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12289 const struct got_error *edit_err, struct got_object_id_queue *commits,
12290 const char *path, const char *branch_name, struct got_repository *repo)
12292 const struct got_error *err = NULL, *prev_err = edit_err;
12293 int resp = ' ';
12295 while (resp != 'c' && resp != 'r' && resp != 'a') {
12296 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12297 "or (a)bort: ", getprogname(), prev_err->msg);
12298 resp = getchar();
12299 if (resp == '\n')
12300 resp = getchar();
12301 if (resp == 'c') {
12302 histedit_free_list(histedit_cmds);
12303 err = histedit_run_editor(histedit_cmds, path, commits,
12304 repo);
12305 if (err) {
12306 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12307 err->code != GOT_ERR_HISTEDIT_CMD)
12308 break;
12309 prev_err = err;
12310 resp = ' ';
12311 continue;
12313 break;
12314 } else if (resp == 'r') {
12315 histedit_free_list(histedit_cmds);
12316 err = histedit_edit_script(histedit_cmds,
12317 commits, branch_name, 0, 0, 0, 0, repo);
12318 if (err) {
12319 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12320 err->code != GOT_ERR_HISTEDIT_CMD)
12321 break;
12322 prev_err = err;
12323 resp = ' ';
12324 continue;
12326 break;
12327 } else if (resp == 'a') {
12328 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12329 break;
12330 } else
12331 printf("invalid response '%c'\n", resp);
12334 return err;
12337 static const struct got_error *
12338 histedit_complete(struct got_worktree *worktree,
12339 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12340 struct got_reference *branch, struct got_repository *repo)
12342 printf("Switching work tree to %s\n",
12343 got_ref_get_symref_target(branch));
12344 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12345 branch, repo);
12348 static const struct got_error *
12349 show_histedit_progress(struct got_commit_object *commit,
12350 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12352 const struct got_error *err;
12353 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12355 err = got_object_id_str(&old_id_str, hle->commit_id);
12356 if (err)
12357 goto done;
12359 if (new_id) {
12360 err = got_object_id_str(&new_id_str, new_id);
12361 if (err)
12362 goto done;
12365 old_id_str[12] = '\0';
12366 if (new_id_str)
12367 new_id_str[12] = '\0';
12369 if (hle->logmsg) {
12370 logmsg = strdup(hle->logmsg);
12371 if (logmsg == NULL) {
12372 err = got_error_from_errno("strdup");
12373 goto done;
12375 trim_logmsg(logmsg, 42);
12376 } else {
12377 err = get_short_logmsg(&logmsg, 42, commit);
12378 if (err)
12379 goto done;
12382 switch (hle->cmd->code) {
12383 case GOT_HISTEDIT_PICK:
12384 case GOT_HISTEDIT_EDIT:
12385 case GOT_HISTEDIT_MESG:
12386 printf("%s -> %s: %s\n", old_id_str,
12387 new_id_str ? new_id_str : "no-op change", logmsg);
12388 break;
12389 case GOT_HISTEDIT_DROP:
12390 case GOT_HISTEDIT_FOLD:
12391 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12392 logmsg);
12393 break;
12394 default:
12395 break;
12397 done:
12398 free(old_id_str);
12399 free(new_id_str);
12400 return err;
12403 static const struct got_error *
12404 histedit_commit(struct got_pathlist_head *merged_paths,
12405 struct got_worktree *worktree, struct got_fileindex *fileindex,
12406 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12407 const char *committer, int allow_conflict, struct got_repository *repo)
12409 const struct got_error *err;
12410 struct got_commit_object *commit;
12411 struct got_object_id *new_commit_id;
12413 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12414 && hle->logmsg == NULL) {
12415 err = histedit_edit_logmsg(hle, repo);
12416 if (err)
12417 return err;
12420 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12421 if (err)
12422 return err;
12424 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12425 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12426 hle->logmsg, allow_conflict, repo);
12427 if (err) {
12428 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12429 goto done;
12430 err = show_histedit_progress(commit, hle, NULL);
12431 } else {
12432 err = show_histedit_progress(commit, hle, new_commit_id);
12433 free(new_commit_id);
12435 done:
12436 got_object_commit_close(commit);
12437 return err;
12440 static const struct got_error *
12441 histedit_skip_commit(struct got_histedit_list_entry *hle,
12442 struct got_worktree *worktree, struct got_repository *repo)
12444 const struct got_error *error;
12445 struct got_commit_object *commit;
12447 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12448 repo);
12449 if (error)
12450 return error;
12452 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12453 if (error)
12454 return error;
12456 error = show_histedit_progress(commit, hle, NULL);
12457 got_object_commit_close(commit);
12458 return error;
12461 static const struct got_error *
12462 check_local_changes(void *arg, unsigned char status,
12463 unsigned char staged_status, const char *path,
12464 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12465 struct got_object_id *commit_id, int dirfd, const char *de_name)
12467 int *have_local_changes = arg;
12469 switch (status) {
12470 case GOT_STATUS_ADD:
12471 case GOT_STATUS_DELETE:
12472 case GOT_STATUS_MODIFY:
12473 case GOT_STATUS_CONFLICT:
12474 *have_local_changes = 1;
12475 return got_error(GOT_ERR_CANCELLED);
12476 default:
12477 break;
12480 switch (staged_status) {
12481 case GOT_STATUS_ADD:
12482 case GOT_STATUS_DELETE:
12483 case GOT_STATUS_MODIFY:
12484 *have_local_changes = 1;
12485 return got_error(GOT_ERR_CANCELLED);
12486 default:
12487 break;
12490 return NULL;
12493 static const struct got_error *
12494 cmd_histedit(int argc, char *argv[])
12496 const struct got_error *error = NULL;
12497 struct got_worktree *worktree = NULL;
12498 struct got_fileindex *fileindex = NULL;
12499 struct got_repository *repo = NULL;
12500 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12501 struct got_reference *branch = NULL;
12502 struct got_reference *tmp_branch = NULL;
12503 struct got_object_id *resume_commit_id = NULL;
12504 struct got_object_id *base_commit_id = NULL;
12505 struct got_object_id *head_commit_id = NULL;
12506 struct got_commit_object *commit = NULL;
12507 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12508 struct got_update_progress_arg upa;
12509 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12510 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12511 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12512 const char *edit_script_path = NULL;
12513 struct got_object_id_queue commits;
12514 struct got_pathlist_head merged_paths;
12515 const struct got_object_id_queue *parent_ids;
12516 struct got_object_qid *pid;
12517 struct got_histedit_list histedit_cmds;
12518 struct got_histedit_list_entry *hle;
12519 int *pack_fds = NULL;
12521 STAILQ_INIT(&commits);
12522 TAILQ_INIT(&histedit_cmds);
12523 TAILQ_INIT(&merged_paths);
12524 memset(&upa, 0, sizeof(upa));
12526 #ifndef PROFILE
12527 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12528 "unveil", NULL) == -1)
12529 err(1, "pledge");
12530 #endif
12532 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12533 switch (ch) {
12534 case 'a':
12535 abort_edit = 1;
12536 break;
12537 case 'C':
12538 allow_conflict = 1;
12539 break;
12540 case 'c':
12541 continue_edit = 1;
12542 break;
12543 case 'd':
12544 drop_only = 1;
12545 break;
12546 case 'e':
12547 edit_only = 1;
12548 break;
12549 case 'F':
12550 edit_script_path = optarg;
12551 break;
12552 case 'f':
12553 fold_only = 1;
12554 break;
12555 case 'l':
12556 list_backups = 1;
12557 break;
12558 case 'm':
12559 edit_logmsg_only = 1;
12560 break;
12561 case 'X':
12562 delete_backups = 1;
12563 break;
12564 default:
12565 usage_histedit();
12566 /* NOTREACHED */
12570 argc -= optind;
12571 argv += optind;
12573 if (abort_edit && allow_conflict)
12574 option_conflict('a', 'C');
12575 if (abort_edit && continue_edit)
12576 option_conflict('a', 'c');
12577 if (edit_script_path && allow_conflict)
12578 option_conflict('F', 'C');
12579 if (edit_script_path && edit_logmsg_only)
12580 option_conflict('F', 'm');
12581 if (abort_edit && edit_logmsg_only)
12582 option_conflict('a', 'm');
12583 if (edit_logmsg_only && allow_conflict)
12584 option_conflict('m', 'C');
12585 if (continue_edit && edit_logmsg_only)
12586 option_conflict('c', 'm');
12587 if (abort_edit && fold_only)
12588 option_conflict('a', 'f');
12589 if (fold_only && allow_conflict)
12590 option_conflict('f', 'C');
12591 if (continue_edit && fold_only)
12592 option_conflict('c', 'f');
12593 if (fold_only && edit_logmsg_only)
12594 option_conflict('f', 'm');
12595 if (edit_script_path && fold_only)
12596 option_conflict('F', 'f');
12597 if (abort_edit && edit_only)
12598 option_conflict('a', 'e');
12599 if (continue_edit && edit_only)
12600 option_conflict('c', 'e');
12601 if (edit_only && edit_logmsg_only)
12602 option_conflict('e', 'm');
12603 if (edit_script_path && edit_only)
12604 option_conflict('F', 'e');
12605 if (fold_only && edit_only)
12606 option_conflict('f', 'e');
12607 if (drop_only && abort_edit)
12608 option_conflict('d', 'a');
12609 if (drop_only && allow_conflict)
12610 option_conflict('d', 'C');
12611 if (drop_only && continue_edit)
12612 option_conflict('d', 'c');
12613 if (drop_only && edit_logmsg_only)
12614 option_conflict('d', 'm');
12615 if (drop_only && edit_only)
12616 option_conflict('d', 'e');
12617 if (drop_only && edit_script_path)
12618 option_conflict('d', 'F');
12619 if (drop_only && fold_only)
12620 option_conflict('d', 'f');
12621 if (list_backups) {
12622 if (abort_edit)
12623 option_conflict('l', 'a');
12624 if (allow_conflict)
12625 option_conflict('l', 'C');
12626 if (continue_edit)
12627 option_conflict('l', 'c');
12628 if (edit_script_path)
12629 option_conflict('l', 'F');
12630 if (edit_logmsg_only)
12631 option_conflict('l', 'm');
12632 if (drop_only)
12633 option_conflict('l', 'd');
12634 if (fold_only)
12635 option_conflict('l', 'f');
12636 if (edit_only)
12637 option_conflict('l', 'e');
12638 if (delete_backups)
12639 option_conflict('l', 'X');
12640 if (argc != 0 && argc != 1)
12641 usage_histedit();
12642 } else if (delete_backups) {
12643 if (abort_edit)
12644 option_conflict('X', 'a');
12645 if (allow_conflict)
12646 option_conflict('X', 'C');
12647 if (continue_edit)
12648 option_conflict('X', 'c');
12649 if (drop_only)
12650 option_conflict('X', 'd');
12651 if (edit_script_path)
12652 option_conflict('X', 'F');
12653 if (edit_logmsg_only)
12654 option_conflict('X', 'm');
12655 if (fold_only)
12656 option_conflict('X', 'f');
12657 if (edit_only)
12658 option_conflict('X', 'e');
12659 if (list_backups)
12660 option_conflict('X', 'l');
12661 if (argc != 0 && argc != 1)
12662 usage_histedit();
12663 } else if (allow_conflict && !continue_edit)
12664 errx(1, "-C option requires -c");
12665 else if (argc != 0)
12666 usage_histedit();
12669 * This command cannot apply unveil(2) in all cases because the
12670 * user may choose to run an editor to edit the histedit script
12671 * and to edit individual commit log messages.
12672 * unveil(2) traverses exec(2); if an editor is used we have to
12673 * apply unveil after edit script and log messages have been written.
12674 * XXX TODO: Make use of unveil(2) where possible.
12677 cwd = getcwd(NULL, 0);
12678 if (cwd == NULL) {
12679 error = got_error_from_errno("getcwd");
12680 goto done;
12683 error = got_repo_pack_fds_open(&pack_fds);
12684 if (error != NULL)
12685 goto done;
12687 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12688 if (error) {
12689 if (list_backups || delete_backups) {
12690 if (error->code != GOT_ERR_NOT_WORKTREE)
12691 goto done;
12692 } else {
12693 if (error->code == GOT_ERR_NOT_WORKTREE)
12694 error = wrap_not_worktree_error(error,
12695 "histedit", cwd);
12696 goto done;
12700 if (list_backups || delete_backups) {
12701 error = got_repo_open(&repo,
12702 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12703 NULL, pack_fds);
12704 if (error != NULL)
12705 goto done;
12706 error = apply_unveil(got_repo_get_path(repo), 0,
12707 worktree ? got_worktree_get_root_path(worktree) : NULL);
12708 if (error)
12709 goto done;
12710 error = process_backup_refs(
12711 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12712 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12713 goto done; /* nothing else to do */
12716 error = get_gitconfig_path(&gitconfig_path);
12717 if (error)
12718 goto done;
12719 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12720 gitconfig_path, pack_fds);
12721 if (error != NULL)
12722 goto done;
12724 if (worktree != NULL && !list_backups && !delete_backups) {
12725 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12726 if (error)
12727 goto done;
12730 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12731 if (error)
12732 goto done;
12733 if (rebase_in_progress) {
12734 error = got_error(GOT_ERR_REBASING);
12735 goto done;
12738 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12739 repo);
12740 if (error)
12741 goto done;
12742 if (merge_in_progress) {
12743 error = got_error(GOT_ERR_MERGE_BUSY);
12744 goto done;
12747 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12748 if (error)
12749 goto done;
12751 if (edit_in_progress && edit_logmsg_only) {
12752 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12753 "histedit operation is in progress in this "
12754 "work tree and must be continued or aborted "
12755 "before the -m option can be used");
12756 goto done;
12758 if (edit_in_progress && drop_only) {
12759 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12760 "histedit operation is in progress in this "
12761 "work tree and must be continued or aborted "
12762 "before the -d option can be used");
12763 goto done;
12765 if (edit_in_progress && fold_only) {
12766 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12767 "histedit operation is in progress in this "
12768 "work tree and must be continued or aborted "
12769 "before the -f option can be used");
12770 goto done;
12772 if (edit_in_progress && edit_only) {
12773 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12774 "histedit operation is in progress in this "
12775 "work tree and must be continued or aborted "
12776 "before the -e option can be used");
12777 goto done;
12780 if (edit_in_progress && abort_edit) {
12781 error = got_worktree_histedit_continue(&resume_commit_id,
12782 &tmp_branch, &branch, &base_commit_id, &fileindex,
12783 worktree, repo);
12784 if (error)
12785 goto done;
12786 printf("Switching work tree to %s\n",
12787 got_ref_get_symref_target(branch));
12788 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12789 branch, base_commit_id, abort_progress, &upa);
12790 if (error)
12791 goto done;
12792 printf("Histedit of %s aborted\n",
12793 got_ref_get_symref_target(branch));
12794 print_merge_progress_stats(&upa);
12795 goto done; /* nothing else to do */
12796 } else if (abort_edit) {
12797 error = got_error(GOT_ERR_NOT_HISTEDIT);
12798 goto done;
12801 error = get_author(&committer, repo, worktree);
12802 if (error)
12803 goto done;
12805 if (continue_edit) {
12806 char *path;
12808 if (!edit_in_progress) {
12809 error = got_error(GOT_ERR_NOT_HISTEDIT);
12810 goto done;
12813 error = got_worktree_get_histedit_script_path(&path, worktree);
12814 if (error)
12815 goto done;
12817 error = histedit_load_list(&histedit_cmds, path, repo);
12818 free(path);
12819 if (error)
12820 goto done;
12822 error = got_worktree_histedit_continue(&resume_commit_id,
12823 &tmp_branch, &branch, &base_commit_id, &fileindex,
12824 worktree, repo);
12825 if (error)
12826 goto done;
12828 error = got_ref_resolve(&head_commit_id, repo, branch);
12829 if (error)
12830 goto done;
12832 error = got_object_open_as_commit(&commit, repo,
12833 head_commit_id);
12834 if (error)
12835 goto done;
12836 parent_ids = got_object_commit_get_parent_ids(commit);
12837 pid = STAILQ_FIRST(parent_ids);
12838 if (pid == NULL) {
12839 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12840 goto done;
12842 error = collect_commits(&commits, head_commit_id, &pid->id,
12843 base_commit_id, got_worktree_get_path_prefix(worktree),
12844 GOT_ERR_HISTEDIT_PATH, repo);
12845 got_object_commit_close(commit);
12846 commit = NULL;
12847 if (error)
12848 goto done;
12849 } else {
12850 if (edit_in_progress) {
12851 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12852 goto done;
12855 error = got_ref_open(&branch, repo,
12856 got_worktree_get_head_ref_name(worktree), 0);
12857 if (error != NULL)
12858 goto done;
12860 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12861 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12862 "will not edit commit history of a branch outside "
12863 "the \"refs/heads/\" reference namespace");
12864 goto done;
12867 error = got_ref_resolve(&head_commit_id, repo, branch);
12868 got_ref_close(branch);
12869 branch = NULL;
12870 if (error)
12871 goto done;
12873 error = got_object_open_as_commit(&commit, repo,
12874 head_commit_id);
12875 if (error)
12876 goto done;
12877 parent_ids = got_object_commit_get_parent_ids(commit);
12878 pid = STAILQ_FIRST(parent_ids);
12879 if (pid == NULL) {
12880 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12881 goto done;
12883 error = collect_commits(&commits, head_commit_id, &pid->id,
12884 got_worktree_get_base_commit_id(worktree),
12885 got_worktree_get_path_prefix(worktree),
12886 GOT_ERR_HISTEDIT_PATH, repo);
12887 got_object_commit_close(commit);
12888 commit = NULL;
12889 if (error)
12890 goto done;
12892 if (STAILQ_EMPTY(&commits)) {
12893 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12894 goto done;
12897 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12898 &base_commit_id, &fileindex, worktree, repo);
12899 if (error)
12900 goto done;
12902 if (edit_script_path) {
12903 error = histedit_load_list(&histedit_cmds,
12904 edit_script_path, repo);
12905 if (error) {
12906 got_worktree_histedit_abort(worktree, fileindex,
12907 repo, branch, base_commit_id,
12908 abort_progress, &upa);
12909 print_merge_progress_stats(&upa);
12910 goto done;
12912 } else {
12913 const char *branch_name;
12914 branch_name = got_ref_get_symref_target(branch);
12915 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12916 branch_name += 11;
12917 error = histedit_edit_script(&histedit_cmds, &commits,
12918 branch_name, edit_logmsg_only, fold_only,
12919 drop_only, edit_only, repo);
12920 if (error) {
12921 got_worktree_histedit_abort(worktree, fileindex,
12922 repo, branch, base_commit_id,
12923 abort_progress, &upa);
12924 print_merge_progress_stats(&upa);
12925 goto done;
12930 error = histedit_save_list(&histedit_cmds, worktree,
12931 repo);
12932 if (error) {
12933 got_worktree_histedit_abort(worktree, fileindex,
12934 repo, branch, base_commit_id,
12935 abort_progress, &upa);
12936 print_merge_progress_stats(&upa);
12937 goto done;
12942 error = histedit_check_script(&histedit_cmds, &commits, repo);
12943 if (error)
12944 goto done;
12946 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12947 if (resume_commit_id) {
12948 if (got_object_id_cmp(hle->commit_id,
12949 resume_commit_id) != 0)
12950 continue;
12952 resume_commit_id = NULL;
12953 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12954 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12955 error = histedit_skip_commit(hle, worktree,
12956 repo);
12957 if (error)
12958 goto done;
12959 } else {
12960 struct got_pathlist_head paths;
12961 int have_changes = 0;
12963 TAILQ_INIT(&paths);
12964 error = got_pathlist_append(&paths, "", NULL);
12965 if (error)
12966 goto done;
12967 error = got_worktree_status(worktree, &paths,
12968 repo, 0, check_local_changes, &have_changes,
12969 check_cancelled, NULL);
12970 got_pathlist_free(&paths,
12971 GOT_PATHLIST_FREE_NONE);
12972 if (error) {
12973 if (error->code != GOT_ERR_CANCELLED)
12974 goto done;
12975 if (sigint_received || sigpipe_received)
12976 goto done;
12978 if (have_changes) {
12979 error = histedit_commit(NULL, worktree,
12980 fileindex, tmp_branch, hle,
12981 committer, allow_conflict, repo);
12982 if (error)
12983 goto done;
12984 } else {
12985 error = got_object_open_as_commit(
12986 &commit, repo, hle->commit_id);
12987 if (error)
12988 goto done;
12989 error = show_histedit_progress(commit,
12990 hle, NULL);
12991 got_object_commit_close(commit);
12992 commit = NULL;
12993 if (error)
12994 goto done;
12997 continue;
13000 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13001 error = histedit_skip_commit(hle, worktree, repo);
13002 if (error)
13003 goto done;
13004 continue;
13006 error = got_object_open_as_commit(&commit, repo,
13007 hle->commit_id);
13008 if (error)
13009 goto done;
13010 parent_ids = got_object_commit_get_parent_ids(commit);
13011 pid = STAILQ_FIRST(parent_ids);
13013 error = got_worktree_histedit_merge_files(&merged_paths,
13014 worktree, fileindex, &pid->id, hle->commit_id, repo,
13015 update_progress, &upa, check_cancelled, NULL);
13016 if (error)
13017 goto done;
13018 got_object_commit_close(commit);
13019 commit = NULL;
13021 print_merge_progress_stats(&upa);
13022 if (upa.conflicts > 0 || upa.missing > 0 ||
13023 upa.not_deleted > 0 || upa.unversioned > 0) {
13024 if (upa.conflicts > 0) {
13025 error = show_rebase_merge_conflict(
13026 hle->commit_id, repo);
13027 if (error)
13028 goto done;
13030 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13031 break;
13034 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13035 char *id_str;
13036 error = got_object_id_str(&id_str, hle->commit_id);
13037 if (error)
13038 goto done;
13039 printf("Stopping histedit for amending commit %s\n",
13040 id_str);
13041 free(id_str);
13042 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13043 error = got_worktree_histedit_postpone(worktree,
13044 fileindex);
13045 goto done;
13046 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13047 error = histedit_skip_commit(hle, worktree, repo);
13048 if (error)
13049 goto done;
13050 continue;
13051 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13052 error = histedit_edit_logmsg(hle, repo);
13053 if (error)
13054 goto done;
13057 error = histedit_commit(&merged_paths, worktree, fileindex,
13058 tmp_branch, hle, committer, allow_conflict, repo);
13059 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13060 if (error)
13061 goto done;
13064 if (upa.conflicts > 0 || upa.missing > 0 ||
13065 upa.not_deleted > 0 || upa.unversioned > 0) {
13066 error = got_worktree_histedit_postpone(worktree, fileindex);
13067 if (error)
13068 goto done;
13069 if (upa.conflicts > 0 && upa.missing == 0 &&
13070 upa.not_deleted == 0 && upa.unversioned == 0) {
13071 error = got_error_msg(GOT_ERR_CONFLICTS,
13072 "conflicts must be resolved before histedit "
13073 "can continue");
13074 } else if (upa.conflicts > 0) {
13075 error = got_error_msg(GOT_ERR_CONFLICTS,
13076 "conflicts must be resolved before histedit "
13077 "can continue; changes destined for some "
13078 "files were not yet merged and should be "
13079 "merged manually if required before the "
13080 "histedit operation is continued");
13081 } else {
13082 error = got_error_msg(GOT_ERR_CONFLICTS,
13083 "changes destined for some files were not "
13084 "yet merged and should be merged manually "
13085 "if required before the histedit operation "
13086 "is continued");
13088 } else
13089 error = histedit_complete(worktree, fileindex, tmp_branch,
13090 branch, repo);
13091 done:
13092 free(cwd);
13093 free(committer);
13094 free(gitconfig_path);
13095 got_object_id_queue_free(&commits);
13096 histedit_free_list(&histedit_cmds);
13097 free(head_commit_id);
13098 free(base_commit_id);
13099 free(resume_commit_id);
13100 if (commit)
13101 got_object_commit_close(commit);
13102 if (branch)
13103 got_ref_close(branch);
13104 if (tmp_branch)
13105 got_ref_close(tmp_branch);
13106 if (worktree)
13107 got_worktree_close(worktree);
13108 if (repo) {
13109 const struct got_error *close_err = got_repo_close(repo);
13110 if (error == NULL)
13111 error = close_err;
13113 if (pack_fds) {
13114 const struct got_error *pack_err =
13115 got_repo_pack_fds_close(pack_fds);
13116 if (error == NULL)
13117 error = pack_err;
13119 return error;
13122 __dead static void
13123 usage_integrate(void)
13125 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13126 exit(1);
13129 static const struct got_error *
13130 cmd_integrate(int argc, char *argv[])
13132 const struct got_error *error = NULL;
13133 struct got_repository *repo = NULL;
13134 struct got_worktree *worktree = NULL;
13135 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13136 const char *branch_arg = NULL;
13137 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13138 struct got_fileindex *fileindex = NULL;
13139 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13140 int ch;
13141 struct got_update_progress_arg upa;
13142 int *pack_fds = NULL;
13144 #ifndef PROFILE
13145 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13146 "unveil", NULL) == -1)
13147 err(1, "pledge");
13148 #endif
13150 while ((ch = getopt(argc, argv, "")) != -1) {
13151 switch (ch) {
13152 default:
13153 usage_integrate();
13154 /* NOTREACHED */
13158 argc -= optind;
13159 argv += optind;
13161 if (argc != 1)
13162 usage_integrate();
13163 branch_arg = argv[0];
13165 cwd = getcwd(NULL, 0);
13166 if (cwd == NULL) {
13167 error = got_error_from_errno("getcwd");
13168 goto done;
13171 error = got_repo_pack_fds_open(&pack_fds);
13172 if (error != NULL)
13173 goto done;
13175 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13176 if (error) {
13177 if (error->code == GOT_ERR_NOT_WORKTREE)
13178 error = wrap_not_worktree_error(error, "integrate",
13179 cwd);
13180 goto done;
13183 error = check_rebase_or_histedit_in_progress(worktree);
13184 if (error)
13185 goto done;
13187 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13188 NULL, pack_fds);
13189 if (error != NULL)
13190 goto done;
13192 error = apply_unveil(got_repo_get_path(repo), 0,
13193 got_worktree_get_root_path(worktree));
13194 if (error)
13195 goto done;
13197 error = check_merge_in_progress(worktree, repo);
13198 if (error)
13199 goto done;
13201 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13202 error = got_error_from_errno("asprintf");
13203 goto done;
13206 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13207 &base_branch_ref, worktree, refname, repo);
13208 if (error)
13209 goto done;
13211 refname = strdup(got_ref_get_name(branch_ref));
13212 if (refname == NULL) {
13213 error = got_error_from_errno("strdup");
13214 got_worktree_integrate_abort(worktree, fileindex, repo,
13215 branch_ref, base_branch_ref);
13216 goto done;
13218 base_refname = strdup(got_ref_get_name(base_branch_ref));
13219 if (base_refname == NULL) {
13220 error = got_error_from_errno("strdup");
13221 got_worktree_integrate_abort(worktree, fileindex, repo,
13222 branch_ref, base_branch_ref);
13223 goto done;
13225 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13226 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13227 got_worktree_integrate_abort(worktree, fileindex, repo,
13228 branch_ref, base_branch_ref);
13229 goto done;
13232 error = got_ref_resolve(&commit_id, repo, branch_ref);
13233 if (error)
13234 goto done;
13236 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13237 if (error)
13238 goto done;
13240 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13241 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13242 "specified branch has already been integrated");
13243 got_worktree_integrate_abort(worktree, fileindex, repo,
13244 branch_ref, base_branch_ref);
13245 goto done;
13248 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13249 if (error) {
13250 if (error->code == GOT_ERR_ANCESTRY)
13251 error = got_error(GOT_ERR_REBASE_REQUIRED);
13252 got_worktree_integrate_abort(worktree, fileindex, repo,
13253 branch_ref, base_branch_ref);
13254 goto done;
13257 memset(&upa, 0, sizeof(upa));
13258 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13259 branch_ref, base_branch_ref, update_progress, &upa,
13260 check_cancelled, NULL);
13261 if (error)
13262 goto done;
13264 printf("Integrated %s into %s\n", refname, base_refname);
13265 print_update_progress_stats(&upa);
13266 done:
13267 if (repo) {
13268 const struct got_error *close_err = got_repo_close(repo);
13269 if (error == NULL)
13270 error = close_err;
13272 if (worktree)
13273 got_worktree_close(worktree);
13274 if (pack_fds) {
13275 const struct got_error *pack_err =
13276 got_repo_pack_fds_close(pack_fds);
13277 if (error == NULL)
13278 error = pack_err;
13280 free(cwd);
13281 free(base_commit_id);
13282 free(commit_id);
13283 free(refname);
13284 free(base_refname);
13285 return error;
13288 __dead static void
13289 usage_merge(void)
13291 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13292 exit(1);
13295 static const struct got_error *
13296 cmd_merge(int argc, char *argv[])
13298 const struct got_error *error = NULL;
13299 struct got_worktree *worktree = NULL;
13300 struct got_repository *repo = NULL;
13301 struct got_fileindex *fileindex = NULL;
13302 char *cwd = NULL, *id_str = NULL, *author = NULL;
13303 char *gitconfig_path = NULL;
13304 struct got_reference *branch = NULL, *wt_branch = NULL;
13305 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13306 struct got_object_id *wt_branch_tip = NULL;
13307 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13308 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13309 struct got_update_progress_arg upa;
13310 struct got_object_id *merge_commit_id = NULL;
13311 char *branch_name = NULL;
13312 int *pack_fds = NULL;
13314 memset(&upa, 0, sizeof(upa));
13316 #ifndef PROFILE
13317 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13318 "unveil", NULL) == -1)
13319 err(1, "pledge");
13320 #endif
13322 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13323 switch (ch) {
13324 case 'a':
13325 abort_merge = 1;
13326 break;
13327 case 'C':
13328 allow_conflict = 1;
13329 break;
13330 case 'c':
13331 continue_merge = 1;
13332 break;
13333 case 'M':
13334 prefer_fast_forward = 0;
13335 break;
13336 case 'n':
13337 interrupt_merge = 1;
13338 break;
13339 default:
13340 usage_merge();
13341 /* NOTREACHED */
13345 argc -= optind;
13346 argv += optind;
13348 if (abort_merge) {
13349 if (continue_merge)
13350 option_conflict('a', 'c');
13351 if (!prefer_fast_forward)
13352 option_conflict('a', 'M');
13353 if (interrupt_merge)
13354 option_conflict('a', 'n');
13355 } else if (continue_merge) {
13356 if (!prefer_fast_forward)
13357 option_conflict('c', 'M');
13358 if (interrupt_merge)
13359 option_conflict('c', 'n');
13361 if (allow_conflict) {
13362 if (!continue_merge)
13363 errx(1, "-C option requires -c");
13365 if (abort_merge || continue_merge) {
13366 if (argc != 0)
13367 usage_merge();
13368 } else if (argc != 1)
13369 usage_merge();
13371 cwd = getcwd(NULL, 0);
13372 if (cwd == NULL) {
13373 error = got_error_from_errno("getcwd");
13374 goto done;
13377 error = got_repo_pack_fds_open(&pack_fds);
13378 if (error != NULL)
13379 goto done;
13381 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13382 if (error) {
13383 if (error->code == GOT_ERR_NOT_WORKTREE)
13384 error = wrap_not_worktree_error(error,
13385 "merge", cwd);
13386 goto done;
13389 error = get_gitconfig_path(&gitconfig_path);
13390 if (error)
13391 goto done;
13392 error = got_repo_open(&repo,
13393 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13394 gitconfig_path, pack_fds);
13395 if (error != NULL)
13396 goto done;
13398 if (worktree != NULL) {
13399 error = worktree_has_logmsg_ref("merge", worktree, repo);
13400 if (error)
13401 goto done;
13404 error = apply_unveil(got_repo_get_path(repo), 0,
13405 worktree ? got_worktree_get_root_path(worktree) : NULL);
13406 if (error)
13407 goto done;
13409 error = check_rebase_or_histedit_in_progress(worktree);
13410 if (error)
13411 goto done;
13413 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13414 repo);
13415 if (error)
13416 goto done;
13418 if (merge_in_progress && !(abort_merge || continue_merge)) {
13419 error = got_error(GOT_ERR_MERGE_BUSY);
13420 goto done;
13423 if (!merge_in_progress && (abort_merge || continue_merge)) {
13424 error = got_error(GOT_ERR_NOT_MERGING);
13425 goto done;
13428 if (abort_merge) {
13429 error = got_worktree_merge_continue(&branch_name,
13430 &branch_tip, &fileindex, worktree, repo);
13431 if (error)
13432 goto done;
13433 error = got_worktree_merge_abort(worktree, fileindex, repo,
13434 abort_progress, &upa);
13435 if (error)
13436 goto done;
13437 printf("Merge of %s aborted\n", branch_name);
13438 goto done; /* nothing else to do */
13441 if (strncmp(got_worktree_get_head_ref_name(worktree),
13442 "refs/heads/", 11) != 0) {
13443 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13444 "work tree's current branch %s is outside the "
13445 "\"refs/heads/\" reference namespace; "
13446 "update -b required",
13447 got_worktree_get_head_ref_name(worktree));
13448 goto done;
13451 error = get_author(&author, repo, worktree);
13452 if (error)
13453 goto done;
13455 error = got_ref_open(&wt_branch, repo,
13456 got_worktree_get_head_ref_name(worktree), 0);
13457 if (error)
13458 goto done;
13459 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13460 if (error)
13461 goto done;
13463 if (continue_merge) {
13464 struct got_object_id *base_commit_id;
13465 base_commit_id = got_worktree_get_base_commit_id(worktree);
13466 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13467 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13468 goto done;
13470 error = got_worktree_merge_continue(&branch_name,
13471 &branch_tip, &fileindex, worktree, repo);
13472 if (error)
13473 goto done;
13474 } else {
13475 error = got_ref_open(&branch, repo, argv[0], 0);
13476 if (error != NULL)
13477 goto done;
13478 branch_name = strdup(got_ref_get_name(branch));
13479 if (branch_name == NULL) {
13480 error = got_error_from_errno("strdup");
13481 goto done;
13483 error = got_ref_resolve(&branch_tip, repo, branch);
13484 if (error)
13485 goto done;
13488 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13489 wt_branch_tip, branch_tip, 0, repo,
13490 check_cancelled, NULL);
13491 if (error && error->code != GOT_ERR_ANCESTRY)
13492 goto done;
13494 if (!continue_merge) {
13495 error = check_path_prefix(wt_branch_tip, branch_tip,
13496 got_worktree_get_path_prefix(worktree),
13497 GOT_ERR_MERGE_PATH, repo);
13498 if (error)
13499 goto done;
13500 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13501 if (error)
13502 goto done;
13503 if (prefer_fast_forward && yca_id &&
13504 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13505 struct got_pathlist_head paths;
13506 if (interrupt_merge) {
13507 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13508 "there are no changes to merge since %s "
13509 "is already based on %s; merge cannot be "
13510 "interrupted for amending; -n",
13511 branch_name, got_ref_get_name(wt_branch));
13512 goto done;
13514 printf("Forwarding %s to %s\n",
13515 got_ref_get_name(wt_branch), branch_name);
13516 error = got_ref_change_ref(wt_branch, branch_tip);
13517 if (error)
13518 goto done;
13519 error = got_ref_write(wt_branch, repo);
13520 if (error)
13521 goto done;
13522 error = got_worktree_set_base_commit_id(worktree, repo,
13523 branch_tip);
13524 if (error)
13525 goto done;
13526 TAILQ_INIT(&paths);
13527 error = got_pathlist_append(&paths, "", NULL);
13528 if (error)
13529 goto done;
13530 error = got_worktree_checkout_files(worktree,
13531 &paths, repo, update_progress, &upa,
13532 check_cancelled, NULL);
13533 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13534 if (error)
13535 goto done;
13536 if (upa.did_something) {
13537 char *id_str;
13538 error = got_object_id_str(&id_str, branch_tip);
13539 if (error)
13540 goto done;
13541 printf("Updated to commit %s\n", id_str);
13542 free(id_str);
13543 } else
13544 printf("Already up-to-date\n");
13545 print_update_progress_stats(&upa);
13546 goto done;
13548 error = got_worktree_merge_write_refs(worktree, branch, repo);
13549 if (error)
13550 goto done;
13552 error = got_worktree_merge_branch(worktree, fileindex,
13553 yca_id, branch_tip, repo, update_progress, &upa,
13554 check_cancelled, NULL);
13555 if (error)
13556 goto done;
13557 print_merge_progress_stats(&upa);
13558 if (!upa.did_something) {
13559 error = got_worktree_merge_abort(worktree, fileindex,
13560 repo, abort_progress, &upa);
13561 if (error)
13562 goto done;
13563 printf("Already up-to-date\n");
13564 goto done;
13568 if (interrupt_merge) {
13569 error = got_worktree_merge_postpone(worktree, fileindex);
13570 if (error)
13571 goto done;
13572 printf("Merge of %s interrupted on request\n", branch_name);
13573 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13574 upa.not_deleted > 0 || upa.unversioned > 0) {
13575 error = got_worktree_merge_postpone(worktree, fileindex);
13576 if (error)
13577 goto done;
13578 if (upa.conflicts > 0 && upa.missing == 0 &&
13579 upa.not_deleted == 0 && upa.unversioned == 0) {
13580 error = got_error_msg(GOT_ERR_CONFLICTS,
13581 "conflicts must be resolved before merging "
13582 "can continue");
13583 } else if (upa.conflicts > 0) {
13584 error = got_error_msg(GOT_ERR_CONFLICTS,
13585 "conflicts must be resolved before merging "
13586 "can continue; changes destined for some "
13587 "files were not yet merged and "
13588 "should be merged manually if required before the "
13589 "merge operation is continued");
13590 } else {
13591 error = got_error_msg(GOT_ERR_CONFLICTS,
13592 "changes destined for some "
13593 "files were not yet merged and should be "
13594 "merged manually if required before the "
13595 "merge operation is continued");
13597 goto done;
13598 } else {
13599 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13600 fileindex, author, NULL, 1, branch_tip, branch_name,
13601 allow_conflict, repo, continue_merge ? print_status : NULL,
13602 NULL);
13603 if (error)
13604 goto done;
13605 error = got_worktree_merge_complete(worktree, fileindex, repo);
13606 if (error)
13607 goto done;
13608 error = got_object_id_str(&id_str, merge_commit_id);
13609 if (error)
13610 goto done;
13611 printf("Merged %s into %s: %s\n", branch_name,
13612 got_worktree_get_head_ref_name(worktree),
13613 id_str);
13616 done:
13617 free(gitconfig_path);
13618 free(id_str);
13619 free(merge_commit_id);
13620 free(author);
13621 free(branch_tip);
13622 free(branch_name);
13623 free(yca_id);
13624 if (branch)
13625 got_ref_close(branch);
13626 if (wt_branch)
13627 got_ref_close(wt_branch);
13628 if (worktree)
13629 got_worktree_close(worktree);
13630 if (repo) {
13631 const struct got_error *close_err = got_repo_close(repo);
13632 if (error == NULL)
13633 error = close_err;
13635 if (pack_fds) {
13636 const struct got_error *pack_err =
13637 got_repo_pack_fds_close(pack_fds);
13638 if (error == NULL)
13639 error = pack_err;
13641 return error;
13644 __dead static void
13645 usage_stage(void)
13647 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13648 "[path ...]\n", getprogname());
13649 exit(1);
13652 static const struct got_error *
13653 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13654 const char *path, struct got_object_id *blob_id,
13655 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13656 int dirfd, const char *de_name)
13658 const struct got_error *err = NULL;
13659 char *id_str = NULL;
13661 if (staged_status != GOT_STATUS_ADD &&
13662 staged_status != GOT_STATUS_MODIFY &&
13663 staged_status != GOT_STATUS_DELETE)
13664 return NULL;
13666 if (staged_status == GOT_STATUS_ADD ||
13667 staged_status == GOT_STATUS_MODIFY)
13668 err = got_object_id_str(&id_str, staged_blob_id);
13669 else
13670 err = got_object_id_str(&id_str, blob_id);
13671 if (err)
13672 return err;
13674 printf("%s %c %s\n", id_str, staged_status, path);
13675 free(id_str);
13676 return NULL;
13679 static const struct got_error *
13680 cmd_stage(int argc, char *argv[])
13682 const struct got_error *error = NULL;
13683 struct got_repository *repo = NULL;
13684 struct got_worktree *worktree = NULL;
13685 char *cwd = NULL;
13686 struct got_pathlist_head paths;
13687 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13688 FILE *patch_script_file = NULL;
13689 const char *patch_script_path = NULL;
13690 struct choose_patch_arg cpa;
13691 int *pack_fds = NULL;
13693 TAILQ_INIT(&paths);
13695 #ifndef PROFILE
13696 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13697 "unveil", NULL) == -1)
13698 err(1, "pledge");
13699 #endif
13701 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13702 switch (ch) {
13703 case 'F':
13704 patch_script_path = optarg;
13705 break;
13706 case 'l':
13707 list_stage = 1;
13708 break;
13709 case 'p':
13710 pflag = 1;
13711 break;
13712 case 'S':
13713 allow_bad_symlinks = 1;
13714 break;
13715 default:
13716 usage_stage();
13717 /* NOTREACHED */
13721 argc -= optind;
13722 argv += optind;
13724 if (list_stage && (pflag || patch_script_path))
13725 errx(1, "-l option cannot be used with other options");
13726 if (patch_script_path && !pflag)
13727 errx(1, "-F option can only be used together with -p option");
13729 cwd = getcwd(NULL, 0);
13730 if (cwd == NULL) {
13731 error = got_error_from_errno("getcwd");
13732 goto done;
13735 error = got_repo_pack_fds_open(&pack_fds);
13736 if (error != NULL)
13737 goto done;
13739 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13740 if (error) {
13741 if (error->code == GOT_ERR_NOT_WORKTREE)
13742 error = wrap_not_worktree_error(error, "stage", cwd);
13743 goto done;
13746 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13747 NULL, pack_fds);
13748 if (error != NULL)
13749 goto done;
13751 if (patch_script_path) {
13752 patch_script_file = fopen(patch_script_path, "re");
13753 if (patch_script_file == NULL) {
13754 error = got_error_from_errno2("fopen",
13755 patch_script_path);
13756 goto done;
13759 error = apply_unveil(got_repo_get_path(repo), 0,
13760 got_worktree_get_root_path(worktree));
13761 if (error)
13762 goto done;
13764 error = check_merge_in_progress(worktree, repo);
13765 if (error)
13766 goto done;
13768 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13769 if (error)
13770 goto done;
13772 if (list_stage)
13773 error = got_worktree_status(worktree, &paths, repo, 0,
13774 print_stage, NULL, check_cancelled, NULL);
13775 else {
13776 cpa.patch_script_file = patch_script_file;
13777 cpa.action = "stage";
13778 error = got_worktree_stage(worktree, &paths,
13779 pflag ? NULL : print_status, NULL,
13780 pflag ? choose_patch : NULL, &cpa,
13781 allow_bad_symlinks, repo);
13783 done:
13784 if (patch_script_file && fclose(patch_script_file) == EOF &&
13785 error == NULL)
13786 error = got_error_from_errno2("fclose", patch_script_path);
13787 if (repo) {
13788 const struct got_error *close_err = got_repo_close(repo);
13789 if (error == NULL)
13790 error = close_err;
13792 if (worktree)
13793 got_worktree_close(worktree);
13794 if (pack_fds) {
13795 const struct got_error *pack_err =
13796 got_repo_pack_fds_close(pack_fds);
13797 if (error == NULL)
13798 error = pack_err;
13800 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13801 free(cwd);
13802 return error;
13805 __dead static void
13806 usage_unstage(void)
13808 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13809 "[path ...]\n", getprogname());
13810 exit(1);
13814 static const struct got_error *
13815 cmd_unstage(int argc, char *argv[])
13817 const struct got_error *error = NULL;
13818 struct got_repository *repo = NULL;
13819 struct got_worktree *worktree = NULL;
13820 char *cwd = NULL;
13821 struct got_pathlist_head paths;
13822 int ch, pflag = 0;
13823 struct got_update_progress_arg upa;
13824 FILE *patch_script_file = NULL;
13825 const char *patch_script_path = NULL;
13826 struct choose_patch_arg cpa;
13827 int *pack_fds = NULL;
13829 TAILQ_INIT(&paths);
13831 #ifndef PROFILE
13832 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13833 "unveil", NULL) == -1)
13834 err(1, "pledge");
13835 #endif
13837 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13838 switch (ch) {
13839 case 'F':
13840 patch_script_path = optarg;
13841 break;
13842 case 'p':
13843 pflag = 1;
13844 break;
13845 default:
13846 usage_unstage();
13847 /* NOTREACHED */
13851 argc -= optind;
13852 argv += optind;
13854 if (patch_script_path && !pflag)
13855 errx(1, "-F option can only be used together with -p option");
13857 cwd = getcwd(NULL, 0);
13858 if (cwd == NULL) {
13859 error = got_error_from_errno("getcwd");
13860 goto done;
13863 error = got_repo_pack_fds_open(&pack_fds);
13864 if (error != NULL)
13865 goto done;
13867 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13868 if (error) {
13869 if (error->code == GOT_ERR_NOT_WORKTREE)
13870 error = wrap_not_worktree_error(error, "unstage", cwd);
13871 goto done;
13874 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13875 NULL, pack_fds);
13876 if (error != NULL)
13877 goto done;
13879 if (patch_script_path) {
13880 patch_script_file = fopen(patch_script_path, "re");
13881 if (patch_script_file == NULL) {
13882 error = got_error_from_errno2("fopen",
13883 patch_script_path);
13884 goto done;
13888 error = apply_unveil(got_repo_get_path(repo), 0,
13889 got_worktree_get_root_path(worktree));
13890 if (error)
13891 goto done;
13893 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13894 if (error)
13895 goto done;
13897 cpa.patch_script_file = patch_script_file;
13898 cpa.action = "unstage";
13899 memset(&upa, 0, sizeof(upa));
13900 error = got_worktree_unstage(worktree, &paths, update_progress,
13901 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13902 if (!error)
13903 print_merge_progress_stats(&upa);
13904 done:
13905 if (patch_script_file && fclose(patch_script_file) == EOF &&
13906 error == NULL)
13907 error = got_error_from_errno2("fclose", patch_script_path);
13908 if (repo) {
13909 const struct got_error *close_err = got_repo_close(repo);
13910 if (error == NULL)
13911 error = close_err;
13913 if (worktree)
13914 got_worktree_close(worktree);
13915 if (pack_fds) {
13916 const struct got_error *pack_err =
13917 got_repo_pack_fds_close(pack_fds);
13918 if (error == NULL)
13919 error = pack_err;
13921 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13922 free(cwd);
13923 return error;
13926 __dead static void
13927 usage_cat(void)
13929 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13930 "arg ...\n", getprogname());
13931 exit(1);
13934 static const struct got_error *
13935 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13937 const struct got_error *err;
13938 struct got_blob_object *blob;
13939 int fd = -1;
13941 fd = got_opentempfd();
13942 if (fd == -1)
13943 return got_error_from_errno("got_opentempfd");
13945 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13946 if (err)
13947 goto done;
13949 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13950 done:
13951 if (fd != -1 && close(fd) == -1 && err == NULL)
13952 err = got_error_from_errno("close");
13953 if (blob)
13954 got_object_blob_close(blob);
13955 return err;
13958 static const struct got_error *
13959 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13961 const struct got_error *err;
13962 struct got_tree_object *tree;
13963 int nentries, i;
13965 err = got_object_open_as_tree(&tree, repo, id);
13966 if (err)
13967 return err;
13969 nentries = got_object_tree_get_nentries(tree);
13970 for (i = 0; i < nentries; i++) {
13971 struct got_tree_entry *te;
13972 char *id_str;
13973 if (sigint_received || sigpipe_received)
13974 break;
13975 te = got_object_tree_get_entry(tree, i);
13976 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13977 if (err)
13978 break;
13979 fprintf(outfile, "%s %.7o %s\n", id_str,
13980 got_tree_entry_get_mode(te),
13981 got_tree_entry_get_name(te));
13982 free(id_str);
13985 got_object_tree_close(tree);
13986 return err;
13989 static const struct got_error *
13990 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13992 const struct got_error *err;
13993 struct got_commit_object *commit;
13994 const struct got_object_id_queue *parent_ids;
13995 struct got_object_qid *pid;
13996 char *id_str = NULL;
13997 const char *logmsg = NULL;
13998 char gmtoff[6];
14000 err = got_object_open_as_commit(&commit, repo, id);
14001 if (err)
14002 return err;
14004 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14005 if (err)
14006 goto done;
14008 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14009 parent_ids = got_object_commit_get_parent_ids(commit);
14010 fprintf(outfile, "numparents %d\n",
14011 got_object_commit_get_nparents(commit));
14012 STAILQ_FOREACH(pid, parent_ids, entry) {
14013 char *pid_str;
14014 err = got_object_id_str(&pid_str, &pid->id);
14015 if (err)
14016 goto done;
14017 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14018 free(pid_str);
14020 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14021 got_object_commit_get_author_gmtoff(commit));
14022 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14023 got_object_commit_get_author(commit),
14024 (long long)got_object_commit_get_author_time(commit),
14025 gmtoff);
14027 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14028 got_object_commit_get_committer_gmtoff(commit));
14029 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14030 got_object_commit_get_committer(commit),
14031 (long long)got_object_commit_get_committer_time(commit),
14032 gmtoff);
14034 logmsg = got_object_commit_get_logmsg_raw(commit);
14035 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14036 fprintf(outfile, "%s", logmsg);
14037 done:
14038 free(id_str);
14039 got_object_commit_close(commit);
14040 return err;
14043 static const struct got_error *
14044 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14046 const struct got_error *err;
14047 struct got_tag_object *tag;
14048 char *id_str = NULL;
14049 const char *tagmsg = NULL;
14050 char gmtoff[6];
14052 err = got_object_open_as_tag(&tag, repo, id);
14053 if (err)
14054 return err;
14056 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14057 if (err)
14058 goto done;
14060 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14062 switch (got_object_tag_get_object_type(tag)) {
14063 case GOT_OBJ_TYPE_BLOB:
14064 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14065 GOT_OBJ_LABEL_BLOB);
14066 break;
14067 case GOT_OBJ_TYPE_TREE:
14068 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14069 GOT_OBJ_LABEL_TREE);
14070 break;
14071 case GOT_OBJ_TYPE_COMMIT:
14072 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14073 GOT_OBJ_LABEL_COMMIT);
14074 break;
14075 case GOT_OBJ_TYPE_TAG:
14076 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14077 GOT_OBJ_LABEL_TAG);
14078 break;
14079 default:
14080 break;
14083 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14084 got_object_tag_get_name(tag));
14086 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14087 got_object_tag_get_tagger_gmtoff(tag));
14088 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14089 got_object_tag_get_tagger(tag),
14090 (long long)got_object_tag_get_tagger_time(tag),
14091 gmtoff);
14093 tagmsg = got_object_tag_get_message(tag);
14094 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14095 fprintf(outfile, "%s", tagmsg);
14096 done:
14097 free(id_str);
14098 got_object_tag_close(tag);
14099 return err;
14102 static const struct got_error *
14103 cmd_cat(int argc, char *argv[])
14105 const struct got_error *error;
14106 struct got_repository *repo = NULL;
14107 struct got_worktree *worktree = NULL;
14108 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14109 char *keyword_idstr = NULL;
14110 const char *commit_id_str = NULL;
14111 struct got_object_id *id = NULL, *commit_id = NULL;
14112 struct got_commit_object *commit = NULL;
14113 int ch, obj_type, i, force_path = 0;
14114 struct got_reflist_head refs;
14115 int *pack_fds = NULL;
14117 TAILQ_INIT(&refs);
14119 #ifndef PROFILE
14120 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14121 NULL) == -1)
14122 err(1, "pledge");
14123 #endif
14125 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14126 switch (ch) {
14127 case 'c':
14128 commit_id_str = optarg;
14129 break;
14130 case 'P':
14131 force_path = 1;
14132 break;
14133 case 'r':
14134 repo_path = realpath(optarg, NULL);
14135 if (repo_path == NULL)
14136 return got_error_from_errno2("realpath",
14137 optarg);
14138 got_path_strip_trailing_slashes(repo_path);
14139 break;
14140 default:
14141 usage_cat();
14142 /* NOTREACHED */
14146 argc -= optind;
14147 argv += optind;
14149 cwd = getcwd(NULL, 0);
14150 if (cwd == NULL) {
14151 error = got_error_from_errno("getcwd");
14152 goto done;
14155 error = got_repo_pack_fds_open(&pack_fds);
14156 if (error != NULL)
14157 goto done;
14159 if (repo_path == NULL) {
14160 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14161 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14162 goto done;
14163 if (worktree) {
14164 repo_path = strdup(
14165 got_worktree_get_repo_path(worktree));
14166 if (repo_path == NULL) {
14167 error = got_error_from_errno("strdup");
14168 goto done;
14171 if (commit_id_str == NULL) {
14172 /* Release work tree lock. */
14173 got_worktree_close(worktree);
14174 worktree = NULL;
14179 if (repo_path == NULL) {
14180 repo_path = strdup(cwd);
14181 if (repo_path == NULL)
14182 return got_error_from_errno("strdup");
14185 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14186 free(repo_path);
14187 if (error != NULL)
14188 goto done;
14190 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14191 if (error)
14192 goto done;
14194 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14195 if (error)
14196 goto done;
14198 if (commit_id_str != NULL) {
14199 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14200 repo, worktree);
14201 if (error != NULL)
14202 goto done;
14203 if (keyword_idstr != NULL)
14204 commit_id_str = keyword_idstr;
14205 if (worktree != NULL) {
14206 got_worktree_close(worktree);
14207 worktree = NULL;
14209 } else
14210 commit_id_str = GOT_REF_HEAD;
14211 error = got_repo_match_object_id(&commit_id, NULL,
14212 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14213 if (error)
14214 goto done;
14216 error = got_object_open_as_commit(&commit, repo, commit_id);
14217 if (error)
14218 goto done;
14220 for (i = 0; i < argc; i++) {
14221 if (force_path) {
14222 error = got_object_id_by_path(&id, repo, commit,
14223 argv[i]);
14224 if (error)
14225 break;
14226 } else {
14227 error = got_repo_match_object_id(&id, &label, argv[i],
14228 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14229 repo);
14230 if (error) {
14231 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14232 error->code != GOT_ERR_NOT_REF)
14233 break;
14234 error = got_object_id_by_path(&id, repo,
14235 commit, argv[i]);
14236 if (error)
14237 break;
14241 error = got_object_get_type(&obj_type, repo, id);
14242 if (error)
14243 break;
14245 switch (obj_type) {
14246 case GOT_OBJ_TYPE_BLOB:
14247 error = cat_blob(id, repo, stdout);
14248 break;
14249 case GOT_OBJ_TYPE_TREE:
14250 error = cat_tree(id, repo, stdout);
14251 break;
14252 case GOT_OBJ_TYPE_COMMIT:
14253 error = cat_commit(id, repo, stdout);
14254 break;
14255 case GOT_OBJ_TYPE_TAG:
14256 error = cat_tag(id, repo, stdout);
14257 break;
14258 default:
14259 error = got_error(GOT_ERR_OBJ_TYPE);
14260 break;
14262 if (error)
14263 break;
14264 free(label);
14265 label = NULL;
14266 free(id);
14267 id = NULL;
14269 done:
14270 free(label);
14271 free(id);
14272 free(commit_id);
14273 free(keyword_idstr);
14274 if (commit)
14275 got_object_commit_close(commit);
14276 if (worktree)
14277 got_worktree_close(worktree);
14278 if (repo) {
14279 const struct got_error *close_err = got_repo_close(repo);
14280 if (error == NULL)
14281 error = close_err;
14283 if (pack_fds) {
14284 const struct got_error *pack_err =
14285 got_repo_pack_fds_close(pack_fds);
14286 if (error == NULL)
14287 error = pack_err;
14290 got_ref_list_free(&refs);
14291 return error;
14294 __dead static void
14295 usage_info(void)
14297 fprintf(stderr, "usage: %s info [path ...]\n",
14298 getprogname());
14299 exit(1);
14302 static const struct got_error *
14303 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14304 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14305 struct got_object_id *commit_id)
14307 const struct got_error *err = NULL;
14308 char *id_str = NULL;
14309 char datebuf[128];
14310 struct tm mytm, *tm;
14311 struct got_pathlist_head *paths = arg;
14312 struct got_pathlist_entry *pe;
14315 * Clear error indication from any of the path arguments which
14316 * would cause this file index entry to be displayed.
14318 TAILQ_FOREACH(pe, paths, entry) {
14319 if (got_path_cmp(path, pe->path, strlen(path),
14320 pe->path_len) == 0 ||
14321 got_path_is_child(path, pe->path, pe->path_len))
14322 pe->data = NULL; /* no error */
14325 printf(GOT_COMMIT_SEP_STR);
14326 if (S_ISLNK(mode))
14327 printf("symlink: %s\n", path);
14328 else if (S_ISREG(mode)) {
14329 printf("file: %s\n", path);
14330 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14331 } else if (S_ISDIR(mode))
14332 printf("directory: %s\n", path);
14333 else
14334 printf("something: %s\n", path);
14336 tm = localtime_r(&mtime, &mytm);
14337 if (tm == NULL)
14338 return NULL;
14339 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14340 return got_error(GOT_ERR_NO_SPACE);
14341 printf("timestamp: %s\n", datebuf);
14343 if (blob_id) {
14344 err = got_object_id_str(&id_str, blob_id);
14345 if (err)
14346 return err;
14347 printf("based on blob: %s\n", id_str);
14348 free(id_str);
14351 if (staged_blob_id) {
14352 err = got_object_id_str(&id_str, staged_blob_id);
14353 if (err)
14354 return err;
14355 printf("based on staged blob: %s\n", id_str);
14356 free(id_str);
14359 if (commit_id) {
14360 err = got_object_id_str(&id_str, commit_id);
14361 if (err)
14362 return err;
14363 printf("based on commit: %s\n", id_str);
14364 free(id_str);
14367 return NULL;
14370 static const struct got_error *
14371 cmd_info(int argc, char *argv[])
14373 const struct got_error *error = NULL;
14374 struct got_worktree *worktree = NULL;
14375 char *cwd = NULL, *id_str = NULL;
14376 struct got_pathlist_head paths;
14377 char *uuidstr = NULL;
14378 int ch, show_files = 0;
14380 TAILQ_INIT(&paths);
14382 #ifndef PROFILE
14383 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14384 NULL) == -1)
14385 err(1, "pledge");
14386 #endif
14388 while ((ch = getopt(argc, argv, "")) != -1) {
14389 switch (ch) {
14390 default:
14391 usage_info();
14392 /* NOTREACHED */
14396 argc -= optind;
14397 argv += optind;
14399 cwd = getcwd(NULL, 0);
14400 if (cwd == NULL) {
14401 error = got_error_from_errno("getcwd");
14402 goto done;
14405 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14406 if (error) {
14407 if (error->code == GOT_ERR_NOT_WORKTREE)
14408 error = wrap_not_worktree_error(error, "info", cwd);
14409 goto done;
14412 #ifndef PROFILE
14413 /* Remove "wpath cpath proc exec sendfd" promises. */
14414 if (pledge("stdio rpath flock unveil", NULL) == -1)
14415 err(1, "pledge");
14416 #endif
14417 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14418 if (error)
14419 goto done;
14421 if (argc >= 1) {
14422 error = get_worktree_paths_from_argv(&paths, argc, argv,
14423 worktree);
14424 if (error)
14425 goto done;
14426 show_files = 1;
14429 error = got_object_id_str(&id_str,
14430 got_worktree_get_base_commit_id(worktree));
14431 if (error)
14432 goto done;
14434 error = got_worktree_get_uuid(&uuidstr, worktree);
14435 if (error)
14436 goto done;
14438 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14439 printf("work tree base commit: %s\n", id_str);
14440 printf("work tree path prefix: %s\n",
14441 got_worktree_get_path_prefix(worktree));
14442 printf("work tree branch reference: %s\n",
14443 got_worktree_get_head_ref_name(worktree));
14444 printf("work tree UUID: %s\n", uuidstr);
14445 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14447 if (show_files) {
14448 struct got_pathlist_entry *pe;
14449 TAILQ_FOREACH(pe, &paths, entry) {
14450 if (pe->path_len == 0)
14451 continue;
14453 * Assume this path will fail. This will be corrected
14454 * in print_path_info() in case the path does suceeed.
14456 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14458 error = got_worktree_path_info(worktree, &paths,
14459 print_path_info, &paths, check_cancelled, NULL);
14460 if (error)
14461 goto done;
14462 TAILQ_FOREACH(pe, &paths, entry) {
14463 if (pe->data != NULL) {
14464 const struct got_error *perr;
14466 perr = pe->data;
14467 error = got_error_fmt(perr->code, "%s",
14468 pe->path);
14469 break;
14473 done:
14474 if (worktree)
14475 got_worktree_close(worktree);
14476 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14477 free(cwd);
14478 free(id_str);
14479 free(uuidstr);
14480 return error;