Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fflush(stdout);
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/usr/bin/vi");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_import(void)
352 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
353 "[-r repository-path] directory\n", getprogname());
354 exit(1);
357 static int
358 spawn_editor(const char *editor, const char *file)
360 pid_t pid;
361 sig_t sighup, sigint, sigquit;
362 int st = -1;
364 sighup = signal(SIGHUP, SIG_IGN);
365 sigint = signal(SIGINT, SIG_IGN);
366 sigquit = signal(SIGQUIT, SIG_IGN);
368 switch (pid = fork()) {
369 case -1:
370 goto doneediting;
371 case 0:
372 execl(editor, editor, file, (char *)NULL);
373 _exit(127);
376 while (waitpid(pid, &st, 0) == -1)
377 if (errno != EINTR)
378 break;
380 doneediting:
381 (void)signal(SIGHUP, sighup);
382 (void)signal(SIGINT, sigint);
383 (void)signal(SIGQUIT, sigquit);
385 if (!WIFEXITED(st)) {
386 errno = EINTR;
387 return -1;
390 return WEXITSTATUS(st);
393 static const struct got_error *
394 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
400 *logmsg = NULL;
401 *len = 0;
403 if (fseeko(fp, 0L, SEEK_SET) == -1)
404 return got_error_from_errno("fseeko");
406 *logmsg = malloc(filesize + 1);
407 if (*logmsg == NULL)
408 return got_error_from_errno("malloc");
409 (*logmsg)[0] = '\0';
411 while (getline(&line, &linesize, fp) != -1) {
412 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t logmsg_len;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (require_modification) {
458 struct timespec timeout;
460 timeout.tv_sec = 0;
461 timeout.tv_nsec = 1;
462 nanosleep(&timeout, NULL);
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno2("stat", logmsg_path);
468 if (require_modification && st.st_size == st2.st_size &&
469 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 fp = fopen(logmsg_path, "re");
474 if (fp == NULL) {
475 err = got_error_from_errno("fopen");
476 goto done;
479 /* strip comments and leading/trailing newlines */
480 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
481 if (err)
482 goto done;
483 if (logmsg_len == 0) {
484 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
485 "commit message cannot be empty, aborting");
486 goto done;
488 done:
489 if (fp && fclose(fp) == EOF && err == NULL)
490 err = got_error_from_errno("fclose");
491 if (err) {
492 free(*logmsg);
493 *logmsg = NULL;
495 return err;
498 static const struct got_error *
499 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
500 const char *path_dir, const char *branch_name)
502 char *initial_content = NULL;
503 const struct got_error *err = NULL;
504 int initial_content_len;
505 int fd = -1;
507 initial_content_len = asprintf(&initial_content,
508 "\n# %s to be imported to branch %s\n", path_dir,
509 branch_name);
510 if (initial_content_len == -1)
511 return got_error_from_errno("asprintf");
513 err = got_opentemp_named_fd(logmsg_path, &fd,
514 GOT_TMPDIR_STR "/got-importmsg", "");
515 if (err)
516 goto done;
518 if (write(fd, initial_content, initial_content_len) == -1) {
519 err = got_error_from_errno2("write", *logmsg_path);
520 goto done;
522 if (close(fd) == -1) {
523 err = got_error_from_errno2("close", *logmsg_path);
524 goto done;
526 fd = -1;
528 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
529 initial_content_len, 1);
530 done:
531 if (fd != -1 && close(fd) == -1 && err == NULL)
532 err = got_error_from_errno2("close", *logmsg_path);
533 free(initial_content);
534 if (err) {
535 free(*logmsg_path);
536 *logmsg_path = NULL;
538 return err;
541 static const struct got_error *
542 import_progress(void *arg, const char *path)
544 printf("A %s\n", path);
545 return NULL;
548 static const struct got_error *
549 valid_author(const char *author)
551 const char *email = author;
553 /*
554 * Git' expects the author (or committer) to be in the form
555 * "name <email>", which are mostly free form (see the
556 * "committer" description in git-fast-import(1)). We're only
557 * doing this to avoid git's object parser breaking on commits
558 * we create.
559 */
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (author != email && *author == '<' && *(author - 1) != ' ')
564 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
565 "between author name and email required", email);
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const char *
711 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 if (worktree)
717 worktree_conf = got_worktree_get_gotconfig(worktree);
718 repo_conf = got_repo_get_gotconfig(repo);
720 /*
721 * Priority of potential author information sources, from most
722 * significant to least significant:
723 * 1) work tree's .got/got.conf file
724 * 2) repository's got.conf file
725 */
727 if (worktree_conf)
728 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
729 if (got_signer_id == NULL)
730 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
732 return got_signer_id;
735 static const struct got_error *
736 get_gitconfig_path(char **gitconfig_path)
738 const char *homedir = getenv("HOME");
740 *gitconfig_path = NULL;
741 if (homedir) {
742 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
743 return got_error_from_errno("asprintf");
746 return NULL;
749 static const struct got_error *
750 cmd_import(int argc, char *argv[])
752 const struct got_error *error = NULL;
753 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
754 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
755 const char *branch_name = NULL;
756 char *id_str = NULL, *logmsg_path = NULL;
757 char refname[PATH_MAX] = "refs/heads/";
758 struct got_repository *repo = NULL;
759 struct got_reference *branch_ref = NULL, *head_ref = NULL;
760 struct got_object_id *new_commit_id = NULL;
761 int ch, n = 0;
762 struct got_pathlist_head ignores;
763 struct got_pathlist_entry *pe;
764 int preserve_logmsg = 0;
765 int *pack_fds = NULL;
767 TAILQ_INIT(&ignores);
769 #ifndef PROFILE
770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
771 "unveil",
772 NULL) == -1)
773 err(1, "pledge");
774 #endif
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 if (argc != 1)
814 usage_import();
816 if (repo_path == NULL) {
817 repo_path = getcwd(NULL, 0);
818 if (repo_path == NULL)
819 return got_error_from_errno("getcwd");
821 got_path_strip_trailing_slashes(repo_path);
822 error = get_gitconfig_path(&gitconfig_path);
823 if (error)
824 goto done;
825 error = got_repo_pack_fds_open(&pack_fds);
826 if (error != NULL)
827 goto done;
828 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
829 if (error)
830 goto done;
832 error = get_author(&author, repo, NULL);
833 if (error)
834 return error;
836 /*
837 * Don't let the user create a branch name with a leading '-'.
838 * While technically a valid reference name, this case is usually
839 * an unintended typo.
840 */
841 if (branch_name && branch_name[0] == '-')
842 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
844 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
845 if (error && error->code != GOT_ERR_NOT_REF)
846 goto done;
848 if (branch_name)
849 n = strlcat(refname, branch_name, sizeof(refname));
850 else if (head_ref && got_ref_is_symbolic(head_ref))
851 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
852 sizeof(refname));
853 else
854 n = strlcat(refname, "main", sizeof(refname));
855 if (n >= sizeof(refname)) {
856 error = got_error(GOT_ERR_NO_SPACE);
857 goto done;
860 error = got_ref_open(&branch_ref, repo, refname, 0);
861 if (error) {
862 if (error->code != GOT_ERR_NOT_REF)
863 goto done;
864 } else {
865 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
866 "import target branch already exists");
867 goto done;
870 path_dir = realpath(argv[0], NULL);
871 if (path_dir == NULL) {
872 error = got_error_from_errno2("realpath", argv[0]);
873 goto done;
875 got_path_strip_trailing_slashes(path_dir);
877 /*
878 * unveil(2) traverses exec(2); if an editor is used we have
879 * to apply unveil after the log message has been written.
880 */
881 if (logmsg == NULL || *logmsg == '\0') {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes, *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 struct got_pathlist_entry *pe;
2298 struct got_reflist_head remote_refs;
2299 struct got_reflist_entry *re;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL, have_bflag = 0;
2307 const char *remote_head = NULL, *worktree_branch = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&remote_refs);
2312 TAILQ_INIT(&wanted_branches);
2313 TAILQ_INIT(&wanted_refs);
2315 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2316 switch (ch) {
2317 case 'a':
2318 fetch_all_branches = 1;
2319 break;
2320 case 'b':
2321 error = got_pathlist_append(&wanted_branches,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 have_bflag = 1;
2326 break;
2327 case 'd':
2328 delete_refs = 1;
2329 break;
2330 case 'l':
2331 list_refs_only = 1;
2332 break;
2333 case 'q':
2334 verbosity = -1;
2335 break;
2336 case 'R':
2337 error = got_pathlist_append(&wanted_refs,
2338 optarg, NULL);
2339 if (error)
2340 return error;
2341 break;
2342 case 'r':
2343 repo_path = realpath(optarg, NULL);
2344 if (repo_path == NULL)
2345 return got_error_from_errno2("realpath",
2346 optarg);
2347 got_path_strip_trailing_slashes(repo_path);
2348 break;
2349 case 't':
2350 replace_tags = 1;
2351 break;
2352 case 'v':
2353 if (verbosity < 0)
2354 verbosity = 0;
2355 else if (verbosity < 3)
2356 verbosity++;
2357 break;
2358 case 'X':
2359 delete_remote = 1;
2360 break;
2361 default:
2362 usage_fetch();
2363 break;
2366 argc -= optind;
2367 argv += optind;
2369 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('a', 'b');
2371 if (list_refs_only) {
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('l', 'b');
2374 if (fetch_all_branches)
2375 option_conflict('l', 'a');
2376 if (delete_refs)
2377 option_conflict('l', 'd');
2378 if (delete_remote)
2379 option_conflict('l', 'X');
2381 if (delete_remote) {
2382 if (fetch_all_branches)
2383 option_conflict('X', 'a');
2384 if (!TAILQ_EMPTY(&wanted_branches))
2385 option_conflict('X', 'b');
2386 if (delete_refs)
2387 option_conflict('X', 'd');
2388 if (replace_tags)
2389 option_conflict('X', 't');
2390 if (!TAILQ_EMPTY(&wanted_refs))
2391 option_conflict('X', 'R');
2394 if (argc == 0) {
2395 if (delete_remote)
2396 errx(1, "-X option requires a remote name");
2397 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2398 } else if (argc == 1)
2399 remote_name = argv[0];
2400 else
2401 usage_fetch();
2403 cwd = getcwd(NULL, 0);
2404 if (cwd == NULL) {
2405 error = got_error_from_errno("getcwd");
2406 goto done;
2409 error = got_repo_pack_fds_open(&pack_fds);
2410 if (error != NULL)
2411 goto done;
2413 if (repo_path == NULL) {
2414 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2416 goto done;
2417 else
2418 error = NULL;
2419 if (worktree) {
2420 repo_path =
2421 strdup(got_worktree_get_repo_path(worktree));
2422 if (repo_path == NULL)
2423 error = got_error_from_errno("strdup");
2424 if (error)
2425 goto done;
2426 } else {
2427 repo_path = strdup(cwd);
2428 if (repo_path == NULL) {
2429 error = got_error_from_errno("strdup");
2430 goto done;
2435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2436 if (error)
2437 goto done;
2439 if (delete_remote) {
2440 error = delete_refs_for_remote(repo, remote_name);
2441 goto done; /* nothing else to do */
2444 if (worktree) {
2445 worktree_conf = got_worktree_get_gotconfig(worktree);
2446 if (worktree_conf) {
2447 got_gotconfig_get_remotes(&nremotes, &remotes,
2448 worktree_conf);
2449 for (i = 0; i < nremotes; i++) {
2450 if (strcmp(remotes[i].name, remote_name) == 0) {
2451 remote = &remotes[i];
2452 break;
2457 if (remote == NULL) {
2458 repo_conf = got_repo_get_gotconfig(repo);
2459 if (repo_conf) {
2460 got_gotconfig_get_remotes(&nremotes, &remotes,
2461 repo_conf);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2470 if (remote == NULL) {
2471 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 remote = &remotes[i];
2475 break;
2479 if (remote == NULL) {
2480 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_branches)) {
2485 if (!fetch_all_branches)
2486 fetch_all_branches = remote->fetch_all_branches;
2487 for (i = 0; i < remote->nfetch_branches; i++) {
2488 error = got_pathlist_append(&wanted_branches,
2489 remote->fetch_branches[i], NULL);
2490 if (error)
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_refs)) {
2495 for (i = 0; i < remote->nfetch_refs; i++) {
2496 error = got_pathlist_append(&wanted_refs,
2497 remote->fetch_refs[i], NULL);
2498 if (error)
2499 goto done;
2503 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2504 &repo_name, remote->fetch_url);
2505 if (error)
2506 goto done;
2508 if (strcmp(proto, "git") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd dns inet unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "git+ssh") == 0 ||
2515 strcmp(proto, "ssh") == 0) {
2516 #ifndef PROFILE
2517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2518 "sendfd unveil", NULL) == -1)
2519 err(1, "pledge");
2520 #endif
2521 } else if (strcmp(proto, "http") == 0 ||
2522 strcmp(proto, "git+http") == 0) {
2523 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2524 goto done;
2525 } else {
2526 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2527 goto done;
2530 error = got_dial_apply_unveil(proto);
2531 if (error)
2532 goto done;
2534 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2535 if (error)
2536 goto done;
2538 if (verbosity >= 0) {
2539 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2540 remote->name, proto, host,
2541 port ? ":" : "", port ? port : "",
2542 *server_path == '/' ? "" : "/", server_path);
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 if (!have_bflag) {
2552 * If set, get this remote's HEAD ref target so
2553 * if it has changed on the server we can fetch it.
2555 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2556 got_ref_cmp_by_name, repo);
2557 if (error)
2558 goto done;
2560 TAILQ_FOREACH(re, &remote_refs, entry) {
2561 const char *remote_refname, *remote_target;
2562 size_t remote_name_len;
2564 if (!got_ref_is_symbolic(re->ref))
2565 continue;
2567 remote_name_len = strlen(remote->name);
2568 remote_refname = got_ref_get_name(re->ref);
2570 /* we only want refs/remotes/$remote->name/HEAD */
2571 if (strncmp(remote_refname + 13, remote->name,
2572 remote_name_len) != 0)
2573 continue;
2575 if (strcmp(remote_refname + remote_name_len + 14,
2576 GOT_REF_HEAD) != 0)
2577 continue;
2580 * Take the name itself because we already
2581 * only match with refs/heads/ in fetch_pack().
2583 remote_target = got_ref_get_symref_target(re->ref);
2584 remote_head = remote_target + remote_name_len + 14;
2585 break;
2588 if (worktree) {
2589 const char *refname;
2591 refname = got_worktree_get_head_ref_name(worktree);
2592 if (strncmp(refname, "refs/heads/", 11) == 0)
2593 worktree_branch = refname;
2597 fpa.last_scaled_size[0] = '\0';
2598 fpa.last_p_indexed = -1;
2599 fpa.last_p_resolved = -1;
2600 fpa.verbosity = verbosity;
2601 fpa.repo = repo;
2602 fpa.create_configs = 0;
2603 fpa.configs_created = 0;
2604 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2606 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2607 remote->mirror_references, fetch_all_branches, &wanted_branches,
2608 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2609 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2610 if (error)
2611 goto done;
2613 if (list_refs_only) {
2614 error = list_remote_refs(&symrefs, &refs);
2615 goto done;
2618 if (pack_hash == NULL) {
2619 if (verbosity >= 0)
2620 printf("Already up-to-date\n");
2621 } else if (verbosity >= 0) {
2622 error = got_object_id_str(&id_str, pack_hash);
2623 if (error)
2624 goto done;
2625 printf("\nFetched %s.pack\n", id_str);
2626 free(id_str);
2627 id_str = NULL;
2630 /* Update references provided with the pack file. */
2631 TAILQ_FOREACH(pe, &refs, entry) {
2632 const char *refname = pe->path;
2633 struct got_object_id *id = pe->data;
2634 struct got_reference *ref;
2635 char *remote_refname;
2637 if (is_wanted_ref(&wanted_refs, refname) &&
2638 !remote->mirror_references) {
2639 error = update_wanted_ref(refname, id,
2640 remote->name, verbosity, repo);
2641 if (error)
2642 goto done;
2643 continue;
2646 if (remote->mirror_references ||
2647 strncmp("refs/tags/", refname, 10) == 0) {
2648 error = got_ref_open(&ref, repo, refname, 1);
2649 if (error) {
2650 if (error->code != GOT_ERR_NOT_REF)
2651 goto done;
2652 error = create_ref(refname, id, verbosity,
2653 repo);
2654 if (error)
2655 goto done;
2656 } else {
2657 error = update_ref(ref, id, replace_tags,
2658 verbosity, repo);
2659 unlock_err = got_ref_unlock(ref);
2660 if (unlock_err && error == NULL)
2661 error = unlock_err;
2662 got_ref_close(ref);
2663 if (error)
2664 goto done;
2666 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2667 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2668 remote_name, refname + 11) == -1) {
2669 error = got_error_from_errno("asprintf");
2670 goto done;
2673 error = got_ref_open(&ref, repo, remote_refname, 1);
2674 if (error) {
2675 if (error->code != GOT_ERR_NOT_REF)
2676 goto done;
2677 error = create_ref(remote_refname, id,
2678 verbosity, repo);
2679 if (error)
2680 goto done;
2681 } else {
2682 error = update_ref(ref, id, replace_tags,
2683 verbosity, repo);
2684 unlock_err = got_ref_unlock(ref);
2685 if (unlock_err && error == NULL)
2686 error = unlock_err;
2687 got_ref_close(ref);
2688 if (error)
2689 goto done;
2692 /* Also create a local branch if none exists yet. */
2693 error = got_ref_open(&ref, repo, refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(refname, id, verbosity,
2698 repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2709 if (delete_refs) {
2710 error = delete_missing_refs(&refs, &symrefs, remote,
2711 verbosity, repo);
2712 if (error)
2713 goto done;
2716 if (!remote->mirror_references) {
2717 /* Update remote HEAD reference if the server provided one. */
2718 TAILQ_FOREACH(pe, &symrefs, entry) {
2719 struct got_reference *target_ref;
2720 const char *refname = pe->path;
2721 const char *target = pe->data;
2722 char *remote_refname = NULL, *remote_target = NULL;
2724 if (strcmp(refname, GOT_REF_HEAD) != 0)
2725 continue;
2727 if (strncmp("refs/heads/", target, 11) != 0)
2728 continue;
2730 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2731 remote->name, refname) == -1) {
2732 error = got_error_from_errno("asprintf");
2733 goto done;
2735 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2736 remote->name, target + 11) == -1) {
2737 error = got_error_from_errno("asprintf");
2738 free(remote_refname);
2739 goto done;
2742 error = got_ref_open(&target_ref, repo, remote_target,
2743 0);
2744 if (error) {
2745 free(remote_refname);
2746 free(remote_target);
2747 if (error->code == GOT_ERR_NOT_REF) {
2748 error = NULL;
2749 continue;
2751 goto done;
2753 error = update_symref(remote_refname, target_ref,
2754 verbosity, repo);
2755 free(remote_refname);
2756 free(remote_target);
2757 got_ref_close(target_ref);
2758 if (error)
2759 goto done;
2762 done:
2763 if (fetchpid > 0) {
2764 if (kill(fetchpid, SIGTERM) == -1)
2765 error = got_error_from_errno("kill");
2766 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2767 error = got_error_from_errno("waitpid");
2769 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2770 error = got_error_from_errno("close");
2771 if (repo) {
2772 const struct got_error *close_err = got_repo_close(repo);
2773 if (error == NULL)
2774 error = close_err;
2776 if (worktree)
2777 got_worktree_close(worktree);
2778 if (pack_fds) {
2779 const struct got_error *pack_err =
2780 got_repo_pack_fds_close(pack_fds);
2781 if (error == NULL)
2782 error = pack_err;
2784 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2787 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2788 got_ref_list_free(&remote_refs);
2789 free(id_str);
2790 free(cwd);
2791 free(repo_path);
2792 free(pack_hash);
2793 free(proto);
2794 free(host);
2795 free(port);
2796 free(server_path);
2797 free(repo_name);
2798 return error;
2802 __dead static void
2803 usage_checkout(void)
2805 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2806 "[-p path-prefix] repository-path [work-tree-path]\n",
2807 getprogname());
2808 exit(1);
2811 static void
2812 show_worktree_base_ref_warning(void)
2814 fprintf(stderr, "%s: warning: could not create a reference "
2815 "to the work tree's base commit; the commit could be "
2816 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2817 "repository writable and running 'got update' will prevent this\n",
2818 getprogname());
2821 struct got_checkout_progress_arg {
2822 const char *worktree_path;
2823 int had_base_commit_ref_error;
2824 int verbosity;
2827 static const struct got_error *
2828 checkout_progress(void *arg, unsigned char status, const char *path)
2830 struct got_checkout_progress_arg *a = arg;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_BASE_REF_ERR) {
2837 a->had_base_commit_ref_error = 1;
2838 return NULL;
2841 while (path[0] == '/')
2842 path++;
2844 if (a->verbosity >= 0)
2845 printf("%c %s/%s\n", status, a->worktree_path, path);
2847 return NULL;
2850 static const struct got_error *
2851 check_cancelled(void *arg)
2853 if (sigint_received || sigpipe_received)
2854 return got_error(GOT_ERR_CANCELLED);
2855 return NULL;
2858 static const struct got_error *
2859 check_linear_ancestry(struct got_object_id *commit_id,
2860 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2861 struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct got_object_id *yca_id;
2866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2867 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2868 if (err)
2869 return err;
2871 if (yca_id == NULL)
2872 return got_error(GOT_ERR_ANCESTRY);
2875 * Require a straight line of history between the target commit
2876 * and the work tree's base commit.
2878 * Non-linear situations such as this require a rebase:
2880 * (commit) D F (base_commit)
2881 * \ /
2882 * C E
2883 * \ /
2884 * B (yca)
2885 * |
2886 * A
2888 * 'got update' only handles linear cases:
2889 * Update forwards in time: A (base/yca) - B - C - D (commit)
2890 * Update backwards in time: D (base) - C - B - A (commit/yca)
2892 if (allow_forwards_in_time_only) {
2893 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2894 return got_error(GOT_ERR_ANCESTRY);
2895 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2896 got_object_id_cmp(base_commit_id, yca_id) != 0)
2897 return got_error(GOT_ERR_ANCESTRY);
2899 free(yca_id);
2900 return NULL;
2903 static const struct got_error *
2904 check_same_branch(struct got_object_id *commit_id,
2905 struct got_reference *head_ref, struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2911 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2912 if (err)
2913 goto done;
2915 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2916 goto done;
2918 err = got_commit_graph_open(&graph, "/", 1);
2919 if (err)
2920 goto done;
2922 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2923 check_cancelled, NULL);
2924 if (err)
2925 goto done;
2927 for (;;) {
2928 struct got_object_id id;
2930 err = got_commit_graph_iter_next(&id, graph, repo,
2931 check_cancelled, NULL);
2932 if (err) {
2933 if (err->code == GOT_ERR_ITER_COMPLETED)
2934 err = got_error(GOT_ERR_ANCESTRY);
2935 break;
2938 if (got_object_id_cmp(&id, commit_id) == 0)
2939 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL, *keyword_idstr = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 #ifndef PROFILE
2994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2995 "unveil", NULL) == -1)
2996 err(1, "pledge");
2997 #endif
2999 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3000 switch (ch) {
3001 case 'b':
3002 branch_name = optarg;
3003 break;
3004 case 'c':
3005 commit_id_str = strdup(optarg);
3006 if (commit_id_str == NULL)
3007 return got_error_from_errno("strdup");
3008 break;
3009 case 'E':
3010 allow_nonempty = 1;
3011 break;
3012 case 'p':
3013 path_prefix = optarg;
3014 break;
3015 case 'q':
3016 verbosity = -1;
3017 break;
3018 default:
3019 usage_checkout();
3020 /* NOTREACHED */
3024 argc -= optind;
3025 argv += optind;
3027 if (argc == 1) {
3028 char *base, *dotgit;
3029 const char *path;
3030 repo_path = realpath(argv[0], NULL);
3031 if (repo_path == NULL)
3032 return got_error_from_errno2("realpath", argv[0]);
3033 cwd = getcwd(NULL, 0);
3034 if (cwd == NULL) {
3035 error = got_error_from_errno("getcwd");
3036 goto done;
3038 if (path_prefix[0])
3039 path = path_prefix;
3040 else
3041 path = repo_path;
3042 error = got_path_basename(&base, path);
3043 if (error)
3044 goto done;
3045 dotgit = strstr(base, ".git");
3046 if (dotgit)
3047 *dotgit = '\0';
3048 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3049 error = got_error_from_errno("asprintf");
3050 free(base);
3051 goto done;
3053 free(base);
3054 } else if (argc == 2) {
3055 repo_path = realpath(argv[0], NULL);
3056 if (repo_path == NULL) {
3057 error = got_error_from_errno2("realpath", argv[0]);
3058 goto done;
3060 worktree_path = realpath(argv[1], NULL);
3061 if (worktree_path == NULL) {
3062 if (errno != ENOENT) {
3063 error = got_error_from_errno2("realpath",
3064 argv[1]);
3065 goto done;
3067 worktree_path = strdup(argv[1]);
3068 if (worktree_path == NULL) {
3069 error = got_error_from_errno("strdup");
3070 goto done;
3073 } else
3074 usage_checkout();
3076 got_path_strip_trailing_slashes(repo_path);
3077 got_path_strip_trailing_slashes(worktree_path);
3079 error = got_repo_pack_fds_open(&pack_fds);
3080 if (error != NULL)
3081 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 /* Pre-create work tree path for unveil(2) */
3088 error = got_path_mkdir(worktree_path);
3089 if (error) {
3090 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3091 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3092 goto done;
3093 if (!allow_nonempty &&
3094 !got_path_dir_is_empty(worktree_path)) {
3095 error = got_error_path(worktree_path,
3096 GOT_ERR_DIR_NOT_EMPTY);
3097 goto done;
3101 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3102 if (error)
3103 goto done;
3105 error = got_ref_open(&head_ref, repo, branch_name, 0);
3106 if (error != NULL)
3107 goto done;
3109 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3110 GOT_WORKTREE_GOT_DIR, repo);
3111 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3112 goto done;
3114 error = got_worktree_open(&worktree, worktree_path,
3115 GOT_WORKTREE_GOT_DIR);
3116 if (error != NULL)
3117 goto done;
3119 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3120 path_prefix);
3121 if (error != NULL)
3122 goto done;
3123 if (!same_path_prefix) {
3124 error = got_error(GOT_ERR_PATH_PREFIX);
3125 goto done;
3128 if (commit_id_str) {
3129 struct got_reflist_head refs;
3130 TAILQ_INIT(&refs);
3131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3132 NULL);
3133 if (error)
3134 goto done;
3136 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3137 repo, worktree);
3138 if (error != NULL)
3139 goto done;
3140 if (keyword_idstr != NULL) {
3141 free(commit_id_str);
3142 commit_id_str = keyword_idstr;
3145 error = got_repo_match_object_id(&commit_id, NULL,
3146 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3147 got_ref_list_free(&refs);
3148 if (error)
3149 goto done;
3150 error = check_linear_ancestry(commit_id,
3151 got_worktree_get_base_commit_id(worktree), 0, repo);
3152 if (error != NULL) {
3153 if (error->code == GOT_ERR_ANCESTRY) {
3154 error = checkout_ancestry_error(
3155 head_ref, commit_id_str);
3157 goto done;
3159 error = check_same_branch(commit_id, head_ref, repo);
3160 if (error) {
3161 if (error->code == GOT_ERR_ANCESTRY) {
3162 error = checkout_ancestry_error(
3163 head_ref, commit_id_str);
3165 goto done;
3167 error = got_worktree_set_base_commit_id(worktree, repo,
3168 commit_id);
3169 if (error)
3170 goto done;
3171 /* Expand potentially abbreviated commit ID string. */
3172 free(commit_id_str);
3173 error = got_object_id_str(&commit_id_str, commit_id);
3174 if (error)
3175 goto done;
3176 } else {
3177 commit_id = got_object_id_dup(
3178 got_worktree_get_base_commit_id(worktree));
3179 if (commit_id == NULL) {
3180 error = got_error_from_errno("got_object_id_dup");
3181 goto done;
3183 error = got_object_id_str(&commit_id_str, commit_id);
3184 if (error)
3185 goto done;
3188 error = got_pathlist_append(&paths, "", NULL);
3189 if (error)
3190 goto done;
3191 cpa.worktree_path = worktree_path;
3192 cpa.had_base_commit_ref_error = 0;
3193 cpa.verbosity = verbosity;
3194 error = got_worktree_checkout_files(worktree, &paths, repo,
3195 checkout_progress, &cpa, check_cancelled, NULL);
3196 if (error != NULL)
3197 goto done;
3199 if (got_ref_is_symbolic(head_ref)) {
3200 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3201 if (error)
3202 goto done;
3203 refname = got_ref_get_name(ref);
3204 } else
3205 refname = got_ref_get_name(head_ref);
3206 printf("Checked out %s: %s\n", refname, commit_id_str);
3207 printf("Now shut up and hack\n");
3208 if (cpa.had_base_commit_ref_error)
3209 show_worktree_base_ref_warning();
3210 done:
3211 if (pack_fds) {
3212 const struct got_error *pack_err =
3213 got_repo_pack_fds_close(pack_fds);
3214 if (error == NULL)
3215 error = pack_err;
3217 if (head_ref)
3218 got_ref_close(head_ref);
3219 if (ref)
3220 got_ref_close(ref);
3221 if (repo) {
3222 const struct got_error *close_err = got_repo_close(repo);
3223 if (error == NULL)
3224 error = close_err;
3226 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3227 free(commit_id_str);
3228 free(commit_id);
3229 free(repo_path);
3230 free(worktree_path);
3231 free(cwd);
3232 return error;
3235 struct got_update_progress_arg {
3236 int did_something;
3237 int conflicts;
3238 int obstructed;
3239 int not_updated;
3240 int missing;
3241 int not_deleted;
3242 int unversioned;
3243 int verbosity;
3246 static void
3247 print_update_progress_stats(struct got_update_progress_arg *upa)
3249 if (!upa->did_something)
3250 return;
3252 if (upa->conflicts > 0)
3253 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3254 if (upa->obstructed > 0)
3255 printf("File paths obstructed by a non-regular file: %d\n",
3256 upa->obstructed);
3257 if (upa->not_updated > 0)
3258 printf("Files not updated because of existing merge "
3259 "conflicts: %d\n", upa->not_updated);
3263 * The meaning of some status codes differs between merge-style operations and
3264 * update operations. For example, the ! status code means "file was missing"
3265 * if changes were merged into the work tree, and "missing file was restored"
3266 * if the work tree was updated. This function should be used by any operation
3267 * which merges changes into the work tree without updating the work tree.
3269 static void
3270 print_merge_progress_stats(struct got_update_progress_arg *upa)
3272 if (!upa->did_something)
3273 return;
3275 if (upa->conflicts > 0)
3276 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3277 if (upa->obstructed > 0)
3278 printf("File paths obstructed by a non-regular file: %d\n",
3279 upa->obstructed);
3280 if (upa->missing > 0)
3281 printf("Files which had incoming changes but could not be "
3282 "found in the work tree: %d\n", upa->missing);
3283 if (upa->not_deleted > 0)
3284 printf("Files not deleted due to differences in deleted "
3285 "content: %d\n", upa->not_deleted);
3286 if (upa->unversioned > 0)
3287 printf("Files not merged because an unversioned file was "
3288 "found in the work tree: %d\n", upa->unversioned);
3291 __dead static void
3292 usage_update(void)
3294 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3295 "[path ...]\n", getprogname());
3296 exit(1);
3299 static const struct got_error *
3300 update_progress(void *arg, unsigned char status, const char *path)
3302 struct got_update_progress_arg *upa = arg;
3304 if (status == GOT_STATUS_EXISTS ||
3305 status == GOT_STATUS_BASE_REF_ERR)
3306 return NULL;
3308 upa->did_something = 1;
3310 /* Base commit bump happens silently. */
3311 if (status == GOT_STATUS_BUMP_BASE)
3312 return NULL;
3314 if (status == GOT_STATUS_CONFLICT)
3315 upa->conflicts++;
3316 if (status == GOT_STATUS_OBSTRUCTED)
3317 upa->obstructed++;
3318 if (status == GOT_STATUS_CANNOT_UPDATE)
3319 upa->not_updated++;
3320 if (status == GOT_STATUS_MISSING)
3321 upa->missing++;
3322 if (status == GOT_STATUS_CANNOT_DELETE)
3323 upa->not_deleted++;
3324 if (status == GOT_STATUS_UNVERSIONED)
3325 upa->unversioned++;
3327 while (path[0] == '/')
3328 path++;
3329 if (upa->verbosity >= 0)
3330 printf("%c %s\n", status, path);
3332 return NULL;
3335 static const struct got_error *
3336 switch_head_ref(struct got_reference *head_ref,
3337 struct got_object_id *commit_id, struct got_worktree *worktree,
3338 struct got_repository *repo)
3340 const struct got_error *err = NULL;
3341 char *base_id_str;
3342 int ref_has_moved = 0;
3344 /* Trivial case: switching between two different references. */
3345 if (strcmp(got_ref_get_name(head_ref),
3346 got_worktree_get_head_ref_name(worktree)) != 0) {
3347 printf("Switching work tree from %s to %s\n",
3348 got_worktree_get_head_ref_name(worktree),
3349 got_ref_get_name(head_ref));
3350 return got_worktree_set_head_ref(worktree, head_ref);
3353 err = check_linear_ancestry(commit_id,
3354 got_worktree_get_base_commit_id(worktree), 0, repo);
3355 if (err) {
3356 if (err->code != GOT_ERR_ANCESTRY)
3357 return err;
3358 ref_has_moved = 1;
3360 if (!ref_has_moved)
3361 return NULL;
3363 /* Switching to a rebased branch with the same reference name. */
3364 err = got_object_id_str(&base_id_str,
3365 got_worktree_get_base_commit_id(worktree));
3366 if (err)
3367 return err;
3368 printf("Reference %s now points at a different branch\n",
3369 got_worktree_get_head_ref_name(worktree));
3370 printf("Switching work tree from %s to %s\n", base_id_str,
3371 got_worktree_get_head_ref_name(worktree));
3372 return NULL;
3375 static const struct got_error *
3376 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3378 const struct got_error *err;
3379 int in_progress;
3381 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3382 if (err)
3383 return err;
3384 if (in_progress)
3385 return got_error(GOT_ERR_REBASING);
3387 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3388 if (err)
3389 return err;
3390 if (in_progress)
3391 return got_error(GOT_ERR_HISTEDIT_BUSY);
3393 return NULL;
3396 static const struct got_error *
3397 check_merge_in_progress(struct got_worktree *worktree,
3398 struct got_repository *repo)
3400 const struct got_error *err;
3401 int in_progress;
3403 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3404 if (err)
3405 return err;
3406 if (in_progress)
3407 return got_error(GOT_ERR_MERGE_BUSY);
3409 return NULL;
3412 static const struct got_error *
3413 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3414 char *argv[], struct got_worktree *worktree)
3416 const struct got_error *err = NULL;
3417 char *path;
3418 struct got_pathlist_entry *new;
3419 int i;
3421 if (argc == 0) {
3422 path = strdup("");
3423 if (path == NULL)
3424 return got_error_from_errno("strdup");
3425 return got_pathlist_append(paths, path, NULL);
3428 for (i = 0; i < argc; i++) {
3429 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3430 if (err)
3431 break;
3432 err = got_pathlist_insert(&new, paths, path, NULL);
3433 if (err || new == NULL /* duplicate */) {
3434 free(path);
3435 if (err)
3436 break;
3440 return err;
3443 static const struct got_error *
3444 wrap_not_worktree_error(const struct got_error *orig_err,
3445 const char *cmdname, const char *path)
3447 const struct got_error *err;
3448 struct got_repository *repo;
3449 static char msg[512];
3450 int *pack_fds = NULL;
3452 err = got_repo_pack_fds_open(&pack_fds);
3453 if (err)
3454 return err;
3456 err = got_repo_open(&repo, path, NULL, pack_fds);
3457 if (err)
3458 return orig_err;
3460 snprintf(msg, sizeof(msg),
3461 "'got %s' needs a work tree in addition to a git repository\n"
3462 "Work trees can be checked out from this Git repository with "
3463 "'got checkout'.\n"
3464 "The got(1) manual page contains more information.", cmdname);
3465 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3466 if (repo) {
3467 const struct got_error *close_err = got_repo_close(repo);
3468 if (err == NULL)
3469 err = close_err;
3471 if (pack_fds) {
3472 const struct got_error *pack_err =
3473 got_repo_pack_fds_close(pack_fds);
3474 if (err == NULL)
3475 err = pack_err;
3477 return err;
3480 static const struct got_error *
3481 cmd_update(int argc, char *argv[])
3483 const struct got_error *error = NULL;
3484 struct got_repository *repo = NULL;
3485 struct got_worktree *worktree = NULL;
3486 char *worktree_path = NULL;
3487 struct got_object_id *commit_id = NULL;
3488 char *commit_id_str = NULL;
3489 const char *branch_name = NULL;
3490 struct got_reference *head_ref = NULL;
3491 struct got_pathlist_head paths;
3492 struct got_pathlist_entry *pe;
3493 int ch, verbosity = 0;
3494 struct got_update_progress_arg upa;
3495 int *pack_fds = NULL;
3497 TAILQ_INIT(&paths);
3499 #ifndef PROFILE
3500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3501 "unveil", NULL) == -1)
3502 err(1, "pledge");
3503 #endif
3505 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3506 switch (ch) {
3507 case 'b':
3508 branch_name = optarg;
3509 break;
3510 case 'c':
3511 commit_id_str = strdup(optarg);
3512 if (commit_id_str == NULL)
3513 return got_error_from_errno("strdup");
3514 break;
3515 case 'q':
3516 verbosity = -1;
3517 break;
3518 default:
3519 usage_update();
3520 /* NOTREACHED */
3524 argc -= optind;
3525 argv += optind;
3527 worktree_path = getcwd(NULL, 0);
3528 if (worktree_path == NULL) {
3529 error = got_error_from_errno("getcwd");
3530 goto done;
3533 error = got_repo_pack_fds_open(&pack_fds);
3534 if (error != NULL)
3535 goto done;
3537 error = got_worktree_open(&worktree, worktree_path,
3538 GOT_WORKTREE_GOT_DIR);
3539 if (error) {
3540 if (error->code == GOT_ERR_NOT_WORKTREE)
3541 error = wrap_not_worktree_error(error, "update",
3542 worktree_path);
3543 goto done;
3546 error = check_rebase_or_histedit_in_progress(worktree);
3547 if (error)
3548 goto done;
3550 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3551 NULL, pack_fds);
3552 if (error != NULL)
3553 goto done;
3555 error = apply_unveil(got_repo_get_path(repo), 0,
3556 got_worktree_get_root_path(worktree));
3557 if (error)
3558 goto done;
3560 error = check_merge_in_progress(worktree, repo);
3561 if (error)
3562 goto done;
3564 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3565 if (error)
3566 goto done;
3568 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3569 got_worktree_get_head_ref_name(worktree), 0);
3570 if (error != NULL)
3571 goto done;
3572 if (commit_id_str == NULL) {
3573 error = got_ref_resolve(&commit_id, repo, head_ref);
3574 if (error != NULL)
3575 goto done;
3576 error = got_object_id_str(&commit_id_str, commit_id);
3577 if (error != NULL)
3578 goto done;
3579 } else {
3580 struct got_reflist_head refs;
3581 char *keyword_idstr = NULL;
3583 TAILQ_INIT(&refs);
3585 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3586 NULL);
3587 if (error)
3588 goto done;
3590 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3591 repo, worktree);
3592 if (error != NULL)
3593 goto done;
3594 if (keyword_idstr != NULL) {
3595 free(commit_id_str);
3596 commit_id_str = keyword_idstr;
3599 error = got_repo_match_object_id(&commit_id, NULL,
3600 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3601 got_ref_list_free(&refs);
3602 free(commit_id_str);
3603 commit_id_str = NULL;
3604 if (error)
3605 goto done;
3606 error = got_object_id_str(&commit_id_str, commit_id);
3607 if (error)
3608 goto done;
3611 if (branch_name) {
3612 struct got_object_id *head_commit_id;
3613 TAILQ_FOREACH(pe, &paths, entry) {
3614 if (pe->path_len == 0)
3615 continue;
3616 error = got_error_msg(GOT_ERR_BAD_PATH,
3617 "switching between branches requires that "
3618 "the entire work tree gets updated");
3619 goto done;
3621 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3622 if (error)
3623 goto done;
3624 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3625 repo);
3626 free(head_commit_id);
3627 if (error != NULL)
3628 goto done;
3629 error = check_same_branch(commit_id, head_ref, repo);
3630 if (error)
3631 goto done;
3632 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3633 if (error)
3634 goto done;
3635 } else {
3636 error = check_linear_ancestry(commit_id,
3637 got_worktree_get_base_commit_id(worktree), 0, repo);
3638 if (error != NULL) {
3639 if (error->code == GOT_ERR_ANCESTRY)
3640 error = got_error(GOT_ERR_BRANCH_MOVED);
3641 goto done;
3643 error = check_same_branch(commit_id, head_ref, repo);
3644 if (error)
3645 goto done;
3648 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3649 commit_id) != 0) {
3650 error = got_worktree_set_base_commit_id(worktree, repo,
3651 commit_id);
3652 if (error)
3653 goto done;
3656 memset(&upa, 0, sizeof(upa));
3657 upa.verbosity = verbosity;
3658 error = got_worktree_checkout_files(worktree, &paths, repo,
3659 update_progress, &upa, check_cancelled, NULL);
3660 if (error != NULL)
3661 goto done;
3663 if (upa.did_something) {
3664 printf("Updated to %s: %s\n",
3665 got_worktree_get_head_ref_name(worktree), commit_id_str);
3666 } else
3667 printf("Already up-to-date\n");
3669 print_update_progress_stats(&upa);
3670 done:
3671 if (pack_fds) {
3672 const struct got_error *pack_err =
3673 got_repo_pack_fds_close(pack_fds);
3674 if (error == NULL)
3675 error = pack_err;
3677 if (repo) {
3678 const struct got_error *close_err = got_repo_close(repo);
3679 if (error == NULL)
3680 error = close_err;
3682 free(worktree_path);
3683 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3684 free(commit_id);
3685 free(commit_id_str);
3686 return error;
3689 static const struct got_error *
3690 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3691 const char *path, int diff_context, int ignore_whitespace,
3692 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3693 struct got_repository *repo, FILE *outfile)
3695 const struct got_error *err = NULL;
3696 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3697 FILE *f1 = NULL, *f2 = NULL;
3698 int fd1 = -1, fd2 = -1;
3700 fd1 = got_opentempfd();
3701 if (fd1 == -1)
3702 return got_error_from_errno("got_opentempfd");
3703 fd2 = got_opentempfd();
3704 if (fd2 == -1) {
3705 err = got_error_from_errno("got_opentempfd");
3706 goto done;
3709 if (blob_id1) {
3710 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3711 fd1);
3712 if (err)
3713 goto done;
3716 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3717 if (err)
3718 goto done;
3720 f1 = got_opentemp();
3721 if (f1 == NULL) {
3722 err = got_error_from_errno("got_opentemp");
3723 goto done;
3725 f2 = got_opentemp();
3726 if (f2 == NULL) {
3727 err = got_error_from_errno("got_opentemp");
3728 goto done;
3731 while (path[0] == '/')
3732 path++;
3733 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3734 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3735 force_text_diff, dsa, outfile);
3736 done:
3737 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3738 err = got_error_from_errno("close");
3739 if (blob1)
3740 got_object_blob_close(blob1);
3741 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3742 err = got_error_from_errno("close");
3743 if (blob2)
3744 got_object_blob_close(blob2);
3745 if (f1 && fclose(f1) == EOF && err == NULL)
3746 err = got_error_from_errno("fclose");
3747 if (f2 && fclose(f2) == EOF && err == NULL)
3748 err = got_error_from_errno("fclose");
3749 return err;
3752 static const struct got_error *
3753 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3754 const char *path, int diff_context, int ignore_whitespace,
3755 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3756 struct got_repository *repo, FILE *outfile)
3758 const struct got_error *err = NULL;
3759 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3760 struct got_diff_blob_output_unidiff_arg arg;
3761 FILE *f1 = NULL, *f2 = NULL;
3762 int fd1 = -1, fd2 = -1;
3764 if (tree_id1) {
3765 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3766 if (err)
3767 goto done;
3768 fd1 = got_opentempfd();
3769 if (fd1 == -1) {
3770 err = got_error_from_errno("got_opentempfd");
3771 goto done;
3775 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3776 if (err)
3777 goto done;
3779 f1 = got_opentemp();
3780 if (f1 == NULL) {
3781 err = got_error_from_errno("got_opentemp");
3782 goto done;
3785 f2 = got_opentemp();
3786 if (f2 == NULL) {
3787 err = got_error_from_errno("got_opentemp");
3788 goto done;
3790 fd2 = got_opentempfd();
3791 if (fd2 == -1) {
3792 err = got_error_from_errno("got_opentempfd");
3793 goto done;
3795 arg.diff_context = diff_context;
3796 arg.ignore_whitespace = ignore_whitespace;
3797 arg.force_text_diff = force_text_diff;
3798 arg.diffstat = dsa;
3799 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3800 arg.outfile = outfile;
3801 arg.lines = NULL;
3802 arg.nlines = 0;
3803 while (path[0] == '/')
3804 path++;
3805 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3806 got_diff_blob_output_unidiff, &arg, 1);
3807 done:
3808 if (tree1)
3809 got_object_tree_close(tree1);
3810 if (tree2)
3811 got_object_tree_close(tree2);
3812 if (f1 && fclose(f1) == EOF && err == NULL)
3813 err = got_error_from_errno("fclose");
3814 if (f2 && fclose(f2) == EOF && err == NULL)
3815 err = got_error_from_errno("fclose");
3816 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3817 err = got_error_from_errno("close");
3818 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3819 err = got_error_from_errno("close");
3820 return err;
3823 static const struct got_error *
3824 get_changed_paths(struct got_pathlist_head *paths,
3825 struct got_commit_object *commit, struct got_repository *repo,
3826 struct got_diffstat_cb_arg *dsa)
3828 const struct got_error *err = NULL;
3829 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3830 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3831 struct got_object_qid *qid;
3832 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3833 FILE *f1 = NULL, *f2 = NULL;
3834 int fd1 = -1, fd2 = -1;
3836 if (dsa) {
3837 cb = got_diff_tree_compute_diffstat;
3839 f1 = got_opentemp();
3840 if (f1 == NULL) {
3841 err = got_error_from_errno("got_opentemp");
3842 goto done;
3844 f2 = got_opentemp();
3845 if (f2 == NULL) {
3846 err = got_error_from_errno("got_opentemp");
3847 goto done;
3849 fd1 = got_opentempfd();
3850 if (fd1 == -1) {
3851 err = got_error_from_errno("got_opentempfd");
3852 goto done;
3854 fd2 = got_opentempfd();
3855 if (fd2 == -1) {
3856 err = got_error_from_errno("got_opentempfd");
3857 goto done;
3861 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3862 if (qid != NULL) {
3863 struct got_commit_object *pcommit;
3864 err = got_object_open_as_commit(&pcommit, repo,
3865 &qid->id);
3866 if (err)
3867 return err;
3869 tree_id1 = got_object_id_dup(
3870 got_object_commit_get_tree_id(pcommit));
3871 if (tree_id1 == NULL) {
3872 got_object_commit_close(pcommit);
3873 return got_error_from_errno("got_object_id_dup");
3875 got_object_commit_close(pcommit);
3879 if (tree_id1) {
3880 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3881 if (err)
3882 goto done;
3885 tree_id2 = got_object_commit_get_tree_id(commit);
3886 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3887 if (err)
3888 goto done;
3890 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3891 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3892 done:
3893 if (tree1)
3894 got_object_tree_close(tree1);
3895 if (tree2)
3896 got_object_tree_close(tree2);
3897 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3898 err = got_error_from_errno("close");
3899 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3900 err = got_error_from_errno("close");
3901 if (f1 && fclose(f1) == EOF && err == NULL)
3902 err = got_error_from_errno("fclose");
3903 if (f2 && fclose(f2) == EOF && err == NULL)
3904 err = got_error_from_errno("fclose");
3905 free(tree_id1);
3906 return err;
3909 static const struct got_error *
3910 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3911 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3912 struct got_repository *repo, FILE *outfile)
3914 const struct got_error *err = NULL;
3915 struct got_commit_object *pcommit = NULL;
3916 char *id_str1 = NULL, *id_str2 = NULL;
3917 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3918 struct got_object_qid *qid;
3920 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3921 if (qid != NULL) {
3922 err = got_object_open_as_commit(&pcommit, repo,
3923 &qid->id);
3924 if (err)
3925 return err;
3926 err = got_object_id_str(&id_str1, &qid->id);
3927 if (err)
3928 goto done;
3931 err = got_object_id_str(&id_str2, id);
3932 if (err)
3933 goto done;
3935 if (path && path[0] != '\0') {
3936 int obj_type;
3937 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3938 if (err)
3939 goto done;
3940 if (pcommit) {
3941 err = got_object_id_by_path(&obj_id1, repo,
3942 pcommit, path);
3943 if (err) {
3944 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3945 free(obj_id2);
3946 goto done;
3950 err = got_object_get_type(&obj_type, repo, obj_id2);
3951 if (err) {
3952 free(obj_id2);
3953 goto done;
3955 fprintf(outfile,
3956 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3957 fprintf(outfile, "commit - %s\n",
3958 id_str1 ? id_str1 : "/dev/null");
3959 fprintf(outfile, "commit + %s\n", id_str2);
3960 switch (obj_type) {
3961 case GOT_OBJ_TYPE_BLOB:
3962 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3963 0, 0, dsa, repo, outfile);
3964 break;
3965 case GOT_OBJ_TYPE_TREE:
3966 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3967 0, 0, dsa, repo, outfile);
3968 break;
3969 default:
3970 err = got_error(GOT_ERR_OBJ_TYPE);
3971 break;
3973 free(obj_id1);
3974 free(obj_id2);
3975 } else {
3976 obj_id2 = got_object_commit_get_tree_id(commit);
3977 if (pcommit)
3978 obj_id1 = got_object_commit_get_tree_id(pcommit);
3979 fprintf(outfile,
3980 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3981 fprintf(outfile, "commit - %s\n",
3982 id_str1 ? id_str1 : "/dev/null");
3983 fprintf(outfile, "commit + %s\n", id_str2);
3984 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3985 dsa, repo, outfile);
3987 done:
3988 free(id_str1);
3989 free(id_str2);
3990 if (pcommit)
3991 got_object_commit_close(pcommit);
3992 return err;
3995 static char *
3996 get_datestr(time_t *time, char *datebuf)
3998 struct tm mytm, *tm;
3999 char *p, *s;
4001 tm = gmtime_r(time, &mytm);
4002 if (tm == NULL)
4003 return NULL;
4004 s = asctime_r(tm, datebuf);
4005 if (s == NULL)
4006 return NULL;
4007 p = strchr(s, '\n');
4008 if (p)
4009 *p = '\0';
4010 return s;
4013 static const struct got_error *
4014 match_commit(int *have_match, struct got_object_id *id,
4015 struct got_commit_object *commit, regex_t *regex)
4017 const struct got_error *err = NULL;
4018 regmatch_t regmatch;
4019 char *id_str = NULL, *logmsg = NULL;
4021 *have_match = 0;
4023 err = got_object_id_str(&id_str, id);
4024 if (err)
4025 return err;
4027 err = got_object_commit_get_logmsg(&logmsg, commit);
4028 if (err)
4029 goto done;
4031 if (regexec(regex, got_object_commit_get_author(commit), 1,
4032 &regmatch, 0) == 0 ||
4033 regexec(regex, got_object_commit_get_committer(commit), 1,
4034 &regmatch, 0) == 0 ||
4035 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4036 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4037 *have_match = 1;
4038 done:
4039 free(id_str);
4040 free(logmsg);
4041 return err;
4044 static void
4045 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4046 regex_t *regex)
4048 regmatch_t regmatch;
4049 struct got_pathlist_entry *pe;
4051 *have_match = 0;
4053 TAILQ_FOREACH(pe, changed_paths, entry) {
4054 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4055 *have_match = 1;
4056 break;
4061 static const struct got_error *
4062 match_patch(int *have_match, struct got_commit_object *commit,
4063 struct got_object_id *id, const char *path, int diff_context,
4064 struct got_repository *repo, regex_t *regex, FILE *f)
4066 const struct got_error *err = NULL;
4067 char *line = NULL;
4068 size_t linesize = 0;
4069 regmatch_t regmatch;
4071 *have_match = 0;
4073 err = got_opentemp_truncate(f);
4074 if (err)
4075 return err;
4077 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4078 if (err)
4079 goto done;
4081 if (fseeko(f, 0L, SEEK_SET) == -1) {
4082 err = got_error_from_errno("fseeko");
4083 goto done;
4086 while (getline(&line, &linesize, f) != -1) {
4087 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4088 *have_match = 1;
4089 break;
4092 done:
4093 free(line);
4094 return err;
4097 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4099 static const struct got_error*
4100 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4101 struct got_object_id *id, struct got_repository *repo,
4102 int local_only)
4104 static const struct got_error *err = NULL;
4105 struct got_reflist_entry *re;
4106 char *s;
4107 const char *name;
4109 *refs_str = NULL;
4111 TAILQ_FOREACH(re, refs, entry) {
4112 struct got_tag_object *tag = NULL;
4113 struct got_object_id *ref_id;
4114 int cmp;
4116 name = got_ref_get_name(re->ref);
4117 if (strcmp(name, GOT_REF_HEAD) == 0)
4118 continue;
4119 if (strncmp(name, "refs/", 5) == 0)
4120 name += 5;
4121 if (strncmp(name, "got/", 4) == 0)
4122 continue;
4123 if (strncmp(name, "heads/", 6) == 0)
4124 name += 6;
4125 if (strncmp(name, "remotes/", 8) == 0) {
4126 if (local_only)
4127 continue;
4128 name += 8;
4129 s = strstr(name, "/" GOT_REF_HEAD);
4130 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4131 continue;
4133 err = got_ref_resolve(&ref_id, repo, re->ref);
4134 if (err)
4135 break;
4136 if (strncmp(name, "tags/", 5) == 0) {
4137 err = got_object_open_as_tag(&tag, repo, ref_id);
4138 if (err) {
4139 if (err->code != GOT_ERR_OBJ_TYPE) {
4140 free(ref_id);
4141 break;
4143 /* Ref points at something other than a tag. */
4144 err = NULL;
4145 tag = NULL;
4148 cmp = got_object_id_cmp(tag ?
4149 got_object_tag_get_object_id(tag) : ref_id, id);
4150 free(ref_id);
4151 if (tag)
4152 got_object_tag_close(tag);
4153 if (cmp != 0)
4154 continue;
4155 s = *refs_str;
4156 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4157 s ? ", " : "", name) == -1) {
4158 err = got_error_from_errno("asprintf");
4159 free(s);
4160 *refs_str = NULL;
4161 break;
4163 free(s);
4166 return err;
4169 static const struct got_error *
4170 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4171 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4173 const struct got_error *err = NULL;
4174 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4175 char *comma, *s, *nl;
4176 struct got_reflist_head *refs;
4177 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4178 struct tm tm;
4179 time_t committer_time;
4181 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4182 if (refs) {
4183 err = build_refs_str(&ref_str, refs, id, repo, 1);
4184 if (err)
4185 return err;
4187 /* Display the first matching ref only. */
4188 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4189 *comma = '\0';
4192 if (ref_str == NULL) {
4193 err = got_object_id_str(&id_str, id);
4194 if (err)
4195 return err;
4198 committer_time = got_object_commit_get_committer_time(commit);
4199 if (gmtime_r(&committer_time, &tm) == NULL) {
4200 err = got_error_from_errno("gmtime_r");
4201 goto done;
4203 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4204 err = got_error(GOT_ERR_NO_SPACE);
4205 goto done;
4208 err = got_object_commit_get_logmsg(&logmsg0, commit);
4209 if (err)
4210 goto done;
4212 s = logmsg0;
4213 while (isspace((unsigned char)s[0]))
4214 s++;
4216 nl = strchr(s, '\n');
4217 if (nl) {
4218 *nl = '\0';
4221 if (ref_str)
4222 printf("%s%-7s %s\n", datebuf, ref_str, s);
4223 else
4224 printf("%s%.7s %s\n", datebuf, id_str, s);
4226 if (fflush(stdout) != 0 && err == NULL)
4227 err = got_error_from_errno("fflush");
4228 done:
4229 free(id_str);
4230 free(ref_str);
4231 free(logmsg0);
4232 return err;
4235 static const struct got_error *
4236 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4238 struct got_pathlist_entry *pe;
4240 if (header != NULL)
4241 printf("%s\n", header);
4243 TAILQ_FOREACH(pe, dsa->paths, entry) {
4244 struct got_diff_changed_path *cp = pe->data;
4245 int pad = dsa->max_path_len - pe->path_len + 1;
4247 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4248 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4250 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4251 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4252 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4254 if (fflush(stdout) != 0)
4255 return got_error_from_errno("fflush");
4257 return NULL;
4260 static const struct got_error *
4261 printfile(FILE *f)
4263 char buf[8192];
4264 size_t r;
4266 if (fseeko(f, 0L, SEEK_SET) == -1)
4267 return got_error_from_errno("fseek");
4269 for (;;) {
4270 r = fread(buf, 1, sizeof(buf), f);
4271 if (r == 0) {
4272 if (ferror(f))
4273 return got_error_from_errno("fread");
4274 if (feof(f))
4275 break;
4277 if (fwrite(buf, 1, r, stdout) != r)
4278 return got_ferror(stdout, GOT_ERR_IO);
4281 return NULL;
4284 static const struct got_error *
4285 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4286 struct got_repository *repo, const char *path,
4287 struct got_pathlist_head *changed_paths,
4288 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4289 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4290 const char *prefix)
4292 const struct got_error *err = NULL;
4293 FILE *f = NULL;
4294 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4295 char datebuf[26];
4296 time_t committer_time;
4297 const char *author, *committer;
4298 char *refs_str = NULL;
4300 err = got_object_id_str(&id_str, id);
4301 if (err)
4302 return err;
4304 if (custom_refs_str == NULL) {
4305 struct got_reflist_head *refs;
4306 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4307 if (refs) {
4308 err = build_refs_str(&refs_str, refs, id, repo, 0);
4309 if (err)
4310 goto done;
4314 printf(GOT_COMMIT_SEP_STR);
4315 if (custom_refs_str)
4316 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4317 custom_refs_str);
4318 else
4319 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4320 refs_str ? " (" : "", refs_str ? refs_str : "",
4321 refs_str ? ")" : "");
4322 free(id_str);
4323 id_str = NULL;
4324 free(refs_str);
4325 refs_str = NULL;
4326 printf("from: %s\n", got_object_commit_get_author(commit));
4327 author = got_object_commit_get_author(commit);
4328 committer = got_object_commit_get_committer(commit);
4329 if (strcmp(author, committer) != 0)
4330 printf("via: %s\n", committer);
4331 committer_time = got_object_commit_get_committer_time(commit);
4332 datestr = get_datestr(&committer_time, datebuf);
4333 if (datestr)
4334 printf("date: %s UTC\n", datestr);
4335 if (got_object_commit_get_nparents(commit) > 1) {
4336 const struct got_object_id_queue *parent_ids;
4337 struct got_object_qid *qid;
4338 int n = 1;
4339 parent_ids = got_object_commit_get_parent_ids(commit);
4340 STAILQ_FOREACH(qid, parent_ids, entry) {
4341 err = got_object_id_str(&id_str, &qid->id);
4342 if (err)
4343 goto done;
4344 printf("parent %d: %s\n", n++, id_str);
4345 free(id_str);
4346 id_str = NULL;
4350 err = got_object_commit_get_logmsg(&logmsg0, commit);
4351 if (err)
4352 goto done;
4354 logmsg = logmsg0;
4355 do {
4356 line = strsep(&logmsg, "\n");
4357 if (line)
4358 printf(" %s\n", line);
4359 } while (line);
4360 free(logmsg0);
4362 if (changed_paths && diffstat == NULL) {
4363 struct got_pathlist_entry *pe;
4365 TAILQ_FOREACH(pe, changed_paths, entry) {
4366 struct got_diff_changed_path *cp = pe->data;
4368 printf(" %c %s\n", cp->status, pe->path);
4370 printf("\n");
4372 if (show_patch) {
4373 if (diffstat) {
4374 f = got_opentemp();
4375 if (f == NULL) {
4376 err = got_error_from_errno("got_opentemp");
4377 goto done;
4381 err = print_patch(commit, id, path, diff_context, diffstat,
4382 repo, diffstat == NULL ? stdout : f);
4383 if (err)
4384 goto done;
4386 if (diffstat) {
4387 err = print_diffstat(diffstat, NULL);
4388 if (err)
4389 goto done;
4390 if (show_patch) {
4391 err = printfile(f);
4392 if (err)
4393 goto done;
4396 if (show_patch)
4397 printf("\n");
4399 if (fflush(stdout) != 0 && err == NULL)
4400 err = got_error_from_errno("fflush");
4401 done:
4402 if (f && fclose(f) == EOF && err == NULL)
4403 err = got_error_from_errno("fclose");
4404 free(id_str);
4405 free(refs_str);
4406 return err;
4409 static const struct got_error *
4410 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4411 struct got_repository *repo, const char *path, int show_changed_paths,
4412 int show_diffstat, int show_patch, const char *search_pattern,
4413 int diff_context, int limit, int log_branches, int reverse_display_order,
4414 struct got_reflist_object_id_map *refs_idmap, int one_line,
4415 FILE *tmpfile)
4417 const struct got_error *err;
4418 struct got_commit_graph *graph;
4419 regex_t regex;
4420 int have_match;
4421 struct got_object_id_queue reversed_commits;
4422 struct got_object_qid *qid;
4423 struct got_commit_object *commit;
4424 struct got_pathlist_head changed_paths;
4426 STAILQ_INIT(&reversed_commits);
4427 TAILQ_INIT(&changed_paths);
4429 if (search_pattern && regcomp(&regex, search_pattern,
4430 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4431 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4433 err = got_commit_graph_open(&graph, path, !log_branches);
4434 if (err)
4435 return err;
4436 err = got_commit_graph_iter_start(graph, root_id, repo,
4437 check_cancelled, NULL);
4438 if (err)
4439 goto done;
4440 for (;;) {
4441 struct got_object_id id;
4442 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4443 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4445 if (sigint_received || sigpipe_received)
4446 break;
4448 err = got_commit_graph_iter_next(&id, graph, repo,
4449 check_cancelled, NULL);
4450 if (err) {
4451 if (err->code == GOT_ERR_ITER_COMPLETED)
4452 err = NULL;
4453 break;
4456 err = got_object_open_as_commit(&commit, repo, &id);
4457 if (err)
4458 break;
4460 if ((show_changed_paths || (show_diffstat && !show_patch))
4461 && !reverse_display_order) {
4462 err = get_changed_paths(&changed_paths, commit, repo,
4463 show_diffstat ? &dsa : NULL);
4464 if (err)
4465 break;
4468 if (search_pattern) {
4469 err = match_commit(&have_match, &id, commit, &regex);
4470 if (err) {
4471 got_object_commit_close(commit);
4472 break;
4474 if (have_match == 0 && show_changed_paths)
4475 match_changed_paths(&have_match,
4476 &changed_paths, &regex);
4477 if (have_match == 0 && show_patch) {
4478 err = match_patch(&have_match, commit, &id,
4479 path, diff_context, repo, &regex, tmpfile);
4480 if (err)
4481 break;
4483 if (have_match == 0) {
4484 got_object_commit_close(commit);
4485 got_pathlist_free(&changed_paths,
4486 GOT_PATHLIST_FREE_ALL);
4487 continue;
4491 if (reverse_display_order) {
4492 err = got_object_qid_alloc(&qid, &id);
4493 if (err)
4494 break;
4495 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4496 got_object_commit_close(commit);
4497 } else {
4498 if (one_line)
4499 err = print_commit_oneline(commit, &id,
4500 repo, refs_idmap);
4501 else
4502 err = print_commit(commit, &id, repo, path,
4503 (show_changed_paths || show_diffstat) ?
4504 &changed_paths : NULL,
4505 show_diffstat ? &dsa : NULL, show_patch,
4506 diff_context, refs_idmap, NULL, NULL);
4507 got_object_commit_close(commit);
4508 if (err)
4509 break;
4511 if ((limit && --limit == 0) ||
4512 (end_id && got_object_id_cmp(&id, end_id) == 0))
4513 break;
4515 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4517 if (reverse_display_order) {
4518 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4519 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4520 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4522 err = got_object_open_as_commit(&commit, repo,
4523 &qid->id);
4524 if (err)
4525 break;
4526 if (show_changed_paths ||
4527 (show_diffstat && !show_patch)) {
4528 err = get_changed_paths(&changed_paths, commit,
4529 repo, show_diffstat ? &dsa : NULL);
4530 if (err)
4531 break;
4533 if (one_line)
4534 err = print_commit_oneline(commit, &qid->id,
4535 repo, refs_idmap);
4536 else
4537 err = print_commit(commit, &qid->id, repo, path,
4538 (show_changed_paths || show_diffstat) ?
4539 &changed_paths : NULL,
4540 show_diffstat ? &dsa : NULL, show_patch,
4541 diff_context, refs_idmap, NULL, NULL);
4542 got_object_commit_close(commit);
4543 if (err)
4544 break;
4545 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4548 done:
4549 while (!STAILQ_EMPTY(&reversed_commits)) {
4550 qid = STAILQ_FIRST(&reversed_commits);
4551 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4552 got_object_qid_free(qid);
4554 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4555 if (search_pattern)
4556 regfree(&regex);
4557 got_commit_graph_close(graph);
4558 return err;
4561 __dead static void
4562 usage_log(void)
4564 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4565 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4566 "[path]\n", getprogname());
4567 exit(1);
4570 static int
4571 get_default_log_limit(void)
4573 const char *got_default_log_limit;
4574 long long n;
4575 const char *errstr;
4577 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4578 if (got_default_log_limit == NULL)
4579 return 0;
4580 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4581 if (errstr != NULL)
4582 return 0;
4583 return n;
4586 static const struct got_error *
4587 cmd_log(int argc, char *argv[])
4589 const struct got_error *error;
4590 struct got_repository *repo = NULL;
4591 struct got_worktree *worktree = NULL;
4592 struct got_object_id *start_id = NULL, *end_id = NULL;
4593 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4594 const char *start_commit = NULL, *end_commit = NULL;
4595 const char *search_pattern = NULL;
4596 int diff_context = -1, ch;
4597 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4598 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4599 const char *errstr;
4600 struct got_reflist_head refs;
4601 struct got_reflist_object_id_map *refs_idmap = NULL;
4602 FILE *tmpfile = NULL;
4603 int *pack_fds = NULL;
4605 TAILQ_INIT(&refs);
4607 #ifndef PROFILE
4608 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4609 NULL)
4610 == -1)
4611 err(1, "pledge");
4612 #endif
4614 limit = get_default_log_limit();
4616 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4617 switch (ch) {
4618 case 'b':
4619 log_branches = 1;
4620 break;
4621 case 'C':
4622 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4623 &errstr);
4624 if (errstr != NULL)
4625 errx(1, "number of context lines is %s: %s",
4626 errstr, optarg);
4627 break;
4628 case 'c':
4629 start_commit = optarg;
4630 break;
4631 case 'd':
4632 show_diffstat = 1;
4633 break;
4634 case 'l':
4635 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4636 if (errstr != NULL)
4637 errx(1, "number of commits is %s: %s",
4638 errstr, optarg);
4639 break;
4640 case 'P':
4641 show_changed_paths = 1;
4642 break;
4643 case 'p':
4644 show_patch = 1;
4645 break;
4646 case 'R':
4647 reverse_display_order = 1;
4648 break;
4649 case 'r':
4650 repo_path = realpath(optarg, NULL);
4651 if (repo_path == NULL)
4652 return got_error_from_errno2("realpath",
4653 optarg);
4654 got_path_strip_trailing_slashes(repo_path);
4655 break;
4656 case 'S':
4657 search_pattern = optarg;
4658 break;
4659 case 's':
4660 one_line = 1;
4661 break;
4662 case 'x':
4663 end_commit = optarg;
4664 break;
4665 default:
4666 usage_log();
4667 /* NOTREACHED */
4671 argc -= optind;
4672 argv += optind;
4674 if (diff_context == -1)
4675 diff_context = 3;
4676 else if (!show_patch)
4677 errx(1, "-C requires -p");
4679 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4680 errx(1, "cannot use -s with -d, -p or -P");
4682 cwd = getcwd(NULL, 0);
4683 if (cwd == NULL) {
4684 error = got_error_from_errno("getcwd");
4685 goto done;
4688 error = got_repo_pack_fds_open(&pack_fds);
4689 if (error != NULL)
4690 goto done;
4692 if (repo_path == NULL) {
4693 error = got_worktree_open(&worktree, cwd,
4694 GOT_WORKTREE_GOT_DIR);
4695 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4696 goto done;
4697 error = NULL;
4700 if (argc == 1) {
4701 if (worktree) {
4702 error = got_worktree_resolve_path(&path, worktree,
4703 argv[0]);
4704 if (error)
4705 goto done;
4706 } else {
4707 path = strdup(argv[0]);
4708 if (path == NULL) {
4709 error = got_error_from_errno("strdup");
4710 goto done;
4713 } else if (argc != 0)
4714 usage_log();
4716 if (repo_path == NULL) {
4717 repo_path = worktree ?
4718 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4720 if (repo_path == NULL) {
4721 error = got_error_from_errno("strdup");
4722 goto done;
4725 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4726 if (error != NULL)
4727 goto done;
4729 error = apply_unveil(got_repo_get_path(repo), 1,
4730 worktree ? got_worktree_get_root_path(worktree) : NULL);
4731 if (error)
4732 goto done;
4734 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4735 if (error)
4736 goto done;
4738 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4739 if (error)
4740 goto done;
4742 if (start_commit == NULL) {
4743 struct got_reference *head_ref;
4744 struct got_commit_object *commit = NULL;
4745 error = got_ref_open(&head_ref, repo,
4746 worktree ? got_worktree_get_head_ref_name(worktree)
4747 : GOT_REF_HEAD, 0);
4748 if (error != NULL)
4749 goto done;
4750 error = got_ref_resolve(&start_id, repo, head_ref);
4751 got_ref_close(head_ref);
4752 if (error != NULL)
4753 goto done;
4754 error = got_object_open_as_commit(&commit, repo,
4755 start_id);
4756 if (error != NULL)
4757 goto done;
4758 got_object_commit_close(commit);
4759 } else {
4760 char *keyword_idstr = NULL;
4762 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4763 repo, worktree);
4764 if (error != NULL)
4765 goto done;
4766 if (keyword_idstr != NULL)
4767 start_commit = keyword_idstr;
4769 error = got_repo_match_object_id(&start_id, NULL,
4770 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4771 free(keyword_idstr);
4772 if (error != NULL)
4773 goto done;
4775 if (end_commit != NULL) {
4776 error = got_repo_match_object_id(&end_id, NULL,
4777 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4778 if (error != NULL)
4779 goto done;
4782 if (worktree) {
4784 * If a path was specified on the command line it was resolved
4785 * to a path in the work tree above. Prepend the work tree's
4786 * path prefix to obtain the corresponding in-repository path.
4788 if (path) {
4789 const char *prefix;
4790 prefix = got_worktree_get_path_prefix(worktree);
4791 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4792 (path[0] != '\0') ? "/" : "", path) == -1) {
4793 error = got_error_from_errno("asprintf");
4794 goto done;
4797 } else
4798 error = got_repo_map_path(&in_repo_path, repo,
4799 path ? path : "");
4800 if (error != NULL)
4801 goto done;
4802 if (in_repo_path) {
4803 free(path);
4804 path = in_repo_path;
4807 if (worktree) {
4808 /* Release work tree lock. */
4809 got_worktree_close(worktree);
4810 worktree = NULL;
4813 if (search_pattern && show_patch) {
4814 tmpfile = got_opentemp();
4815 if (tmpfile == NULL) {
4816 error = got_error_from_errno("got_opentemp");
4817 goto done;
4821 error = print_commits(start_id, end_id, repo, path ? path : "",
4822 show_changed_paths, show_diffstat, show_patch, search_pattern,
4823 diff_context, limit, log_branches, reverse_display_order,
4824 refs_idmap, one_line, tmpfile);
4825 done:
4826 free(path);
4827 free(repo_path);
4828 free(cwd);
4829 free(start_id);
4830 free(end_id);
4831 if (worktree)
4832 got_worktree_close(worktree);
4833 if (repo) {
4834 const struct got_error *close_err = got_repo_close(repo);
4835 if (error == NULL)
4836 error = close_err;
4838 if (pack_fds) {
4839 const struct got_error *pack_err =
4840 got_repo_pack_fds_close(pack_fds);
4841 if (error == NULL)
4842 error = pack_err;
4844 if (refs_idmap)
4845 got_reflist_object_id_map_free(refs_idmap);
4846 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4847 error = got_error_from_errno("fclose");
4848 got_ref_list_free(&refs);
4849 return error;
4852 __dead static void
4853 usage_diff(void)
4855 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4856 "[-r repository-path] [object1 object2 | path ...]\n",
4857 getprogname());
4858 exit(1);
4861 struct print_diff_arg {
4862 struct got_repository *repo;
4863 struct got_worktree *worktree;
4864 struct got_diffstat_cb_arg *diffstat;
4865 int diff_context;
4866 const char *id_str;
4867 int header_shown;
4868 int diff_staged;
4869 enum got_diff_algorithm diff_algo;
4870 int ignore_whitespace;
4871 int force_text_diff;
4872 FILE *f1;
4873 FILE *f2;
4874 FILE *outfile;
4878 * Create a file which contains the target path of a symlink so we can feed
4879 * it as content to the diff engine.
4881 static const struct got_error *
4882 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4883 const char *abspath)
4885 const struct got_error *err = NULL;
4886 char target_path[PATH_MAX];
4887 ssize_t target_len, outlen;
4889 *fd = -1;
4891 if (dirfd != -1) {
4892 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4893 if (target_len == -1)
4894 return got_error_from_errno2("readlinkat", abspath);
4895 } else {
4896 target_len = readlink(abspath, target_path, PATH_MAX);
4897 if (target_len == -1)
4898 return got_error_from_errno2("readlink", abspath);
4901 *fd = got_opentempfd();
4902 if (*fd == -1)
4903 return got_error_from_errno("got_opentempfd");
4905 outlen = write(*fd, target_path, target_len);
4906 if (outlen == -1) {
4907 err = got_error_from_errno("got_opentempfd");
4908 goto done;
4911 if (lseek(*fd, 0, SEEK_SET) == -1) {
4912 err = got_error_from_errno2("lseek", abspath);
4913 goto done;
4915 done:
4916 if (err) {
4917 close(*fd);
4918 *fd = -1;
4920 return err;
4923 static const struct got_error *
4924 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4925 const char *path, struct got_object_id *blob_id,
4926 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4927 int dirfd, const char *de_name)
4929 struct print_diff_arg *a = arg;
4930 const struct got_error *err = NULL;
4931 struct got_blob_object *blob1 = NULL;
4932 int fd = -1, fd1 = -1, fd2 = -1;
4933 FILE *f2 = NULL;
4934 char *abspath = NULL, *label1 = NULL;
4935 struct stat sb;
4936 off_t size1 = 0;
4937 int f2_exists = 0;
4939 memset(&sb, 0, sizeof(sb));
4941 if (a->diff_staged) {
4942 if (staged_status != GOT_STATUS_MODIFY &&
4943 staged_status != GOT_STATUS_ADD &&
4944 staged_status != GOT_STATUS_DELETE)
4945 return NULL;
4946 } else {
4947 if (staged_status == GOT_STATUS_DELETE)
4948 return NULL;
4949 if (status == GOT_STATUS_NONEXISTENT)
4950 return got_error_set_errno(ENOENT, path);
4951 if (status != GOT_STATUS_MODIFY &&
4952 status != GOT_STATUS_ADD &&
4953 status != GOT_STATUS_DELETE &&
4954 status != GOT_STATUS_CONFLICT)
4955 return NULL;
4958 err = got_opentemp_truncate(a->f1);
4959 if (err)
4960 return got_error_from_errno("got_opentemp_truncate");
4961 err = got_opentemp_truncate(a->f2);
4962 if (err)
4963 return got_error_from_errno("got_opentemp_truncate");
4965 if (!a->header_shown) {
4966 if (fprintf(a->outfile, "diff %s%s\n",
4967 a->diff_staged ? "-s " : "",
4968 got_worktree_get_root_path(a->worktree)) < 0) {
4969 err = got_error_from_errno("fprintf");
4970 goto done;
4972 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4973 err = got_error_from_errno("fprintf");
4974 goto done;
4976 if (fprintf(a->outfile, "path + %s%s\n",
4977 got_worktree_get_root_path(a->worktree),
4978 a->diff_staged ? " (staged changes)" : "") < 0) {
4979 err = got_error_from_errno("fprintf");
4980 goto done;
4982 a->header_shown = 1;
4985 if (a->diff_staged) {
4986 const char *label1 = NULL, *label2 = NULL;
4987 switch (staged_status) {
4988 case GOT_STATUS_MODIFY:
4989 label1 = path;
4990 label2 = path;
4991 break;
4992 case GOT_STATUS_ADD:
4993 label2 = path;
4994 break;
4995 case GOT_STATUS_DELETE:
4996 label1 = path;
4997 break;
4998 default:
4999 return got_error(GOT_ERR_FILE_STATUS);
5001 fd1 = got_opentempfd();
5002 if (fd1 == -1) {
5003 err = got_error_from_errno("got_opentempfd");
5004 goto done;
5006 fd2 = got_opentempfd();
5007 if (fd2 == -1) {
5008 err = got_error_from_errno("got_opentempfd");
5009 goto done;
5011 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5012 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5013 a->diff_algo, a->diff_context, a->ignore_whitespace,
5014 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5015 goto done;
5018 fd1 = got_opentempfd();
5019 if (fd1 == -1) {
5020 err = got_error_from_errno("got_opentempfd");
5021 goto done;
5024 if (staged_status == GOT_STATUS_ADD ||
5025 staged_status == GOT_STATUS_MODIFY) {
5026 char *id_str;
5027 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5028 8192, fd1);
5029 if (err)
5030 goto done;
5031 err = got_object_id_str(&id_str, staged_blob_id);
5032 if (err)
5033 goto done;
5034 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5035 err = got_error_from_errno("asprintf");
5036 free(id_str);
5037 goto done;
5039 free(id_str);
5040 } else if (status != GOT_STATUS_ADD) {
5041 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5042 fd1);
5043 if (err)
5044 goto done;
5047 if (status != GOT_STATUS_DELETE) {
5048 if (asprintf(&abspath, "%s/%s",
5049 got_worktree_get_root_path(a->worktree), path) == -1) {
5050 err = got_error_from_errno("asprintf");
5051 goto done;
5054 if (dirfd != -1) {
5055 fd = openat(dirfd, de_name,
5056 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5057 if (fd == -1) {
5058 if (!got_err_open_nofollow_on_symlink()) {
5059 err = got_error_from_errno2("openat",
5060 abspath);
5061 goto done;
5063 err = get_symlink_target_file(&fd, dirfd,
5064 de_name, abspath);
5065 if (err)
5066 goto done;
5068 } else {
5069 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5070 if (fd == -1) {
5071 if (!got_err_open_nofollow_on_symlink()) {
5072 err = got_error_from_errno2("open",
5073 abspath);
5074 goto done;
5076 err = get_symlink_target_file(&fd, dirfd,
5077 de_name, abspath);
5078 if (err)
5079 goto done;
5082 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5083 err = got_error_from_errno2("fstatat", abspath);
5084 goto done;
5086 f2 = fdopen(fd, "r");
5087 if (f2 == NULL) {
5088 err = got_error_from_errno2("fdopen", abspath);
5089 goto done;
5091 fd = -1;
5092 f2_exists = 1;
5095 if (blob1) {
5096 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5097 a->f1, blob1);
5098 if (err)
5099 goto done;
5102 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5103 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5104 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5105 done:
5106 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5107 err = got_error_from_errno("close");
5108 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5109 err = got_error_from_errno("close");
5110 if (blob1)
5111 got_object_blob_close(blob1);
5112 if (fd != -1 && close(fd) == -1 && err == NULL)
5113 err = got_error_from_errno("close");
5114 if (f2 && fclose(f2) == EOF && err == NULL)
5115 err = got_error_from_errno("fclose");
5116 free(abspath);
5117 return err;
5120 static const struct got_error *
5121 cmd_diff(int argc, char *argv[])
5123 const struct got_error *error;
5124 struct got_repository *repo = NULL;
5125 struct got_worktree *worktree = NULL;
5126 char *cwd = NULL, *repo_path = NULL;
5127 const char *commit_args[2] = { NULL, NULL };
5128 int ncommit_args = 0;
5129 struct got_object_id *ids[2] = { NULL, NULL };
5130 char *labels[2] = { NULL, NULL };
5131 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5132 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5133 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5134 const char *errstr;
5135 struct got_reflist_head refs;
5136 struct got_pathlist_head diffstat_paths, paths;
5137 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5138 int fd1 = -1, fd2 = -1;
5139 int *pack_fds = NULL;
5140 struct got_diffstat_cb_arg dsa;
5142 memset(&dsa, 0, sizeof(dsa));
5144 TAILQ_INIT(&refs);
5145 TAILQ_INIT(&paths);
5146 TAILQ_INIT(&diffstat_paths);
5148 #ifndef PROFILE
5149 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5150 NULL) == -1)
5151 err(1, "pledge");
5152 #endif
5154 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5155 switch (ch) {
5156 case 'a':
5157 force_text_diff = 1;
5158 break;
5159 case 'C':
5160 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5161 &errstr);
5162 if (errstr != NULL)
5163 errx(1, "number of context lines is %s: %s",
5164 errstr, optarg);
5165 break;
5166 case 'c':
5167 if (ncommit_args >= 2)
5168 errx(1, "too many -c options used");
5169 commit_args[ncommit_args++] = optarg;
5170 break;
5171 case 'd':
5172 show_diffstat = 1;
5173 break;
5174 case 'P':
5175 force_path = 1;
5176 break;
5177 case 'r':
5178 repo_path = realpath(optarg, NULL);
5179 if (repo_path == NULL)
5180 return got_error_from_errno2("realpath",
5181 optarg);
5182 got_path_strip_trailing_slashes(repo_path);
5183 rflag = 1;
5184 break;
5185 case 's':
5186 diff_staged = 1;
5187 break;
5188 case 'w':
5189 ignore_whitespace = 1;
5190 break;
5191 default:
5192 usage_diff();
5193 /* NOTREACHED */
5197 argc -= optind;
5198 argv += optind;
5200 cwd = getcwd(NULL, 0);
5201 if (cwd == NULL) {
5202 error = got_error_from_errno("getcwd");
5203 goto done;
5206 error = got_repo_pack_fds_open(&pack_fds);
5207 if (error != NULL)
5208 goto done;
5210 if (repo_path == NULL) {
5211 error = got_worktree_open(&worktree, cwd,
5212 GOT_WORKTREE_GOT_DIR);
5213 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5214 goto done;
5215 else
5216 error = NULL;
5217 if (worktree) {
5218 repo_path =
5219 strdup(got_worktree_get_repo_path(worktree));
5220 if (repo_path == NULL) {
5221 error = got_error_from_errno("strdup");
5222 goto done;
5224 } else {
5225 repo_path = strdup(cwd);
5226 if (repo_path == NULL) {
5227 error = got_error_from_errno("strdup");
5228 goto done;
5233 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5234 free(repo_path);
5235 if (error != NULL)
5236 goto done;
5238 if (show_diffstat) {
5239 dsa.paths = &diffstat_paths;
5240 dsa.force_text = force_text_diff;
5241 dsa.ignore_ws = ignore_whitespace;
5242 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5245 if (rflag || worktree == NULL || ncommit_args > 0) {
5246 if (force_path) {
5247 error = got_error_msg(GOT_ERR_NOT_IMPL,
5248 "-P option can only be used when diffing "
5249 "a work tree");
5250 goto done;
5252 if (diff_staged) {
5253 error = got_error_msg(GOT_ERR_NOT_IMPL,
5254 "-s option can only be used when diffing "
5255 "a work tree");
5256 goto done;
5260 error = apply_unveil(got_repo_get_path(repo), 1,
5261 worktree ? got_worktree_get_root_path(worktree) : NULL);
5262 if (error)
5263 goto done;
5265 if ((!force_path && argc == 2) || ncommit_args > 0) {
5266 int obj_type = (ncommit_args > 0 ?
5267 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5268 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5269 NULL);
5270 if (error)
5271 goto done;
5272 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5273 const char *arg;
5274 char *keyword_idstr = NULL;
5276 if (ncommit_args > 0)
5277 arg = commit_args[i];
5278 else
5279 arg = argv[i];
5281 error = got_keyword_to_idstr(&keyword_idstr, arg,
5282 repo, worktree);
5283 if (error != NULL)
5284 goto done;
5285 if (keyword_idstr != NULL)
5286 arg = keyword_idstr;
5288 error = got_repo_match_object_id(&ids[i], &labels[i],
5289 arg, obj_type, &refs, repo);
5290 free(keyword_idstr);
5291 if (error) {
5292 if (error->code != GOT_ERR_NOT_REF &&
5293 error->code != GOT_ERR_NO_OBJ)
5294 goto done;
5295 if (ncommit_args > 0)
5296 goto done;
5297 error = NULL;
5298 break;
5303 f1 = got_opentemp();
5304 if (f1 == NULL) {
5305 error = got_error_from_errno("got_opentemp");
5306 goto done;
5309 f2 = got_opentemp();
5310 if (f2 == NULL) {
5311 error = got_error_from_errno("got_opentemp");
5312 goto done;
5315 outfile = got_opentemp();
5316 if (outfile == NULL) {
5317 error = got_error_from_errno("got_opentemp");
5318 goto done;
5321 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5322 struct print_diff_arg arg;
5323 char *id_str;
5325 if (worktree == NULL) {
5326 if (argc == 2 && ids[0] == NULL) {
5327 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5328 goto done;
5329 } else if (argc == 2 && ids[1] == NULL) {
5330 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5331 goto done;
5332 } else if (argc > 0) {
5333 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5334 "%s", "specified paths cannot be resolved");
5335 goto done;
5336 } else {
5337 error = got_error(GOT_ERR_NOT_WORKTREE);
5338 goto done;
5342 error = get_worktree_paths_from_argv(&paths, argc, argv,
5343 worktree);
5344 if (error)
5345 goto done;
5347 error = got_object_id_str(&id_str,
5348 got_worktree_get_base_commit_id(worktree));
5349 if (error)
5350 goto done;
5351 arg.repo = repo;
5352 arg.worktree = worktree;
5353 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5354 arg.diff_context = diff_context;
5355 arg.id_str = id_str;
5356 arg.header_shown = 0;
5357 arg.diff_staged = diff_staged;
5358 arg.ignore_whitespace = ignore_whitespace;
5359 arg.force_text_diff = force_text_diff;
5360 arg.diffstat = show_diffstat ? &dsa : NULL;
5361 arg.f1 = f1;
5362 arg.f2 = f2;
5363 arg.outfile = outfile;
5365 error = got_worktree_status(worktree, &paths, repo, 0,
5366 print_diff, &arg, check_cancelled, NULL);
5367 free(id_str);
5368 if (error)
5369 goto done;
5371 if (show_diffstat && dsa.nfiles > 0) {
5372 char *header;
5374 if (asprintf(&header, "diffstat %s%s",
5375 diff_staged ? "-s " : "",
5376 got_worktree_get_root_path(worktree)) == -1) {
5377 error = got_error_from_errno("asprintf");
5378 goto done;
5381 error = print_diffstat(&dsa, header);
5382 free(header);
5383 if (error)
5384 goto done;
5387 error = printfile(outfile);
5388 goto done;
5391 if (ncommit_args == 1) {
5392 struct got_commit_object *commit;
5393 error = got_object_open_as_commit(&commit, repo, ids[0]);
5394 if (error)
5395 goto done;
5397 labels[1] = labels[0];
5398 ids[1] = ids[0];
5399 if (got_object_commit_get_nparents(commit) > 0) {
5400 const struct got_object_id_queue *pids;
5401 struct got_object_qid *pid;
5402 pids = got_object_commit_get_parent_ids(commit);
5403 pid = STAILQ_FIRST(pids);
5404 ids[0] = got_object_id_dup(&pid->id);
5405 if (ids[0] == NULL) {
5406 error = got_error_from_errno(
5407 "got_object_id_dup");
5408 got_object_commit_close(commit);
5409 goto done;
5411 error = got_object_id_str(&labels[0], ids[0]);
5412 if (error) {
5413 got_object_commit_close(commit);
5414 goto done;
5416 } else {
5417 ids[0] = NULL;
5418 labels[0] = strdup("/dev/null");
5419 if (labels[0] == NULL) {
5420 error = got_error_from_errno("strdup");
5421 got_object_commit_close(commit);
5422 goto done;
5426 got_object_commit_close(commit);
5429 if (ncommit_args == 0 && argc > 2) {
5430 error = got_error_msg(GOT_ERR_BAD_PATH,
5431 "path arguments cannot be used when diffing two objects");
5432 goto done;
5435 if (ids[0]) {
5436 error = got_object_get_type(&type1, repo, ids[0]);
5437 if (error)
5438 goto done;
5441 error = got_object_get_type(&type2, repo, ids[1]);
5442 if (error)
5443 goto done;
5444 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5445 error = got_error(GOT_ERR_OBJ_TYPE);
5446 goto done;
5448 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5449 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5450 "path arguments cannot be used when diffing blobs");
5451 goto done;
5454 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5455 char *in_repo_path;
5456 struct got_pathlist_entry *new;
5457 if (worktree) {
5458 const char *prefix;
5459 char *p;
5460 error = got_worktree_resolve_path(&p, worktree,
5461 argv[i]);
5462 if (error)
5463 goto done;
5464 prefix = got_worktree_get_path_prefix(worktree);
5465 while (prefix[0] == '/')
5466 prefix++;
5467 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5468 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5469 p) == -1) {
5470 error = got_error_from_errno("asprintf");
5471 free(p);
5472 goto done;
5474 free(p);
5475 } else {
5476 char *mapped_path, *s;
5477 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5478 if (error)
5479 goto done;
5480 s = mapped_path;
5481 while (s[0] == '/')
5482 s++;
5483 in_repo_path = strdup(s);
5484 if (in_repo_path == NULL) {
5485 error = got_error_from_errno("asprintf");
5486 free(mapped_path);
5487 goto done;
5489 free(mapped_path);
5492 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5493 if (error || new == NULL /* duplicate */)
5494 free(in_repo_path);
5495 if (error)
5496 goto done;
5499 if (worktree) {
5500 /* Release work tree lock. */
5501 got_worktree_close(worktree);
5502 worktree = NULL;
5505 fd1 = got_opentempfd();
5506 if (fd1 == -1) {
5507 error = got_error_from_errno("got_opentempfd");
5508 goto done;
5511 fd2 = got_opentempfd();
5512 if (fd2 == -1) {
5513 error = got_error_from_errno("got_opentempfd");
5514 goto done;
5517 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5518 case GOT_OBJ_TYPE_BLOB:
5519 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5520 fd1, fd2, ids[0], ids[1], NULL, NULL,
5521 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5522 ignore_whitespace, force_text_diff,
5523 show_diffstat ? &dsa : NULL, repo, outfile);
5524 break;
5525 case GOT_OBJ_TYPE_TREE:
5526 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5527 ids[0], ids[1], &paths, "", "",
5528 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5529 ignore_whitespace, force_text_diff,
5530 show_diffstat ? &dsa : NULL, repo, outfile);
5531 break;
5532 case GOT_OBJ_TYPE_COMMIT:
5533 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5534 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5535 fd1, fd2, ids[0], ids[1], &paths,
5536 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5537 ignore_whitespace, force_text_diff,
5538 show_diffstat ? &dsa : NULL, repo, outfile);
5539 break;
5540 default:
5541 error = got_error(GOT_ERR_OBJ_TYPE);
5543 if (error)
5544 goto done;
5546 if (show_diffstat && dsa.nfiles > 0) {
5547 char *header = NULL;
5549 if (asprintf(&header, "diffstat %s %s",
5550 labels[0], labels[1]) == -1) {
5551 error = got_error_from_errno("asprintf");
5552 goto done;
5555 error = print_diffstat(&dsa, header);
5556 free(header);
5557 if (error)
5558 goto done;
5561 error = printfile(outfile);
5563 done:
5564 free(labels[0]);
5565 free(labels[1]);
5566 free(ids[0]);
5567 free(ids[1]);
5568 if (worktree)
5569 got_worktree_close(worktree);
5570 if (repo) {
5571 const struct got_error *close_err = got_repo_close(repo);
5572 if (error == NULL)
5573 error = close_err;
5575 if (pack_fds) {
5576 const struct got_error *pack_err =
5577 got_repo_pack_fds_close(pack_fds);
5578 if (error == NULL)
5579 error = pack_err;
5581 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5582 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5583 got_ref_list_free(&refs);
5584 if (outfile && fclose(outfile) == EOF && error == NULL)
5585 error = got_error_from_errno("fclose");
5586 if (f1 && fclose(f1) == EOF && error == NULL)
5587 error = got_error_from_errno("fclose");
5588 if (f2 && fclose(f2) == EOF && error == NULL)
5589 error = got_error_from_errno("fclose");
5590 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5591 error = got_error_from_errno("close");
5592 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5593 error = got_error_from_errno("close");
5594 return error;
5597 __dead static void
5598 usage_blame(void)
5600 fprintf(stderr,
5601 "usage: %s blame [-c commit] [-r repository-path] path\n",
5602 getprogname());
5603 exit(1);
5606 struct blame_line {
5607 int annotated;
5608 char *id_str;
5609 char *committer;
5610 char datebuf[11]; /* YYYY-MM-DD + NUL */
5613 struct blame_cb_args {
5614 struct blame_line *lines;
5615 int nlines;
5616 int nlines_prec;
5617 int lineno_cur;
5618 off_t *line_offsets;
5619 FILE *f;
5620 struct got_repository *repo;
5623 static const struct got_error *
5624 blame_cb(void *arg, int nlines, int lineno,
5625 struct got_commit_object *commit, struct got_object_id *id)
5627 const struct got_error *err = NULL;
5628 struct blame_cb_args *a = arg;
5629 struct blame_line *bline;
5630 char *line = NULL;
5631 size_t linesize = 0;
5632 off_t offset;
5633 struct tm tm;
5634 time_t committer_time;
5636 if (nlines != a->nlines ||
5637 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5638 return got_error(GOT_ERR_RANGE);
5640 if (sigint_received)
5641 return got_error(GOT_ERR_ITER_COMPLETED);
5643 if (lineno == -1)
5644 return NULL; /* no change in this commit */
5646 /* Annotate this line. */
5647 bline = &a->lines[lineno - 1];
5648 if (bline->annotated)
5649 return NULL;
5650 err = got_object_id_str(&bline->id_str, id);
5651 if (err)
5652 return err;
5654 bline->committer = strdup(got_object_commit_get_committer(commit));
5655 if (bline->committer == NULL) {
5656 err = got_error_from_errno("strdup");
5657 goto done;
5660 committer_time = got_object_commit_get_committer_time(commit);
5661 if (gmtime_r(&committer_time, &tm) == NULL)
5662 return got_error_from_errno("gmtime_r");
5663 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5664 &tm) == 0) {
5665 err = got_error(GOT_ERR_NO_SPACE);
5666 goto done;
5668 bline->annotated = 1;
5670 /* Print lines annotated so far. */
5671 bline = &a->lines[a->lineno_cur - 1];
5672 if (!bline->annotated)
5673 goto done;
5675 offset = a->line_offsets[a->lineno_cur - 1];
5676 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5677 err = got_error_from_errno("fseeko");
5678 goto done;
5681 while (a->lineno_cur <= a->nlines && bline->annotated) {
5682 char *smallerthan, *at, *nl, *committer;
5683 size_t len;
5685 if (getline(&line, &linesize, a->f) == -1) {
5686 if (ferror(a->f))
5687 err = got_error_from_errno("getline");
5688 break;
5691 committer = bline->committer;
5692 smallerthan = strchr(committer, '<');
5693 if (smallerthan && smallerthan[1] != '\0')
5694 committer = smallerthan + 1;
5695 at = strchr(committer, '@');
5696 if (at)
5697 *at = '\0';
5698 len = strlen(committer);
5699 if (len >= 9)
5700 committer[8] = '\0';
5702 nl = strchr(line, '\n');
5703 if (nl)
5704 *nl = '\0';
5705 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5706 bline->id_str, bline->datebuf, committer, line);
5708 a->lineno_cur++;
5709 bline = &a->lines[a->lineno_cur - 1];
5711 done:
5712 free(line);
5713 return err;
5716 static const struct got_error *
5717 cmd_blame(int argc, char *argv[])
5719 const struct got_error *error;
5720 struct got_repository *repo = NULL;
5721 struct got_worktree *worktree = NULL;
5722 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5723 char *link_target = NULL;
5724 struct got_object_id *obj_id = NULL;
5725 struct got_object_id *commit_id = NULL;
5726 struct got_commit_object *commit = NULL;
5727 struct got_blob_object *blob = NULL;
5728 char *commit_id_str = NULL, *keyword_idstr = NULL;
5729 struct blame_cb_args bca;
5730 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5731 off_t filesize;
5732 int *pack_fds = NULL;
5733 FILE *f1 = NULL, *f2 = NULL;
5735 fd1 = got_opentempfd();
5736 if (fd1 == -1)
5737 return got_error_from_errno("got_opentempfd");
5739 memset(&bca, 0, sizeof(bca));
5741 #ifndef PROFILE
5742 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5743 NULL) == -1)
5744 err(1, "pledge");
5745 #endif
5747 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5748 switch (ch) {
5749 case 'c':
5750 commit_id_str = optarg;
5751 break;
5752 case 'r':
5753 repo_path = realpath(optarg, NULL);
5754 if (repo_path == NULL)
5755 return got_error_from_errno2("realpath",
5756 optarg);
5757 got_path_strip_trailing_slashes(repo_path);
5758 break;
5759 default:
5760 usage_blame();
5761 /* NOTREACHED */
5765 argc -= optind;
5766 argv += optind;
5768 if (argc == 1)
5769 path = argv[0];
5770 else
5771 usage_blame();
5773 cwd = getcwd(NULL, 0);
5774 if (cwd == NULL) {
5775 error = got_error_from_errno("getcwd");
5776 goto done;
5779 error = got_repo_pack_fds_open(&pack_fds);
5780 if (error != NULL)
5781 goto done;
5783 if (repo_path == NULL) {
5784 error = got_worktree_open(&worktree, cwd,
5785 GOT_WORKTREE_GOT_DIR);
5786 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5787 goto done;
5788 else
5789 error = NULL;
5790 if (worktree) {
5791 repo_path =
5792 strdup(got_worktree_get_repo_path(worktree));
5793 if (repo_path == NULL) {
5794 error = got_error_from_errno("strdup");
5795 if (error)
5796 goto done;
5798 } else {
5799 repo_path = strdup(cwd);
5800 if (repo_path == NULL) {
5801 error = got_error_from_errno("strdup");
5802 goto done;
5807 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5808 if (error != NULL)
5809 goto done;
5811 if (worktree) {
5812 const char *prefix = got_worktree_get_path_prefix(worktree);
5813 char *p;
5815 error = got_worktree_resolve_path(&p, worktree, path);
5816 if (error)
5817 goto done;
5818 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5819 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5820 p) == -1) {
5821 error = got_error_from_errno("asprintf");
5822 free(p);
5823 goto done;
5825 free(p);
5826 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5827 } else {
5828 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5829 if (error)
5830 goto done;
5831 error = got_repo_map_path(&in_repo_path, repo, path);
5833 if (error)
5834 goto done;
5836 if (commit_id_str == NULL) {
5837 struct got_reference *head_ref;
5838 error = got_ref_open(&head_ref, repo, worktree ?
5839 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5840 if (error != NULL)
5841 goto done;
5842 error = got_ref_resolve(&commit_id, repo, head_ref);
5843 got_ref_close(head_ref);
5844 if (error != NULL)
5845 goto done;
5846 } else {
5847 struct got_reflist_head refs;
5849 TAILQ_INIT(&refs);
5850 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5851 NULL);
5852 if (error)
5853 goto done;
5855 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5856 repo, worktree);
5857 if (error != NULL)
5858 goto done;
5859 if (keyword_idstr != NULL)
5860 commit_id_str = keyword_idstr;
5862 error = got_repo_match_object_id(&commit_id, NULL,
5863 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5864 got_ref_list_free(&refs);
5865 if (error)
5866 goto done;
5869 if (worktree) {
5870 /* Release work tree lock. */
5871 got_worktree_close(worktree);
5872 worktree = NULL;
5875 error = got_object_open_as_commit(&commit, repo, commit_id);
5876 if (error)
5877 goto done;
5879 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5880 commit, repo);
5881 if (error)
5882 goto done;
5884 error = got_object_id_by_path(&obj_id, repo, commit,
5885 link_target ? link_target : in_repo_path);
5886 if (error)
5887 goto done;
5889 error = got_object_get_type(&obj_type, repo, obj_id);
5890 if (error)
5891 goto done;
5893 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5894 error = got_error_path(link_target ? link_target : in_repo_path,
5895 GOT_ERR_OBJ_TYPE);
5896 goto done;
5899 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5900 if (error)
5901 goto done;
5902 bca.f = got_opentemp();
5903 if (bca.f == NULL) {
5904 error = got_error_from_errno("got_opentemp");
5905 goto done;
5907 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5908 &bca.line_offsets, bca.f, blob);
5909 if (error || bca.nlines == 0)
5910 goto done;
5912 /* Don't include \n at EOF in the blame line count. */
5913 if (bca.line_offsets[bca.nlines - 1] == filesize)
5914 bca.nlines--;
5916 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5917 if (bca.lines == NULL) {
5918 error = got_error_from_errno("calloc");
5919 goto done;
5921 bca.lineno_cur = 1;
5922 bca.nlines_prec = 0;
5923 i = bca.nlines;
5924 while (i > 0) {
5925 i /= 10;
5926 bca.nlines_prec++;
5928 bca.repo = repo;
5930 fd2 = got_opentempfd();
5931 if (fd2 == -1) {
5932 error = got_error_from_errno("got_opentempfd");
5933 goto done;
5935 fd3 = got_opentempfd();
5936 if (fd3 == -1) {
5937 error = got_error_from_errno("got_opentempfd");
5938 goto done;
5940 f1 = got_opentemp();
5941 if (f1 == NULL) {
5942 error = got_error_from_errno("got_opentemp");
5943 goto done;
5945 f2 = got_opentemp();
5946 if (f2 == NULL) {
5947 error = got_error_from_errno("got_opentemp");
5948 goto done;
5950 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5951 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5952 check_cancelled, NULL, fd2, fd3, f1, f2);
5953 done:
5954 free(keyword_idstr);
5955 free(in_repo_path);
5956 free(link_target);
5957 free(repo_path);
5958 free(cwd);
5959 free(commit_id);
5960 free(obj_id);
5961 if (commit)
5962 got_object_commit_close(commit);
5964 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5965 error = got_error_from_errno("close");
5966 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5967 error = got_error_from_errno("close");
5968 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5969 error = got_error_from_errno("close");
5970 if (f1 && fclose(f1) == EOF && error == NULL)
5971 error = got_error_from_errno("fclose");
5972 if (f2 && fclose(f2) == EOF && error == NULL)
5973 error = got_error_from_errno("fclose");
5975 if (blob)
5976 got_object_blob_close(blob);
5977 if (worktree)
5978 got_worktree_close(worktree);
5979 if (repo) {
5980 const struct got_error *close_err = got_repo_close(repo);
5981 if (error == NULL)
5982 error = close_err;
5984 if (pack_fds) {
5985 const struct got_error *pack_err =
5986 got_repo_pack_fds_close(pack_fds);
5987 if (error == NULL)
5988 error = pack_err;
5990 if (bca.lines) {
5991 for (i = 0; i < bca.nlines; i++) {
5992 struct blame_line *bline = &bca.lines[i];
5993 free(bline->id_str);
5994 free(bline->committer);
5996 free(bca.lines);
5998 free(bca.line_offsets);
5999 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6000 error = got_error_from_errno("fclose");
6001 return error;
6004 __dead static void
6005 usage_tree(void)
6007 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6008 "[path]\n", getprogname());
6009 exit(1);
6012 static const struct got_error *
6013 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6014 const char *root_path, struct got_repository *repo)
6016 const struct got_error *err = NULL;
6017 int is_root_path = (strcmp(path, root_path) == 0);
6018 const char *modestr = "";
6019 mode_t mode = got_tree_entry_get_mode(te);
6020 char *link_target = NULL;
6022 path += strlen(root_path);
6023 while (path[0] == '/')
6024 path++;
6026 if (got_object_tree_entry_is_submodule(te))
6027 modestr = "$";
6028 else if (S_ISLNK(mode)) {
6029 int i;
6031 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6032 if (err)
6033 return err;
6034 for (i = 0; link_target[i] != '\0'; i++) {
6035 if (!isprint((unsigned char)link_target[i]))
6036 link_target[i] = '?';
6039 modestr = "@";
6041 else if (S_ISDIR(mode))
6042 modestr = "/";
6043 else if (mode & S_IXUSR)
6044 modestr = "*";
6046 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6047 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6048 link_target ? " -> ": "", link_target ? link_target : "");
6050 free(link_target);
6051 return NULL;
6054 static const struct got_error *
6055 print_tree(const char *path, struct got_commit_object *commit,
6056 int show_ids, int recurse, const char *root_path,
6057 struct got_repository *repo)
6059 const struct got_error *err = NULL;
6060 struct got_object_id *tree_id = NULL;
6061 struct got_tree_object *tree = NULL;
6062 int nentries, i;
6064 err = got_object_id_by_path(&tree_id, repo, commit, path);
6065 if (err)
6066 goto done;
6068 err = got_object_open_as_tree(&tree, repo, tree_id);
6069 if (err)
6070 goto done;
6071 nentries = got_object_tree_get_nentries(tree);
6072 for (i = 0; i < nentries; i++) {
6073 struct got_tree_entry *te;
6074 char *id = NULL;
6076 if (sigint_received || sigpipe_received)
6077 break;
6079 te = got_object_tree_get_entry(tree, i);
6080 if (show_ids) {
6081 char *id_str;
6082 err = got_object_id_str(&id_str,
6083 got_tree_entry_get_id(te));
6084 if (err)
6085 goto done;
6086 if (asprintf(&id, "%s ", id_str) == -1) {
6087 err = got_error_from_errno("asprintf");
6088 free(id_str);
6089 goto done;
6091 free(id_str);
6093 err = print_entry(te, id, path, root_path, repo);
6094 free(id);
6095 if (err)
6096 goto done;
6098 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6099 char *child_path;
6100 if (asprintf(&child_path, "%s%s%s", path,
6101 path[0] == '/' && path[1] == '\0' ? "" : "/",
6102 got_tree_entry_get_name(te)) == -1) {
6103 err = got_error_from_errno("asprintf");
6104 goto done;
6106 err = print_tree(child_path, commit, show_ids, 1,
6107 root_path, repo);
6108 free(child_path);
6109 if (err)
6110 goto done;
6113 done:
6114 if (tree)
6115 got_object_tree_close(tree);
6116 free(tree_id);
6117 return err;
6120 static const struct got_error *
6121 cmd_tree(int argc, char *argv[])
6123 const struct got_error *error;
6124 struct got_repository *repo = NULL;
6125 struct got_worktree *worktree = NULL;
6126 const char *path, *refname = NULL;
6127 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6128 struct got_object_id *commit_id = NULL;
6129 struct got_commit_object *commit = NULL;
6130 char *commit_id_str = NULL, *keyword_idstr = NULL;
6131 int show_ids = 0, recurse = 0;
6132 int ch;
6133 int *pack_fds = NULL;
6135 #ifndef PROFILE
6136 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6137 NULL) == -1)
6138 err(1, "pledge");
6139 #endif
6141 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6142 switch (ch) {
6143 case 'c':
6144 commit_id_str = optarg;
6145 break;
6146 case 'i':
6147 show_ids = 1;
6148 break;
6149 case 'R':
6150 recurse = 1;
6151 break;
6152 case 'r':
6153 repo_path = realpath(optarg, NULL);
6154 if (repo_path == NULL)
6155 return got_error_from_errno2("realpath",
6156 optarg);
6157 got_path_strip_trailing_slashes(repo_path);
6158 break;
6159 default:
6160 usage_tree();
6161 /* NOTREACHED */
6165 argc -= optind;
6166 argv += optind;
6168 if (argc == 1)
6169 path = argv[0];
6170 else if (argc > 1)
6171 usage_tree();
6172 else
6173 path = NULL;
6175 cwd = getcwd(NULL, 0);
6176 if (cwd == NULL) {
6177 error = got_error_from_errno("getcwd");
6178 goto done;
6181 error = got_repo_pack_fds_open(&pack_fds);
6182 if (error != NULL)
6183 goto done;
6185 if (repo_path == NULL) {
6186 error = got_worktree_open(&worktree, cwd,
6187 GOT_WORKTREE_GOT_DIR);
6188 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6189 goto done;
6190 else
6191 error = NULL;
6192 if (worktree) {
6193 repo_path =
6194 strdup(got_worktree_get_repo_path(worktree));
6195 if (repo_path == NULL)
6196 error = got_error_from_errno("strdup");
6197 if (error)
6198 goto done;
6199 } else {
6200 repo_path = strdup(cwd);
6201 if (repo_path == NULL) {
6202 error = got_error_from_errno("strdup");
6203 goto done;
6208 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6209 if (error != NULL)
6210 goto done;
6212 if (worktree) {
6213 const char *prefix = got_worktree_get_path_prefix(worktree);
6214 char *p;
6216 if (path == NULL || got_path_is_root_dir(path))
6217 path = "";
6218 error = got_worktree_resolve_path(&p, worktree, path);
6219 if (error)
6220 goto done;
6221 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6222 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6223 p) == -1) {
6224 error = got_error_from_errno("asprintf");
6225 free(p);
6226 goto done;
6228 free(p);
6229 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6230 if (error)
6231 goto done;
6232 } else {
6233 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6234 if (error)
6235 goto done;
6236 if (path == NULL)
6237 path = "/";
6238 error = got_repo_map_path(&in_repo_path, repo, path);
6239 if (error != NULL)
6240 goto done;
6243 if (commit_id_str == NULL) {
6244 struct got_reference *head_ref;
6245 if (worktree)
6246 refname = got_worktree_get_head_ref_name(worktree);
6247 else
6248 refname = GOT_REF_HEAD;
6249 error = got_ref_open(&head_ref, repo, refname, 0);
6250 if (error != NULL)
6251 goto done;
6252 error = got_ref_resolve(&commit_id, repo, head_ref);
6253 got_ref_close(head_ref);
6254 if (error != NULL)
6255 goto done;
6256 } else {
6257 struct got_reflist_head refs;
6259 TAILQ_INIT(&refs);
6260 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6261 NULL);
6262 if (error)
6263 goto done;
6265 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6266 repo, worktree);
6267 if (error != NULL)
6268 goto done;
6269 if (keyword_idstr != NULL)
6270 commit_id_str = keyword_idstr;
6272 error = got_repo_match_object_id(&commit_id, NULL,
6273 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6274 got_ref_list_free(&refs);
6275 if (error)
6276 goto done;
6279 if (worktree) {
6280 /* Release work tree lock. */
6281 got_worktree_close(worktree);
6282 worktree = NULL;
6285 error = got_object_open_as_commit(&commit, repo, commit_id);
6286 if (error)
6287 goto done;
6289 error = print_tree(in_repo_path, commit, show_ids, recurse,
6290 in_repo_path, repo);
6291 done:
6292 free(keyword_idstr);
6293 free(in_repo_path);
6294 free(repo_path);
6295 free(cwd);
6296 free(commit_id);
6297 if (commit)
6298 got_object_commit_close(commit);
6299 if (worktree)
6300 got_worktree_close(worktree);
6301 if (repo) {
6302 const struct got_error *close_err = got_repo_close(repo);
6303 if (error == NULL)
6304 error = close_err;
6306 if (pack_fds) {
6307 const struct got_error *pack_err =
6308 got_repo_pack_fds_close(pack_fds);
6309 if (error == NULL)
6310 error = pack_err;
6312 return error;
6315 __dead static void
6316 usage_status(void)
6318 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6319 "[-s status-codes] [path ...]\n", getprogname());
6320 exit(1);
6323 struct got_status_arg {
6324 char *status_codes;
6325 int suppress;
6328 static const struct got_error *
6329 print_status(void *arg, unsigned char status, unsigned char staged_status,
6330 const char *path, struct got_object_id *blob_id,
6331 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6332 int dirfd, const char *de_name)
6334 struct got_status_arg *st = arg;
6336 if (status == staged_status && (status == GOT_STATUS_DELETE))
6337 status = GOT_STATUS_NO_CHANGE;
6338 if (st != NULL && st->status_codes) {
6339 size_t ncodes = strlen(st->status_codes);
6340 int i, j = 0;
6342 for (i = 0; i < ncodes ; i++) {
6343 if (st->suppress) {
6344 if (status == st->status_codes[i] ||
6345 staged_status == st->status_codes[i]) {
6346 j++;
6347 continue;
6349 } else {
6350 if (status == st->status_codes[i] ||
6351 staged_status == st->status_codes[i])
6352 break;
6356 if (st->suppress && j == 0)
6357 goto print;
6359 if (i == ncodes)
6360 return NULL;
6362 print:
6363 printf("%c%c %s\n", status, staged_status, path);
6364 return NULL;
6367 static const struct got_error *
6368 cmd_status(int argc, char *argv[])
6370 const struct got_error *error = NULL;
6371 struct got_repository *repo = NULL;
6372 struct got_worktree *worktree = NULL;
6373 struct got_status_arg st;
6374 char *cwd = NULL;
6375 struct got_pathlist_head paths;
6376 int ch, i, no_ignores = 0;
6377 int *pack_fds = NULL;
6379 TAILQ_INIT(&paths);
6381 memset(&st, 0, sizeof(st));
6382 st.status_codes = NULL;
6383 st.suppress = 0;
6385 #ifndef PROFILE
6386 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6387 NULL) == -1)
6388 err(1, "pledge");
6389 #endif
6391 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6392 switch (ch) {
6393 case 'I':
6394 no_ignores = 1;
6395 break;
6396 case 'S':
6397 if (st.status_codes != NULL && st.suppress == 0)
6398 option_conflict('S', 's');
6399 st.suppress = 1;
6400 /* fallthrough */
6401 case 's':
6402 for (i = 0; optarg[i] != '\0'; i++) {
6403 switch (optarg[i]) {
6404 case GOT_STATUS_MODIFY:
6405 case GOT_STATUS_ADD:
6406 case GOT_STATUS_DELETE:
6407 case GOT_STATUS_CONFLICT:
6408 case GOT_STATUS_MISSING:
6409 case GOT_STATUS_OBSTRUCTED:
6410 case GOT_STATUS_UNVERSIONED:
6411 case GOT_STATUS_MODE_CHANGE:
6412 case GOT_STATUS_NONEXISTENT:
6413 break;
6414 default:
6415 errx(1, "invalid status code '%c'",
6416 optarg[i]);
6419 if (ch == 's' && st.suppress)
6420 option_conflict('s', 'S');
6421 st.status_codes = optarg;
6422 break;
6423 default:
6424 usage_status();
6425 /* NOTREACHED */
6429 argc -= optind;
6430 argv += optind;
6432 cwd = getcwd(NULL, 0);
6433 if (cwd == NULL) {
6434 error = got_error_from_errno("getcwd");
6435 goto done;
6438 error = got_repo_pack_fds_open(&pack_fds);
6439 if (error != NULL)
6440 goto done;
6442 error = got_worktree_open(&worktree, cwd,
6443 GOT_WORKTREE_GOT_DIR);
6444 if (error) {
6445 if (error->code == GOT_ERR_NOT_WORKTREE)
6446 error = wrap_not_worktree_error(error, "status", cwd);
6447 goto done;
6450 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6451 NULL, pack_fds);
6452 if (error != NULL)
6453 goto done;
6455 error = apply_unveil(got_repo_get_path(repo), 1,
6456 got_worktree_get_root_path(worktree));
6457 if (error)
6458 goto done;
6460 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6461 if (error)
6462 goto done;
6464 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6465 print_status, &st, check_cancelled, NULL);
6466 done:
6467 if (pack_fds) {
6468 const struct got_error *pack_err =
6469 got_repo_pack_fds_close(pack_fds);
6470 if (error == NULL)
6471 error = pack_err;
6473 if (repo) {
6474 const struct got_error *close_err = got_repo_close(repo);
6475 if (error == NULL)
6476 error = close_err;
6479 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6480 free(cwd);
6481 return error;
6484 __dead static void
6485 usage_ref(void)
6487 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6488 "[-s reference] [name]\n", getprogname());
6489 exit(1);
6492 static const struct got_error *
6493 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6495 static const struct got_error *err = NULL;
6496 struct got_reflist_head refs;
6497 struct got_reflist_entry *re;
6499 TAILQ_INIT(&refs);
6500 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6501 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6502 repo);
6503 if (err)
6504 return err;
6506 TAILQ_FOREACH(re, &refs, entry) {
6507 char *refstr;
6508 refstr = got_ref_to_str(re->ref);
6509 if (refstr == NULL) {
6510 err = got_error_from_errno("got_ref_to_str");
6511 break;
6513 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6514 free(refstr);
6517 got_ref_list_free(&refs);
6518 return err;
6521 static const struct got_error *
6522 delete_ref_by_name(struct got_repository *repo, const char *refname)
6524 const struct got_error *err;
6525 struct got_reference *ref;
6527 err = got_ref_open(&ref, repo, refname, 0);
6528 if (err)
6529 return err;
6531 err = delete_ref(repo, ref);
6532 got_ref_close(ref);
6533 return err;
6536 static const struct got_error *
6537 add_ref(struct got_repository *repo, const char *refname, const char *target)
6539 const struct got_error *err = NULL;
6540 struct got_object_id *id = NULL;
6541 struct got_reference *ref = NULL;
6542 struct got_reflist_head refs;
6545 * Don't let the user create a reference name with a leading '-'.
6546 * While technically a valid reference name, this case is usually
6547 * an unintended typo.
6549 if (refname[0] == '-')
6550 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6552 TAILQ_INIT(&refs);
6553 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6554 if (err)
6555 goto done;
6556 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6557 &refs, repo);
6558 got_ref_list_free(&refs);
6559 if (err)
6560 goto done;
6562 err = got_ref_alloc(&ref, refname, id);
6563 if (err)
6564 goto done;
6566 err = got_ref_write(ref, repo);
6567 done:
6568 if (ref)
6569 got_ref_close(ref);
6570 free(id);
6571 return err;
6574 static const struct got_error *
6575 add_symref(struct got_repository *repo, const char *refname, const char *target)
6577 const struct got_error *err = NULL;
6578 struct got_reference *ref = NULL;
6579 struct got_reference *target_ref = NULL;
6582 * Don't let the user create a reference name with a leading '-'.
6583 * While technically a valid reference name, this case is usually
6584 * an unintended typo.
6586 if (refname[0] == '-')
6587 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6589 err = got_ref_open(&target_ref, repo, target, 0);
6590 if (err)
6591 return err;
6593 err = got_ref_alloc_symref(&ref, refname, target_ref);
6594 if (err)
6595 goto done;
6597 err = got_ref_write(ref, repo);
6598 done:
6599 if (target_ref)
6600 got_ref_close(target_ref);
6601 if (ref)
6602 got_ref_close(ref);
6603 return err;
6606 static const struct got_error *
6607 cmd_ref(int argc, char *argv[])
6609 const struct got_error *error = NULL;
6610 struct got_repository *repo = NULL;
6611 struct got_worktree *worktree = NULL;
6612 char *cwd = NULL, *repo_path = NULL;
6613 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6614 const char *obj_arg = NULL, *symref_target= NULL;
6615 char *refname = NULL, *keyword_idstr = NULL;
6616 int *pack_fds = NULL;
6618 #ifndef PROFILE
6619 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6620 "sendfd unveil", NULL) == -1)
6621 err(1, "pledge");
6622 #endif
6624 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6625 switch (ch) {
6626 case 'c':
6627 obj_arg = optarg;
6628 break;
6629 case 'd':
6630 do_delete = 1;
6631 break;
6632 case 'l':
6633 do_list = 1;
6634 break;
6635 case 'r':
6636 repo_path = realpath(optarg, NULL);
6637 if (repo_path == NULL)
6638 return got_error_from_errno2("realpath",
6639 optarg);
6640 got_path_strip_trailing_slashes(repo_path);
6641 break;
6642 case 's':
6643 symref_target = optarg;
6644 break;
6645 case 't':
6646 sort_by_time = 1;
6647 break;
6648 default:
6649 usage_ref();
6650 /* NOTREACHED */
6654 if (obj_arg && do_list)
6655 option_conflict('c', 'l');
6656 if (obj_arg && do_delete)
6657 option_conflict('c', 'd');
6658 if (obj_arg && symref_target)
6659 option_conflict('c', 's');
6660 if (symref_target && do_delete)
6661 option_conflict('s', 'd');
6662 if (symref_target && do_list)
6663 option_conflict('s', 'l');
6664 if (do_delete && do_list)
6665 option_conflict('d', 'l');
6666 if (sort_by_time && !do_list)
6667 errx(1, "-t option requires -l option");
6669 argc -= optind;
6670 argv += optind;
6672 if (do_list) {
6673 if (argc != 0 && argc != 1)
6674 usage_ref();
6675 if (argc == 1) {
6676 refname = strdup(argv[0]);
6677 if (refname == NULL) {
6678 error = got_error_from_errno("strdup");
6679 goto done;
6682 } else {
6683 if (argc != 1)
6684 usage_ref();
6685 refname = strdup(argv[0]);
6686 if (refname == NULL) {
6687 error = got_error_from_errno("strdup");
6688 goto done;
6692 if (refname)
6693 got_path_strip_trailing_slashes(refname);
6695 cwd = getcwd(NULL, 0);
6696 if (cwd == NULL) {
6697 error = got_error_from_errno("getcwd");
6698 goto done;
6701 error = got_repo_pack_fds_open(&pack_fds);
6702 if (error != NULL)
6703 goto done;
6705 if (repo_path == NULL) {
6706 error = got_worktree_open(&worktree, cwd,
6707 GOT_WORKTREE_GOT_DIR);
6708 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6709 goto done;
6710 else
6711 error = NULL;
6712 if (worktree) {
6713 repo_path =
6714 strdup(got_worktree_get_repo_path(worktree));
6715 if (repo_path == NULL)
6716 error = got_error_from_errno("strdup");
6717 if (error)
6718 goto done;
6719 } else {
6720 repo_path = strdup(cwd);
6721 if (repo_path == NULL) {
6722 error = got_error_from_errno("strdup");
6723 goto done;
6728 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6729 if (error != NULL)
6730 goto done;
6732 #ifndef PROFILE
6733 if (do_list) {
6734 /* Remove "cpath" promise. */
6735 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6736 NULL) == -1)
6737 err(1, "pledge");
6739 #endif
6741 error = apply_unveil(got_repo_get_path(repo), do_list,
6742 worktree ? got_worktree_get_root_path(worktree) : NULL);
6743 if (error)
6744 goto done;
6746 if (do_list)
6747 error = list_refs(repo, refname, sort_by_time);
6748 else if (do_delete)
6749 error = delete_ref_by_name(repo, refname);
6750 else if (symref_target)
6751 error = add_symref(repo, refname, symref_target);
6752 else {
6753 if (obj_arg == NULL)
6754 usage_ref();
6756 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6757 repo, worktree);
6758 if (error != NULL)
6759 goto done;
6760 if (keyword_idstr != NULL)
6761 obj_arg = keyword_idstr;
6763 error = add_ref(repo, refname, obj_arg);
6765 done:
6766 free(refname);
6767 if (repo) {
6768 const struct got_error *close_err = got_repo_close(repo);
6769 if (error == NULL)
6770 error = close_err;
6772 if (worktree)
6773 got_worktree_close(worktree);
6774 if (pack_fds) {
6775 const struct got_error *pack_err =
6776 got_repo_pack_fds_close(pack_fds);
6777 if (error == NULL)
6778 error = pack_err;
6780 free(cwd);
6781 free(repo_path);
6782 free(keyword_idstr);
6783 return error;
6786 __dead static void
6787 usage_branch(void)
6789 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6790 "[-r repository-path] [name]\n", getprogname());
6791 exit(1);
6794 static const struct got_error *
6795 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6796 struct got_reference *ref)
6798 const struct got_error *err = NULL;
6799 const char *refname, *marker = " ";
6800 char *refstr;
6802 refname = got_ref_get_name(ref);
6803 if (worktree && strcmp(refname,
6804 got_worktree_get_head_ref_name(worktree)) == 0) {
6805 struct got_object_id *id = NULL;
6807 err = got_ref_resolve(&id, repo, ref);
6808 if (err)
6809 return err;
6810 if (got_object_id_cmp(id,
6811 got_worktree_get_base_commit_id(worktree)) == 0)
6812 marker = "* ";
6813 else
6814 marker = "~ ";
6815 free(id);
6818 if (strncmp(refname, "refs/heads/", 11) == 0)
6819 refname += 11;
6820 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6821 refname += 18;
6822 if (strncmp(refname, "refs/remotes/", 13) == 0)
6823 refname += 13;
6825 refstr = got_ref_to_str(ref);
6826 if (refstr == NULL)
6827 return got_error_from_errno("got_ref_to_str");
6829 printf("%s%s: %s\n", marker, refname, refstr);
6830 free(refstr);
6831 return NULL;
6834 static const struct got_error *
6835 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6837 const char *refname;
6839 if (worktree == NULL)
6840 return got_error(GOT_ERR_NOT_WORKTREE);
6842 refname = got_worktree_get_head_ref_name(worktree);
6844 if (strncmp(refname, "refs/heads/", 11) == 0)
6845 refname += 11;
6846 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6847 refname += 18;
6849 printf("%s\n", refname);
6851 return NULL;
6854 static const struct got_error *
6855 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6856 int sort_by_time)
6858 static const struct got_error *err = NULL;
6859 struct got_reflist_head refs;
6860 struct got_reflist_entry *re;
6861 struct got_reference *temp_ref = NULL;
6862 int rebase_in_progress, histedit_in_progress;
6864 TAILQ_INIT(&refs);
6866 if (worktree) {
6867 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6868 worktree);
6869 if (err)
6870 return err;
6872 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6873 worktree);
6874 if (err)
6875 return err;
6877 if (rebase_in_progress || histedit_in_progress) {
6878 err = got_ref_open(&temp_ref, repo,
6879 got_worktree_get_head_ref_name(worktree), 0);
6880 if (err)
6881 return err;
6882 list_branch(repo, worktree, temp_ref);
6883 got_ref_close(temp_ref);
6887 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6888 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6889 repo);
6890 if (err)
6891 return err;
6893 TAILQ_FOREACH(re, &refs, entry)
6894 list_branch(repo, worktree, re->ref);
6896 got_ref_list_free(&refs);
6898 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6899 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6900 repo);
6901 if (err)
6902 return err;
6904 TAILQ_FOREACH(re, &refs, entry)
6905 list_branch(repo, worktree, re->ref);
6907 got_ref_list_free(&refs);
6909 return NULL;
6912 static const struct got_error *
6913 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6914 const char *branch_name)
6916 const struct got_error *err = NULL;
6917 struct got_reference *ref = NULL;
6918 char *refname, *remote_refname = NULL;
6920 if (strncmp(branch_name, "refs/", 5) == 0)
6921 branch_name += 5;
6922 if (strncmp(branch_name, "heads/", 6) == 0)
6923 branch_name += 6;
6924 else if (strncmp(branch_name, "remotes/", 8) == 0)
6925 branch_name += 8;
6927 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6928 return got_error_from_errno("asprintf");
6930 if (asprintf(&remote_refname, "refs/remotes/%s",
6931 branch_name) == -1) {
6932 err = got_error_from_errno("asprintf");
6933 goto done;
6936 err = got_ref_open(&ref, repo, refname, 0);
6937 if (err) {
6938 const struct got_error *err2;
6939 if (err->code != GOT_ERR_NOT_REF)
6940 goto done;
6942 * Keep 'err' intact such that if neither branch exists
6943 * we report "refs/heads" rather than "refs/remotes" in
6944 * our error message.
6946 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6947 if (err2)
6948 goto done;
6949 err = NULL;
6952 if (worktree &&
6953 strcmp(got_worktree_get_head_ref_name(worktree),
6954 got_ref_get_name(ref)) == 0) {
6955 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6956 "will not delete this work tree's current branch");
6957 goto done;
6960 err = delete_ref(repo, ref);
6961 done:
6962 if (ref)
6963 got_ref_close(ref);
6964 free(refname);
6965 free(remote_refname);
6966 return err;
6969 static const struct got_error *
6970 add_branch(struct got_repository *repo, const char *branch_name,
6971 struct got_object_id *base_commit_id)
6973 const struct got_error *err = NULL;
6974 struct got_reference *ref = NULL;
6975 char *refname = NULL;
6978 * Don't let the user create a branch name with a leading '-'.
6979 * While technically a valid reference name, this case is usually
6980 * an unintended typo.
6982 if (branch_name[0] == '-')
6983 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6985 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6986 branch_name += 11;
6988 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6989 err = got_error_from_errno("asprintf");
6990 goto done;
6993 err = got_ref_open(&ref, repo, refname, 0);
6994 if (err == NULL) {
6995 err = got_error(GOT_ERR_BRANCH_EXISTS);
6996 goto done;
6997 } else if (err->code != GOT_ERR_NOT_REF)
6998 goto done;
7000 err = got_ref_alloc(&ref, refname, base_commit_id);
7001 if (err)
7002 goto done;
7004 err = got_ref_write(ref, repo);
7005 done:
7006 if (ref)
7007 got_ref_close(ref);
7008 free(refname);
7009 return err;
7012 static const struct got_error *
7013 cmd_branch(int argc, char *argv[])
7015 const struct got_error *error = NULL;
7016 struct got_repository *repo = NULL;
7017 struct got_worktree *worktree = NULL;
7018 char *cwd = NULL, *repo_path = NULL;
7019 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7020 const char *delref = NULL, *commit_id_arg = NULL;
7021 struct got_reference *ref = NULL;
7022 struct got_pathlist_head paths;
7023 struct got_object_id *commit_id = NULL;
7024 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7025 int *pack_fds = NULL;
7027 TAILQ_INIT(&paths);
7029 #ifndef PROFILE
7030 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7031 "sendfd unveil", NULL) == -1)
7032 err(1, "pledge");
7033 #endif
7035 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7036 switch (ch) {
7037 case 'c':
7038 commit_id_arg = optarg;
7039 break;
7040 case 'd':
7041 delref = optarg;
7042 break;
7043 case 'l':
7044 do_list = 1;
7045 break;
7046 case 'n':
7047 do_update = 0;
7048 break;
7049 case 'r':
7050 repo_path = realpath(optarg, NULL);
7051 if (repo_path == NULL)
7052 return got_error_from_errno2("realpath",
7053 optarg);
7054 got_path_strip_trailing_slashes(repo_path);
7055 break;
7056 case 't':
7057 sort_by_time = 1;
7058 break;
7059 default:
7060 usage_branch();
7061 /* NOTREACHED */
7065 if (do_list && delref)
7066 option_conflict('l', 'd');
7067 if (sort_by_time && !do_list)
7068 errx(1, "-t option requires -l option");
7070 argc -= optind;
7071 argv += optind;
7073 if (!do_list && !delref && argc == 0)
7074 do_show = 1;
7076 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7077 errx(1, "-c option can only be used when creating a branch");
7079 if (do_list || delref) {
7080 if (argc > 0)
7081 usage_branch();
7082 } else if (!do_show && argc != 1)
7083 usage_branch();
7085 cwd = getcwd(NULL, 0);
7086 if (cwd == NULL) {
7087 error = got_error_from_errno("getcwd");
7088 goto done;
7091 error = got_repo_pack_fds_open(&pack_fds);
7092 if (error != NULL)
7093 goto done;
7095 if (repo_path == NULL) {
7096 error = got_worktree_open(&worktree, cwd,
7097 GOT_WORKTREE_GOT_DIR);
7098 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7099 goto done;
7100 else
7101 error = NULL;
7102 if (worktree) {
7103 repo_path =
7104 strdup(got_worktree_get_repo_path(worktree));
7105 if (repo_path == NULL)
7106 error = got_error_from_errno("strdup");
7107 if (error)
7108 goto done;
7109 } else {
7110 repo_path = strdup(cwd);
7111 if (repo_path == NULL) {
7112 error = got_error_from_errno("strdup");
7113 goto done;
7118 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7119 if (error != NULL)
7120 goto done;
7122 #ifndef PROFILE
7123 if (do_list || do_show) {
7124 /* Remove "cpath" promise. */
7125 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7126 NULL) == -1)
7127 err(1, "pledge");
7129 #endif
7131 error = apply_unveil(got_repo_get_path(repo), do_list,
7132 worktree ? got_worktree_get_root_path(worktree) : NULL);
7133 if (error)
7134 goto done;
7136 if (do_show)
7137 error = show_current_branch(repo, worktree);
7138 else if (do_list)
7139 error = list_branches(repo, worktree, sort_by_time);
7140 else if (delref)
7141 error = delete_branch(repo, worktree, delref);
7142 else {
7143 struct got_reflist_head refs;
7144 TAILQ_INIT(&refs);
7145 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7146 NULL);
7147 if (error)
7148 goto done;
7149 if (commit_id_arg == NULL)
7150 commit_id_arg = worktree ?
7151 got_worktree_get_head_ref_name(worktree) :
7152 GOT_REF_HEAD;
7153 else {
7154 error = got_keyword_to_idstr(&keyword_idstr,
7155 commit_id_arg, repo, worktree);
7156 if (error != NULL)
7157 goto done;
7158 if (keyword_idstr != NULL)
7159 commit_id_arg = keyword_idstr;
7161 error = got_repo_match_object_id(&commit_id, NULL,
7162 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7163 got_ref_list_free(&refs);
7164 if (error)
7165 goto done;
7166 error = add_branch(repo, argv[0], commit_id);
7167 if (error)
7168 goto done;
7169 if (worktree && do_update) {
7170 struct got_update_progress_arg upa;
7171 char *branch_refname = NULL;
7173 error = got_object_id_str(&commit_id_str, commit_id);
7174 if (error)
7175 goto done;
7176 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7177 worktree);
7178 if (error)
7179 goto done;
7180 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7181 == -1) {
7182 error = got_error_from_errno("asprintf");
7183 goto done;
7185 error = got_ref_open(&ref, repo, branch_refname, 0);
7186 free(branch_refname);
7187 if (error)
7188 goto done;
7189 error = switch_head_ref(ref, commit_id, worktree,
7190 repo);
7191 if (error)
7192 goto done;
7193 error = got_worktree_set_base_commit_id(worktree, repo,
7194 commit_id);
7195 if (error)
7196 goto done;
7197 memset(&upa, 0, sizeof(upa));
7198 error = got_worktree_checkout_files(worktree, &paths,
7199 repo, update_progress, &upa, check_cancelled,
7200 NULL);
7201 if (error)
7202 goto done;
7203 if (upa.did_something) {
7204 printf("Updated to %s: %s\n",
7205 got_worktree_get_head_ref_name(worktree),
7206 commit_id_str);
7208 print_update_progress_stats(&upa);
7211 done:
7212 free(keyword_idstr);
7213 if (ref)
7214 got_ref_close(ref);
7215 if (repo) {
7216 const struct got_error *close_err = got_repo_close(repo);
7217 if (error == NULL)
7218 error = close_err;
7220 if (worktree)
7221 got_worktree_close(worktree);
7222 if (pack_fds) {
7223 const struct got_error *pack_err =
7224 got_repo_pack_fds_close(pack_fds);
7225 if (error == NULL)
7226 error = pack_err;
7228 free(cwd);
7229 free(repo_path);
7230 free(commit_id);
7231 free(commit_id_str);
7232 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7233 return error;
7237 __dead static void
7238 usage_tag(void)
7240 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7241 "[-r repository-path] [-s signer-id] name\n", getprogname());
7242 exit(1);
7245 #if 0
7246 static const struct got_error *
7247 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7249 const struct got_error *err = NULL;
7250 struct got_reflist_entry *re, *se, *new;
7251 struct got_object_id *re_id, *se_id;
7252 struct got_tag_object *re_tag, *se_tag;
7253 time_t re_time, se_time;
7255 STAILQ_FOREACH(re, tags, entry) {
7256 se = STAILQ_FIRST(sorted);
7257 if (se == NULL) {
7258 err = got_reflist_entry_dup(&new, re);
7259 if (err)
7260 return err;
7261 STAILQ_INSERT_HEAD(sorted, new, entry);
7262 continue;
7263 } else {
7264 err = got_ref_resolve(&re_id, repo, re->ref);
7265 if (err)
7266 break;
7267 err = got_object_open_as_tag(&re_tag, repo, re_id);
7268 free(re_id);
7269 if (err)
7270 break;
7271 re_time = got_object_tag_get_tagger_time(re_tag);
7272 got_object_tag_close(re_tag);
7275 while (se) {
7276 err = got_ref_resolve(&se_id, repo, re->ref);
7277 if (err)
7278 break;
7279 err = got_object_open_as_tag(&se_tag, repo, se_id);
7280 free(se_id);
7281 if (err)
7282 break;
7283 se_time = got_object_tag_get_tagger_time(se_tag);
7284 got_object_tag_close(se_tag);
7286 if (se_time > re_time) {
7287 err = got_reflist_entry_dup(&new, re);
7288 if (err)
7289 return err;
7290 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7291 break;
7293 se = STAILQ_NEXT(se, entry);
7294 continue;
7297 done:
7298 return err;
7300 #endif
7302 static const struct got_error *
7303 get_tag_refname(char **refname, const char *tag_name)
7305 const struct got_error *err;
7307 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7308 *refname = strdup(tag_name);
7309 if (*refname == NULL)
7310 return got_error_from_errno("strdup");
7311 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7312 err = got_error_from_errno("asprintf");
7313 *refname = NULL;
7314 return err;
7317 return NULL;
7320 static const struct got_error *
7321 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7322 const char *allowed_signers, const char *revoked_signers, int verbosity)
7324 static const struct got_error *err = NULL;
7325 struct got_reflist_head refs;
7326 struct got_reflist_entry *re;
7327 char *wanted_refname = NULL;
7328 int bad_sigs = 0;
7330 TAILQ_INIT(&refs);
7332 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7333 if (err)
7334 return err;
7336 if (tag_name) {
7337 struct got_reference *ref;
7338 err = get_tag_refname(&wanted_refname, tag_name);
7339 if (err)
7340 goto done;
7341 /* Wanted tag reference should exist. */
7342 err = got_ref_open(&ref, repo, wanted_refname, 0);
7343 if (err)
7344 goto done;
7345 got_ref_close(ref);
7348 TAILQ_FOREACH(re, &refs, entry) {
7349 const char *refname;
7350 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7351 char datebuf[26];
7352 const char *tagger, *ssh_sig = NULL;
7353 char *sig_msg = NULL;
7354 time_t tagger_time;
7355 struct got_object_id *id;
7356 struct got_tag_object *tag;
7357 struct got_commit_object *commit = NULL;
7359 refname = got_ref_get_name(re->ref);
7360 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7361 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7362 continue;
7363 refname += 10;
7364 refstr = got_ref_to_str(re->ref);
7365 if (refstr == NULL) {
7366 err = got_error_from_errno("got_ref_to_str");
7367 break;
7370 err = got_ref_resolve(&id, repo, re->ref);
7371 if (err)
7372 break;
7373 err = got_object_open_as_tag(&tag, repo, id);
7374 if (err) {
7375 if (err->code != GOT_ERR_OBJ_TYPE) {
7376 free(id);
7377 break;
7379 /* "lightweight" tag */
7380 err = got_object_open_as_commit(&commit, repo, id);
7381 if (err) {
7382 free(id);
7383 break;
7385 tagger = got_object_commit_get_committer(commit);
7386 tagger_time =
7387 got_object_commit_get_committer_time(commit);
7388 err = got_object_id_str(&id_str, id);
7389 free(id);
7390 if (err)
7391 break;
7392 } else {
7393 free(id);
7394 tagger = got_object_tag_get_tagger(tag);
7395 tagger_time = got_object_tag_get_tagger_time(tag);
7396 err = got_object_id_str(&id_str,
7397 got_object_tag_get_object_id(tag));
7398 if (err)
7399 break;
7402 if (tag && verify_tags) {
7403 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7404 got_object_tag_get_message(tag));
7405 if (ssh_sig && allowed_signers == NULL) {
7406 err = got_error_msg(
7407 GOT_ERR_VERIFY_TAG_SIGNATURE,
7408 "SSH signature verification requires "
7409 "setting allowed_signers in "
7410 "got.conf(5)");
7411 break;
7415 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7416 free(refstr);
7417 printf("from: %s\n", tagger);
7418 datestr = get_datestr(&tagger_time, datebuf);
7419 if (datestr)
7420 printf("date: %s UTC\n", datestr);
7421 if (commit)
7422 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7423 else {
7424 switch (got_object_tag_get_object_type(tag)) {
7425 case GOT_OBJ_TYPE_BLOB:
7426 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7427 id_str);
7428 break;
7429 case GOT_OBJ_TYPE_TREE:
7430 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7431 id_str);
7432 break;
7433 case GOT_OBJ_TYPE_COMMIT:
7434 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7435 id_str);
7436 break;
7437 case GOT_OBJ_TYPE_TAG:
7438 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7439 id_str);
7440 break;
7441 default:
7442 break;
7445 free(id_str);
7447 if (ssh_sig) {
7448 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7449 allowed_signers, revoked_signers, verbosity);
7450 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7451 bad_sigs = 1;
7452 else if (err)
7453 break;
7454 printf("signature: %s", sig_msg);
7455 free(sig_msg);
7456 sig_msg = NULL;
7459 if (commit) {
7460 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7461 if (err)
7462 break;
7463 got_object_commit_close(commit);
7464 } else {
7465 tagmsg0 = strdup(got_object_tag_get_message(tag));
7466 got_object_tag_close(tag);
7467 if (tagmsg0 == NULL) {
7468 err = got_error_from_errno("strdup");
7469 break;
7473 tagmsg = tagmsg0;
7474 do {
7475 line = strsep(&tagmsg, "\n");
7476 if (line)
7477 printf(" %s\n", line);
7478 } while (line);
7479 free(tagmsg0);
7481 done:
7482 got_ref_list_free(&refs);
7483 free(wanted_refname);
7485 if (err == NULL && bad_sigs)
7486 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7487 return err;
7490 static const struct got_error *
7491 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7492 const char *tag_name, const char *repo_path)
7494 const struct got_error *err = NULL;
7495 char *template = NULL, *initial_content = NULL;
7496 char *editor = NULL;
7497 int initial_content_len;
7498 int fd = -1;
7500 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7501 err = got_error_from_errno("asprintf");
7502 goto done;
7505 initial_content_len = asprintf(&initial_content,
7506 "\n# tagging commit %s as %s\n",
7507 commit_id_str, tag_name);
7508 if (initial_content_len == -1) {
7509 err = got_error_from_errno("asprintf");
7510 goto done;
7513 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7514 if (err)
7515 goto done;
7517 if (write(fd, initial_content, initial_content_len) == -1) {
7518 err = got_error_from_errno2("write", *tagmsg_path);
7519 goto done;
7521 if (close(fd) == -1) {
7522 err = got_error_from_errno2("close", *tagmsg_path);
7523 goto done;
7525 fd = -1;
7527 err = get_editor(&editor);
7528 if (err)
7529 goto done;
7530 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7531 initial_content_len, 1);
7532 done:
7533 free(initial_content);
7534 free(template);
7535 free(editor);
7537 if (fd != -1 && close(fd) == -1 && err == NULL)
7538 err = got_error_from_errno2("close", *tagmsg_path);
7540 if (err) {
7541 free(*tagmsg);
7542 *tagmsg = NULL;
7544 return err;
7547 static const struct got_error *
7548 add_tag(struct got_repository *repo, const char *tagger,
7549 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7550 const char *signer_id, int verbosity)
7552 const struct got_error *err = NULL;
7553 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7554 char *label = NULL, *commit_id_str = NULL;
7555 struct got_reference *ref = NULL;
7556 char *refname = NULL, *tagmsg = NULL;
7557 char *tagmsg_path = NULL, *tag_id_str = NULL;
7558 int preserve_tagmsg = 0;
7559 struct got_reflist_head refs;
7561 TAILQ_INIT(&refs);
7564 * Don't let the user create a tag name with a leading '-'.
7565 * While technically a valid reference name, this case is usually
7566 * an unintended typo.
7568 if (tag_name[0] == '-')
7569 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7571 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7572 if (err)
7573 goto done;
7575 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7576 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7577 if (err)
7578 goto done;
7580 err = got_object_id_str(&commit_id_str, commit_id);
7581 if (err)
7582 goto done;
7584 err = get_tag_refname(&refname, tag_name);
7585 if (err)
7586 goto done;
7587 if (strncmp("refs/tags/", tag_name, 10) == 0)
7588 tag_name += 10;
7590 err = got_ref_open(&ref, repo, refname, 0);
7591 if (err == NULL) {
7592 err = got_error(GOT_ERR_TAG_EXISTS);
7593 goto done;
7594 } else if (err->code != GOT_ERR_NOT_REF)
7595 goto done;
7597 if (tagmsg_arg == NULL) {
7598 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7599 tag_name, got_repo_get_path(repo));
7600 if (err) {
7601 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7602 tagmsg_path != NULL)
7603 preserve_tagmsg = 1;
7604 goto done;
7606 /* Editor is done; we can now apply unveil(2) */
7607 err = got_sigs_apply_unveil();
7608 if (err)
7609 goto done;
7610 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7611 if (err)
7612 goto done;
7615 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7616 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7617 verbosity);
7618 if (err) {
7619 if (tagmsg_path)
7620 preserve_tagmsg = 1;
7621 goto done;
7624 err = got_ref_alloc(&ref, refname, tag_id);
7625 if (err) {
7626 if (tagmsg_path)
7627 preserve_tagmsg = 1;
7628 goto done;
7631 err = got_ref_write(ref, repo);
7632 if (err) {
7633 if (tagmsg_path)
7634 preserve_tagmsg = 1;
7635 goto done;
7638 err = got_object_id_str(&tag_id_str, tag_id);
7639 if (err) {
7640 if (tagmsg_path)
7641 preserve_tagmsg = 1;
7642 goto done;
7644 printf("Created tag %s\n", tag_id_str);
7645 done:
7646 if (preserve_tagmsg) {
7647 fprintf(stderr, "%s: tag message preserved in %s\n",
7648 getprogname(), tagmsg_path);
7649 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7650 err = got_error_from_errno2("unlink", tagmsg_path);
7651 free(tag_id_str);
7652 if (ref)
7653 got_ref_close(ref);
7654 free(commit_id);
7655 free(commit_id_str);
7656 free(refname);
7657 free(tagmsg);
7658 free(tagmsg_path);
7659 got_ref_list_free(&refs);
7660 return err;
7663 static const struct got_error *
7664 cmd_tag(int argc, char *argv[])
7666 const struct got_error *error = NULL;
7667 struct got_repository *repo = NULL;
7668 struct got_worktree *worktree = NULL;
7669 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7670 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7671 char *allowed_signers = NULL, *revoked_signers = NULL;
7672 const char *signer_id = NULL;
7673 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7674 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7675 int *pack_fds = NULL;
7677 #ifndef PROFILE
7678 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7679 "sendfd unveil", NULL) == -1)
7680 err(1, "pledge");
7681 #endif
7683 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7684 switch (ch) {
7685 case 'c':
7686 commit_id_arg = optarg;
7687 break;
7688 case 'l':
7689 do_list = 1;
7690 break;
7691 case 'm':
7692 tagmsg = optarg;
7693 break;
7694 case 'r':
7695 repo_path = realpath(optarg, NULL);
7696 if (repo_path == NULL) {
7697 error = got_error_from_errno2("realpath",
7698 optarg);
7699 goto done;
7701 got_path_strip_trailing_slashes(repo_path);
7702 break;
7703 case 's':
7704 signer_id = optarg;
7705 break;
7706 case 'V':
7707 verify_tags = 1;
7708 break;
7709 case 'v':
7710 if (verbosity < 0)
7711 verbosity = 0;
7712 else if (verbosity < 3)
7713 verbosity++;
7714 break;
7715 default:
7716 usage_tag();
7717 /* NOTREACHED */
7721 argc -= optind;
7722 argv += optind;
7724 if (do_list || verify_tags) {
7725 if (commit_id_arg != NULL)
7726 errx(1,
7727 "-c option can only be used when creating a tag");
7728 if (tagmsg) {
7729 if (do_list)
7730 option_conflict('l', 'm');
7731 else
7732 option_conflict('V', 'm');
7734 if (signer_id) {
7735 if (do_list)
7736 option_conflict('l', 's');
7737 else
7738 option_conflict('V', 's');
7740 if (argc > 1)
7741 usage_tag();
7742 } else if (argc != 1)
7743 usage_tag();
7745 if (argc == 1)
7746 tag_name = argv[0];
7748 cwd = getcwd(NULL, 0);
7749 if (cwd == NULL) {
7750 error = got_error_from_errno("getcwd");
7751 goto done;
7754 error = got_repo_pack_fds_open(&pack_fds);
7755 if (error != NULL)
7756 goto done;
7758 if (repo_path == NULL) {
7759 error = got_worktree_open(&worktree, cwd,
7760 GOT_WORKTREE_GOT_DIR);
7761 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7762 goto done;
7763 else
7764 error = NULL;
7765 if (worktree) {
7766 repo_path =
7767 strdup(got_worktree_get_repo_path(worktree));
7768 if (repo_path == NULL)
7769 error = got_error_from_errno("strdup");
7770 if (error)
7771 goto done;
7772 } else {
7773 repo_path = strdup(cwd);
7774 if (repo_path == NULL) {
7775 error = got_error_from_errno("strdup");
7776 goto done;
7781 if (do_list || verify_tags) {
7782 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7783 if (error != NULL)
7784 goto done;
7785 error = get_allowed_signers(&allowed_signers, repo, worktree);
7786 if (error)
7787 goto done;
7788 error = get_revoked_signers(&revoked_signers, repo, worktree);
7789 if (error)
7790 goto done;
7791 if (worktree) {
7792 /* Release work tree lock. */
7793 got_worktree_close(worktree);
7794 worktree = NULL;
7798 * Remove "cpath" promise unless needed for signature tmpfile
7799 * creation.
7801 if (verify_tags)
7802 got_sigs_apply_unveil();
7803 else {
7804 #ifndef PROFILE
7805 if (pledge("stdio rpath wpath flock proc exec sendfd "
7806 "unveil", NULL) == -1)
7807 err(1, "pledge");
7808 #endif
7810 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7811 if (error)
7812 goto done;
7813 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7814 revoked_signers, verbosity);
7815 } else {
7816 error = get_gitconfig_path(&gitconfig_path);
7817 if (error)
7818 goto done;
7819 error = got_repo_open(&repo, repo_path, gitconfig_path,
7820 pack_fds);
7821 if (error != NULL)
7822 goto done;
7824 error = get_author(&tagger, repo, worktree);
7825 if (error)
7826 goto done;
7827 if (signer_id == NULL)
7828 signer_id = get_signer_id(repo, worktree);
7830 if (tagmsg) {
7831 if (signer_id) {
7832 error = got_sigs_apply_unveil();
7833 if (error)
7834 goto done;
7836 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7837 if (error)
7838 goto done;
7841 if (commit_id_arg == NULL) {
7842 struct got_reference *head_ref;
7843 struct got_object_id *commit_id;
7844 error = got_ref_open(&head_ref, repo,
7845 worktree ? got_worktree_get_head_ref_name(worktree)
7846 : GOT_REF_HEAD, 0);
7847 if (error)
7848 goto done;
7849 error = got_ref_resolve(&commit_id, repo, head_ref);
7850 got_ref_close(head_ref);
7851 if (error)
7852 goto done;
7853 error = got_object_id_str(&commit_id_str, commit_id);
7854 free(commit_id);
7855 if (error)
7856 goto done;
7857 } else {
7858 error = got_keyword_to_idstr(&keyword_idstr,
7859 commit_id_arg, repo, worktree);
7860 if (error != NULL)
7861 goto done;
7862 commit_id_str = keyword_idstr;
7865 if (worktree) {
7866 /* Release work tree lock. */
7867 got_worktree_close(worktree);
7868 worktree = NULL;
7871 error = add_tag(repo, tagger, tag_name,
7872 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7873 signer_id, verbosity);
7875 done:
7876 if (repo) {
7877 const struct got_error *close_err = got_repo_close(repo);
7878 if (error == NULL)
7879 error = close_err;
7881 if (worktree)
7882 got_worktree_close(worktree);
7883 if (pack_fds) {
7884 const struct got_error *pack_err =
7885 got_repo_pack_fds_close(pack_fds);
7886 if (error == NULL)
7887 error = pack_err;
7889 free(cwd);
7890 free(repo_path);
7891 free(gitconfig_path);
7892 free(commit_id_str);
7893 free(tagger);
7894 free(allowed_signers);
7895 free(revoked_signers);
7896 return error;
7899 __dead static void
7900 usage_add(void)
7902 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7903 exit(1);
7906 static const struct got_error *
7907 add_progress(void *arg, unsigned char status, const char *path)
7909 while (path[0] == '/')
7910 path++;
7911 printf("%c %s\n", status, path);
7912 return NULL;
7915 static const struct got_error *
7916 cmd_add(int argc, char *argv[])
7918 const struct got_error *error = NULL;
7919 struct got_repository *repo = NULL;
7920 struct got_worktree *worktree = NULL;
7921 char *cwd = NULL;
7922 struct got_pathlist_head paths;
7923 struct got_pathlist_entry *pe;
7924 int ch, can_recurse = 0, no_ignores = 0;
7925 int *pack_fds = NULL;
7927 TAILQ_INIT(&paths);
7929 #ifndef PROFILE
7930 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7931 NULL) == -1)
7932 err(1, "pledge");
7933 #endif
7935 while ((ch = getopt(argc, argv, "IR")) != -1) {
7936 switch (ch) {
7937 case 'I':
7938 no_ignores = 1;
7939 break;
7940 case 'R':
7941 can_recurse = 1;
7942 break;
7943 default:
7944 usage_add();
7945 /* NOTREACHED */
7949 argc -= optind;
7950 argv += optind;
7952 if (argc < 1)
7953 usage_add();
7955 cwd = getcwd(NULL, 0);
7956 if (cwd == NULL) {
7957 error = got_error_from_errno("getcwd");
7958 goto done;
7961 error = got_repo_pack_fds_open(&pack_fds);
7962 if (error != NULL)
7963 goto done;
7965 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7966 if (error) {
7967 if (error->code == GOT_ERR_NOT_WORKTREE)
7968 error = wrap_not_worktree_error(error, "add", cwd);
7969 goto done;
7972 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7973 NULL, pack_fds);
7974 if (error != NULL)
7975 goto done;
7977 error = apply_unveil(got_repo_get_path(repo), 1,
7978 got_worktree_get_root_path(worktree));
7979 if (error)
7980 goto done;
7982 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7983 if (error)
7984 goto done;
7986 if (!can_recurse) {
7987 char *ondisk_path;
7988 struct stat sb;
7989 TAILQ_FOREACH(pe, &paths, entry) {
7990 if (asprintf(&ondisk_path, "%s/%s",
7991 got_worktree_get_root_path(worktree),
7992 pe->path) == -1) {
7993 error = got_error_from_errno("asprintf");
7994 goto done;
7996 if (lstat(ondisk_path, &sb) == -1) {
7997 if (errno == ENOENT) {
7998 free(ondisk_path);
7999 continue;
8001 error = got_error_from_errno2("lstat",
8002 ondisk_path);
8003 free(ondisk_path);
8004 goto done;
8006 free(ondisk_path);
8007 if (S_ISDIR(sb.st_mode)) {
8008 error = got_error_msg(GOT_ERR_BAD_PATH,
8009 "adding directories requires -R option");
8010 goto done;
8015 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8016 NULL, repo, no_ignores);
8017 done:
8018 if (repo) {
8019 const struct got_error *close_err = got_repo_close(repo);
8020 if (error == NULL)
8021 error = close_err;
8023 if (worktree)
8024 got_worktree_close(worktree);
8025 if (pack_fds) {
8026 const struct got_error *pack_err =
8027 got_repo_pack_fds_close(pack_fds);
8028 if (error == NULL)
8029 error = pack_err;
8031 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8032 free(cwd);
8033 return error;
8036 __dead static void
8037 usage_remove(void)
8039 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8040 getprogname());
8041 exit(1);
8044 static const struct got_error *
8045 print_remove_status(void *arg, unsigned char status,
8046 unsigned char staged_status, const char *path)
8048 while (path[0] == '/')
8049 path++;
8050 if (status == GOT_STATUS_NONEXISTENT)
8051 return NULL;
8052 if (status == staged_status && (status == GOT_STATUS_DELETE))
8053 status = GOT_STATUS_NO_CHANGE;
8054 printf("%c%c %s\n", status, staged_status, path);
8055 return NULL;
8058 static const struct got_error *
8059 cmd_remove(int argc, char *argv[])
8061 const struct got_error *error = NULL;
8062 struct got_worktree *worktree = NULL;
8063 struct got_repository *repo = NULL;
8064 const char *status_codes = NULL;
8065 char *cwd = NULL;
8066 struct got_pathlist_head paths;
8067 struct got_pathlist_entry *pe;
8068 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8069 int ignore_missing_paths = 0;
8070 int *pack_fds = NULL;
8072 TAILQ_INIT(&paths);
8074 #ifndef PROFILE
8075 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8076 NULL) == -1)
8077 err(1, "pledge");
8078 #endif
8080 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8081 switch (ch) {
8082 case 'f':
8083 delete_local_mods = 1;
8084 ignore_missing_paths = 1;
8085 break;
8086 case 'k':
8087 keep_on_disk = 1;
8088 break;
8089 case 'R':
8090 can_recurse = 1;
8091 break;
8092 case 's':
8093 for (i = 0; optarg[i] != '\0'; i++) {
8094 switch (optarg[i]) {
8095 case GOT_STATUS_MODIFY:
8096 delete_local_mods = 1;
8097 break;
8098 case GOT_STATUS_MISSING:
8099 ignore_missing_paths = 1;
8100 break;
8101 default:
8102 errx(1, "invalid status code '%c'",
8103 optarg[i]);
8106 status_codes = optarg;
8107 break;
8108 default:
8109 usage_remove();
8110 /* NOTREACHED */
8114 argc -= optind;
8115 argv += optind;
8117 if (argc < 1)
8118 usage_remove();
8120 cwd = getcwd(NULL, 0);
8121 if (cwd == NULL) {
8122 error = got_error_from_errno("getcwd");
8123 goto done;
8126 error = got_repo_pack_fds_open(&pack_fds);
8127 if (error != NULL)
8128 goto done;
8130 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8131 if (error) {
8132 if (error->code == GOT_ERR_NOT_WORKTREE)
8133 error = wrap_not_worktree_error(error, "remove", cwd);
8134 goto done;
8137 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8138 NULL, pack_fds);
8139 if (error)
8140 goto done;
8142 error = apply_unveil(got_repo_get_path(repo), 1,
8143 got_worktree_get_root_path(worktree));
8144 if (error)
8145 goto done;
8147 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8148 if (error)
8149 goto done;
8151 if (!can_recurse) {
8152 char *ondisk_path;
8153 struct stat sb;
8154 TAILQ_FOREACH(pe, &paths, entry) {
8155 if (asprintf(&ondisk_path, "%s/%s",
8156 got_worktree_get_root_path(worktree),
8157 pe->path) == -1) {
8158 error = got_error_from_errno("asprintf");
8159 goto done;
8161 if (lstat(ondisk_path, &sb) == -1) {
8162 if (errno == ENOENT) {
8163 free(ondisk_path);
8164 continue;
8166 error = got_error_from_errno2("lstat",
8167 ondisk_path);
8168 free(ondisk_path);
8169 goto done;
8171 free(ondisk_path);
8172 if (S_ISDIR(sb.st_mode)) {
8173 error = got_error_msg(GOT_ERR_BAD_PATH,
8174 "removing directories requires -R option");
8175 goto done;
8180 error = got_worktree_schedule_delete(worktree, &paths,
8181 delete_local_mods, status_codes, print_remove_status, NULL,
8182 repo, keep_on_disk, ignore_missing_paths);
8183 done:
8184 if (repo) {
8185 const struct got_error *close_err = got_repo_close(repo);
8186 if (error == NULL)
8187 error = close_err;
8189 if (worktree)
8190 got_worktree_close(worktree);
8191 if (pack_fds) {
8192 const struct got_error *pack_err =
8193 got_repo_pack_fds_close(pack_fds);
8194 if (error == NULL)
8195 error = pack_err;
8197 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8198 free(cwd);
8199 return error;
8202 __dead static void
8203 usage_patch(void)
8205 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8206 "[patchfile]\n", getprogname());
8207 exit(1);
8210 static const struct got_error *
8211 patch_from_stdin(int *patchfd)
8213 const struct got_error *err = NULL;
8214 ssize_t r;
8215 char buf[BUFSIZ];
8216 sig_t sighup, sigint, sigquit;
8218 *patchfd = got_opentempfd();
8219 if (*patchfd == -1)
8220 return got_error_from_errno("got_opentempfd");
8222 sighup = signal(SIGHUP, SIG_DFL);
8223 sigint = signal(SIGINT, SIG_DFL);
8224 sigquit = signal(SIGQUIT, SIG_DFL);
8226 for (;;) {
8227 r = read(0, buf, sizeof(buf));
8228 if (r == -1) {
8229 err = got_error_from_errno("read");
8230 break;
8232 if (r == 0)
8233 break;
8234 if (write(*patchfd, buf, r) == -1) {
8235 err = got_error_from_errno("write");
8236 break;
8240 signal(SIGHUP, sighup);
8241 signal(SIGINT, sigint);
8242 signal(SIGQUIT, sigquit);
8244 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8245 err = got_error_from_errno("lseek");
8247 if (err != NULL) {
8248 close(*patchfd);
8249 *patchfd = -1;
8252 return err;
8255 struct got_patch_progress_arg {
8256 int did_something;
8257 int conflicts;
8258 int rejects;
8261 static const struct got_error *
8262 patch_progress(void *arg, const char *old, const char *new,
8263 unsigned char status, const struct got_error *error, int old_from,
8264 int old_lines, int new_from, int new_lines, int offset,
8265 int ws_mangled, const struct got_error *hunk_err)
8267 const char *path = new == NULL ? old : new;
8268 struct got_patch_progress_arg *a = arg;
8270 while (*path == '/')
8271 path++;
8273 if (status != GOT_STATUS_NO_CHANGE &&
8274 status != 0 /* per-hunk progress */) {
8275 printf("%c %s\n", status, path);
8276 a->did_something = 1;
8279 if (hunk_err == NULL) {
8280 if (status == GOT_STATUS_CANNOT_UPDATE)
8281 a->rejects++;
8282 else if (status == GOT_STATUS_CONFLICT)
8283 a->conflicts++;
8286 if (error != NULL)
8287 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8289 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8290 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8291 old_lines, new_from, new_lines);
8292 if (hunk_err != NULL)
8293 printf("%s\n", hunk_err->msg);
8294 else if (offset != 0)
8295 printf("applied with offset %d\n", offset);
8296 else
8297 printf("hunk contains mangled whitespace\n");
8300 return NULL;
8303 static void
8304 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8306 if (!ppa->did_something)
8307 return;
8309 if (ppa->conflicts > 0)
8310 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8312 if (ppa->rejects > 0) {
8313 printf("Files where patch failed to apply: %d\n",
8314 ppa->rejects);
8318 static const struct got_error *
8319 cmd_patch(int argc, char *argv[])
8321 const struct got_error *error = NULL, *close_error = NULL;
8322 struct got_worktree *worktree = NULL;
8323 struct got_repository *repo = NULL;
8324 struct got_reflist_head refs;
8325 struct got_object_id *commit_id = NULL;
8326 const char *commit_id_str = NULL;
8327 struct stat sb;
8328 const char *errstr;
8329 char *cwd = NULL, *keyword_idstr = NULL;
8330 int ch, nop = 0, strip = -1, reverse = 0;
8331 int patchfd;
8332 int *pack_fds = NULL;
8333 struct got_patch_progress_arg ppa;
8335 TAILQ_INIT(&refs);
8337 #ifndef PROFILE
8338 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8339 "unveil", NULL) == -1)
8340 err(1, "pledge");
8341 #endif
8343 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8344 switch (ch) {
8345 case 'c':
8346 commit_id_str = optarg;
8347 break;
8348 case 'n':
8349 nop = 1;
8350 break;
8351 case 'p':
8352 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8353 if (errstr != NULL)
8354 errx(1, "pathname strip count is %s: %s",
8355 errstr, optarg);
8356 break;
8357 case 'R':
8358 reverse = 1;
8359 break;
8360 default:
8361 usage_patch();
8362 /* NOTREACHED */
8366 argc -= optind;
8367 argv += optind;
8369 if (argc == 0) {
8370 error = patch_from_stdin(&patchfd);
8371 if (error)
8372 return error;
8373 } else if (argc == 1) {
8374 patchfd = open(argv[0], O_RDONLY);
8375 if (patchfd == -1) {
8376 error = got_error_from_errno2("open", argv[0]);
8377 return error;
8379 if (fstat(patchfd, &sb) == -1) {
8380 error = got_error_from_errno2("fstat", argv[0]);
8381 goto done;
8383 if (!S_ISREG(sb.st_mode)) {
8384 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8385 goto done;
8387 } else
8388 usage_patch();
8390 if ((cwd = getcwd(NULL, 0)) == NULL) {
8391 error = got_error_from_errno("getcwd");
8392 goto done;
8395 error = got_repo_pack_fds_open(&pack_fds);
8396 if (error != NULL)
8397 goto done;
8399 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8400 if (error != NULL)
8401 goto done;
8403 const char *repo_path = got_worktree_get_repo_path(worktree);
8404 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8405 if (error != NULL)
8406 goto done;
8408 error = apply_unveil(got_repo_get_path(repo), 0,
8409 got_worktree_get_root_path(worktree));
8410 if (error != NULL)
8411 goto done;
8413 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8414 if (error)
8415 goto done;
8417 if (commit_id_str != NULL) {
8418 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8419 repo, worktree);
8420 if (error != NULL)
8421 goto done;
8423 error = got_repo_match_object_id(&commit_id, NULL,
8424 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8425 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8426 if (error)
8427 goto done;
8430 memset(&ppa, 0, sizeof(ppa));
8431 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8432 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8433 print_patch_progress_stats(&ppa);
8434 done:
8435 got_ref_list_free(&refs);
8436 free(keyword_idstr);
8437 free(commit_id);
8438 if (repo) {
8439 close_error = got_repo_close(repo);
8440 if (error == NULL)
8441 error = close_error;
8443 if (worktree != NULL) {
8444 close_error = got_worktree_close(worktree);
8445 if (error == NULL)
8446 error = close_error;
8448 if (pack_fds) {
8449 const struct got_error *pack_err =
8450 got_repo_pack_fds_close(pack_fds);
8451 if (error == NULL)
8452 error = pack_err;
8454 free(cwd);
8455 return error;
8458 __dead static void
8459 usage_revert(void)
8461 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8462 getprogname());
8463 exit(1);
8466 static const struct got_error *
8467 revert_progress(void *arg, unsigned char status, const char *path)
8469 if (status == GOT_STATUS_UNVERSIONED)
8470 return NULL;
8472 while (path[0] == '/')
8473 path++;
8474 printf("%c %s\n", status, path);
8475 return NULL;
8478 struct choose_patch_arg {
8479 FILE *patch_script_file;
8480 const char *action;
8483 static const struct got_error *
8484 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8485 int nchanges, const char *action)
8487 const struct got_error *err;
8488 char *line = NULL;
8489 size_t linesize = 0;
8490 ssize_t linelen;
8492 switch (status) {
8493 case GOT_STATUS_ADD:
8494 printf("A %s\n%s this addition? [y/n] ", path, action);
8495 break;
8496 case GOT_STATUS_DELETE:
8497 printf("D %s\n%s this deletion? [y/n] ", path, action);
8498 break;
8499 case GOT_STATUS_MODIFY:
8500 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8501 return got_error_from_errno("fseek");
8502 printf(GOT_COMMIT_SEP_STR);
8503 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8504 printf("%s", line);
8505 if (linelen == -1 && ferror(patch_file)) {
8506 err = got_error_from_errno("getline");
8507 free(line);
8508 return err;
8510 free(line);
8511 printf(GOT_COMMIT_SEP_STR);
8512 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8513 path, n, nchanges, action);
8514 break;
8515 default:
8516 return got_error_path(path, GOT_ERR_FILE_STATUS);
8519 fflush(stdout);
8520 return NULL;
8523 static const struct got_error *
8524 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8525 FILE *patch_file, int n, int nchanges)
8527 const struct got_error *err = NULL;
8528 char *line = NULL;
8529 size_t linesize = 0;
8530 ssize_t linelen;
8531 int resp = ' ';
8532 struct choose_patch_arg *a = arg;
8534 *choice = GOT_PATCH_CHOICE_NONE;
8536 if (a->patch_script_file) {
8537 char *nl;
8538 err = show_change(status, path, patch_file, n, nchanges,
8539 a->action);
8540 if (err)
8541 return err;
8542 linelen = getline(&line, &linesize, a->patch_script_file);
8543 if (linelen == -1) {
8544 if (ferror(a->patch_script_file))
8545 return got_error_from_errno("getline");
8546 return NULL;
8548 nl = strchr(line, '\n');
8549 if (nl)
8550 *nl = '\0';
8551 if (strcmp(line, "y") == 0) {
8552 *choice = GOT_PATCH_CHOICE_YES;
8553 printf("y\n");
8554 } else if (strcmp(line, "n") == 0) {
8555 *choice = GOT_PATCH_CHOICE_NO;
8556 printf("n\n");
8557 } else if (strcmp(line, "q") == 0 &&
8558 status == GOT_STATUS_MODIFY) {
8559 *choice = GOT_PATCH_CHOICE_QUIT;
8560 printf("q\n");
8561 } else
8562 printf("invalid response '%s'\n", line);
8563 free(line);
8564 return NULL;
8567 while (resp != 'y' && resp != 'n' && resp != 'q') {
8568 err = show_change(status, path, patch_file, n, nchanges,
8569 a->action);
8570 if (err)
8571 return err;
8572 resp = getchar();
8573 if (resp == '\n')
8574 resp = getchar();
8575 if (status == GOT_STATUS_MODIFY) {
8576 if (resp != 'y' && resp != 'n' && resp != 'q') {
8577 printf("invalid response '%c'\n", resp);
8578 resp = ' ';
8580 } else if (resp != 'y' && resp != 'n') {
8581 printf("invalid response '%c'\n", resp);
8582 resp = ' ';
8586 if (resp == 'y')
8587 *choice = GOT_PATCH_CHOICE_YES;
8588 else if (resp == 'n')
8589 *choice = GOT_PATCH_CHOICE_NO;
8590 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8591 *choice = GOT_PATCH_CHOICE_QUIT;
8593 return NULL;
8596 struct wt_commitable_path_arg {
8597 struct got_pathlist_head *commit_paths;
8598 int *has_changes;
8602 * Shortcut work tree status callback to determine if the set of paths scanned
8603 * has at least one versioned path that is being modified and, if not NULL, is
8604 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8605 * soon as a path is passed with a status that satisfies this criteria.
8607 static const struct got_error *
8608 worktree_has_commitable_path(void *arg, unsigned char status,
8609 unsigned char staged_status, const char *path,
8610 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8611 struct got_object_id *commit_id, int dirfd, const char *de_name)
8613 struct wt_commitable_path_arg *a = arg;
8615 if (status == staged_status && (status == GOT_STATUS_DELETE))
8616 status = GOT_STATUS_NO_CHANGE;
8618 if (!(status == GOT_STATUS_NO_CHANGE ||
8619 status == GOT_STATUS_UNVERSIONED) ||
8620 staged_status != GOT_STATUS_NO_CHANGE) {
8621 if (a->commit_paths != NULL) {
8622 struct got_pathlist_entry *pe;
8624 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8625 if (strncmp(path, pe->path,
8626 pe->path_len) == 0) {
8627 *a->has_changes = 1;
8628 break;
8631 } else
8632 *a->has_changes = 1;
8634 if (*a->has_changes)
8635 return got_error(GOT_ERR_FILE_MODIFIED);
8638 return NULL;
8642 * Check that the changeset of the commit identified by id is
8643 * comprised of at least one modified path that is being committed.
8645 static const struct got_error *
8646 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8647 struct got_object_id *id, struct got_worktree *worktree,
8648 struct got_repository *repo)
8650 const struct got_error *err;
8651 struct got_pathlist_head paths;
8652 struct got_commit_object *commit = NULL, *pcommit = NULL;
8653 struct got_tree_object *tree = NULL, *ptree = NULL;
8654 struct got_object_qid *pid;
8656 TAILQ_INIT(&paths);
8658 err = got_object_open_as_commit(&commit, repo, id);
8659 if (err)
8660 goto done;
8662 err = got_object_open_as_tree(&tree, repo,
8663 got_object_commit_get_tree_id(commit));
8664 if (err)
8665 goto done;
8667 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8668 if (pid != NULL) {
8669 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8670 if (err)
8671 goto done;
8673 err = got_object_open_as_tree(&ptree, repo,
8674 got_object_commit_get_tree_id(pcommit));
8675 if (err)
8676 goto done;
8679 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8680 got_diff_tree_collect_changed_paths, &paths, 0);
8681 if (err)
8682 goto done;
8684 err = got_worktree_status(worktree, &paths, repo, 0,
8685 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8686 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8688 * At least one changed path in the referenced commit is
8689 * modified in the work tree, that's all we need to know!
8691 err = NULL;
8694 done:
8695 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8696 if (commit)
8697 got_object_commit_close(commit);
8698 if (pcommit)
8699 got_object_commit_close(pcommit);
8700 if (tree)
8701 got_object_tree_close(tree);
8702 if (ptree)
8703 got_object_tree_close(ptree);
8704 return err;
8708 * Remove any "logmsg" reference comprised entirely of paths that have
8709 * been reverted in this work tree. If any path in the logmsg ref changeset
8710 * remains in a changed state in the worktree, do not remove the reference.
8712 static const struct got_error *
8713 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8715 const struct got_error *err;
8716 struct got_reflist_head refs;
8717 struct got_reflist_entry *re;
8718 struct got_commit_object *commit = NULL;
8719 struct got_object_id *commit_id = NULL;
8720 struct wt_commitable_path_arg wcpa;
8721 char *uuidstr = NULL;
8723 TAILQ_INIT(&refs);
8725 err = got_worktree_get_uuid(&uuidstr, worktree);
8726 if (err)
8727 goto done;
8729 err = got_ref_list(&refs, repo, "refs/got/worktree",
8730 got_ref_cmp_by_name, repo);
8731 if (err)
8732 goto done;
8734 TAILQ_FOREACH(re, &refs, entry) {
8735 const char *refname;
8736 int has_changes = 0;
8738 refname = got_ref_get_name(re->ref);
8740 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8741 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8742 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8743 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8744 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8745 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8746 else
8747 continue;
8749 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8750 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8751 else
8752 continue;
8754 err = got_repo_match_object_id(&commit_id, NULL, refname,
8755 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8756 if (err)
8757 goto done;
8759 err = got_object_open_as_commit(&commit, repo, commit_id);
8760 if (err)
8761 goto done;
8763 wcpa.commit_paths = NULL;
8764 wcpa.has_changes = &has_changes;
8766 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8767 worktree, repo);
8768 if (err)
8769 goto done;
8771 if (!has_changes) {
8772 err = got_ref_delete(re->ref, repo);
8773 if (err)
8774 goto done;
8777 got_object_commit_close(commit);
8778 commit = NULL;
8779 free(commit_id);
8780 commit_id = NULL;
8783 done:
8784 free(uuidstr);
8785 free(commit_id);
8786 got_ref_list_free(&refs);
8787 if (commit)
8788 got_object_commit_close(commit);
8789 return err;
8792 static const struct got_error *
8793 cmd_revert(int argc, char *argv[])
8795 const struct got_error *error = NULL;
8796 struct got_worktree *worktree = NULL;
8797 struct got_repository *repo = NULL;
8798 char *cwd = NULL, *path = NULL;
8799 struct got_pathlist_head paths;
8800 struct got_pathlist_entry *pe;
8801 int ch, can_recurse = 0, pflag = 0;
8802 FILE *patch_script_file = NULL;
8803 const char *patch_script_path = NULL;
8804 struct choose_patch_arg cpa;
8805 int *pack_fds = NULL;
8807 TAILQ_INIT(&paths);
8809 #ifndef PROFILE
8810 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8811 "unveil", NULL) == -1)
8812 err(1, "pledge");
8813 #endif
8815 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8816 switch (ch) {
8817 case 'F':
8818 patch_script_path = optarg;
8819 break;
8820 case 'p':
8821 pflag = 1;
8822 break;
8823 case 'R':
8824 can_recurse = 1;
8825 break;
8826 default:
8827 usage_revert();
8828 /* NOTREACHED */
8832 argc -= optind;
8833 argv += optind;
8835 if (argc < 1)
8836 usage_revert();
8837 if (patch_script_path && !pflag)
8838 errx(1, "-F option can only be used together with -p option");
8840 cwd = getcwd(NULL, 0);
8841 if (cwd == NULL) {
8842 error = got_error_from_errno("getcwd");
8843 goto done;
8846 error = got_repo_pack_fds_open(&pack_fds);
8847 if (error != NULL)
8848 goto done;
8850 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8851 if (error) {
8852 if (error->code == GOT_ERR_NOT_WORKTREE)
8853 error = wrap_not_worktree_error(error, "revert", cwd);
8854 goto done;
8857 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8858 NULL, pack_fds);
8859 if (error != NULL)
8860 goto done;
8862 if (patch_script_path) {
8863 patch_script_file = fopen(patch_script_path, "re");
8864 if (patch_script_file == NULL) {
8865 error = got_error_from_errno2("fopen",
8866 patch_script_path);
8867 goto done;
8872 * XXX "c" perm needed on repo dir to delete merge references.
8874 error = apply_unveil(got_repo_get_path(repo), 0,
8875 got_worktree_get_root_path(worktree));
8876 if (error)
8877 goto done;
8879 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8880 if (error)
8881 goto done;
8883 if (!can_recurse) {
8884 char *ondisk_path;
8885 struct stat sb;
8886 TAILQ_FOREACH(pe, &paths, entry) {
8887 if (asprintf(&ondisk_path, "%s/%s",
8888 got_worktree_get_root_path(worktree),
8889 pe->path) == -1) {
8890 error = got_error_from_errno("asprintf");
8891 goto done;
8893 if (lstat(ondisk_path, &sb) == -1) {
8894 if (errno == ENOENT) {
8895 free(ondisk_path);
8896 continue;
8898 error = got_error_from_errno2("lstat",
8899 ondisk_path);
8900 free(ondisk_path);
8901 goto done;
8903 free(ondisk_path);
8904 if (S_ISDIR(sb.st_mode)) {
8905 error = got_error_msg(GOT_ERR_BAD_PATH,
8906 "reverting directories requires -R option");
8907 goto done;
8912 cpa.patch_script_file = patch_script_file;
8913 cpa.action = "revert";
8914 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8915 pflag ? choose_patch : NULL, &cpa, repo);
8917 error = rm_logmsg_ref(worktree, repo);
8918 done:
8919 if (patch_script_file && fclose(patch_script_file) == EOF &&
8920 error == NULL)
8921 error = got_error_from_errno2("fclose", patch_script_path);
8922 if (repo) {
8923 const struct got_error *close_err = got_repo_close(repo);
8924 if (error == NULL)
8925 error = close_err;
8927 if (worktree)
8928 got_worktree_close(worktree);
8929 if (pack_fds) {
8930 const struct got_error *pack_err =
8931 got_repo_pack_fds_close(pack_fds);
8932 if (error == NULL)
8933 error = pack_err;
8935 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8936 free(path);
8937 free(cwd);
8938 return error;
8941 __dead static void
8942 usage_commit(void)
8944 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8945 "[-m message] [path ...]\n", getprogname());
8946 exit(1);
8949 struct collect_commit_logmsg_arg {
8950 const char *cmdline_log;
8951 const char *prepared_log;
8952 const char *merged_log;
8953 int non_interactive;
8954 const char *editor;
8955 const char *worktree_path;
8956 const char *branch_name;
8957 const char *repo_path;
8958 char *logmsg_path;
8962 static const struct got_error *
8963 read_prepared_logmsg(char **logmsg, const char *path)
8965 const struct got_error *err = NULL;
8966 FILE *f = NULL;
8967 struct stat sb;
8968 size_t r;
8970 *logmsg = NULL;
8971 memset(&sb, 0, sizeof(sb));
8973 f = fopen(path, "re");
8974 if (f == NULL)
8975 return got_error_from_errno2("fopen", path);
8977 if (fstat(fileno(f), &sb) == -1) {
8978 err = got_error_from_errno2("fstat", path);
8979 goto done;
8981 if (sb.st_size == 0) {
8982 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8983 goto done;
8986 *logmsg = malloc(sb.st_size + 1);
8987 if (*logmsg == NULL) {
8988 err = got_error_from_errno("malloc");
8989 goto done;
8992 r = fread(*logmsg, 1, sb.st_size, f);
8993 if (r != sb.st_size) {
8994 if (ferror(f))
8995 err = got_error_from_errno2("fread", path);
8996 else
8997 err = got_error(GOT_ERR_IO);
8998 goto done;
9000 (*logmsg)[sb.st_size] = '\0';
9001 done:
9002 if (fclose(f) == EOF && err == NULL)
9003 err = got_error_from_errno2("fclose", path);
9004 if (err) {
9005 free(*logmsg);
9006 *logmsg = NULL;
9008 return err;
9011 static const struct got_error *
9012 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9013 const char *diff_path, char **logmsg, void *arg)
9015 char *initial_content = NULL;
9016 struct got_pathlist_entry *pe;
9017 const struct got_error *err = NULL;
9018 char *template = NULL;
9019 char *prepared_msg = NULL, *merged_msg = NULL;
9020 struct collect_commit_logmsg_arg *a = arg;
9021 int initial_content_len;
9022 int fd = -1;
9023 size_t len;
9025 /* if a message was specified on the command line, just use it */
9026 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9027 len = strlen(a->cmdline_log) + 1;
9028 *logmsg = malloc(len + 1);
9029 if (*logmsg == NULL)
9030 return got_error_from_errno("malloc");
9031 strlcpy(*logmsg, a->cmdline_log, len);
9032 return NULL;
9033 } else if (a->prepared_log != NULL && a->non_interactive)
9034 return read_prepared_logmsg(logmsg, a->prepared_log);
9036 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9037 return got_error_from_errno("asprintf");
9039 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9040 if (err)
9041 goto done;
9043 if (a->prepared_log) {
9044 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9045 if (err)
9046 goto done;
9047 } else if (a->merged_log) {
9048 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9049 if (err)
9050 goto done;
9053 initial_content_len = asprintf(&initial_content,
9054 "%s%s\n# changes to be committed on branch %s:\n",
9055 prepared_msg ? prepared_msg : "",
9056 merged_msg ? merged_msg : "", a->branch_name);
9057 if (initial_content_len == -1) {
9058 err = got_error_from_errno("asprintf");
9059 goto done;
9062 if (write(fd, initial_content, initial_content_len) == -1) {
9063 err = got_error_from_errno2("write", a->logmsg_path);
9064 goto done;
9067 TAILQ_FOREACH(pe, commitable_paths, entry) {
9068 struct got_commitable *ct = pe->data;
9069 dprintf(fd, "# %c %s\n",
9070 got_commitable_get_status(ct),
9071 got_commitable_get_path(ct));
9074 if (diff_path) {
9075 dprintf(fd, "# detailed changes can be viewed in %s\n",
9076 diff_path);
9079 if (close(fd) == -1) {
9080 err = got_error_from_errno2("close", a->logmsg_path);
9081 goto done;
9083 fd = -1;
9085 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9086 initial_content_len, a->prepared_log ? 0 : 1);
9087 done:
9088 free(initial_content);
9089 free(template);
9090 free(prepared_msg);
9091 free(merged_msg);
9093 if (fd != -1 && close(fd) == -1 && err == NULL)
9094 err = got_error_from_errno2("close", a->logmsg_path);
9096 /* Editor is done; we can now apply unveil(2) */
9097 if (err == NULL)
9098 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9099 if (err) {
9100 free(*logmsg);
9101 *logmsg = NULL;
9103 return err;
9106 static const struct got_error *
9107 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9108 const char *type, int has_content)
9110 const struct got_error *err = NULL;
9111 char *logmsg = NULL;
9113 err = got_object_commit_get_logmsg(&logmsg, commit);
9114 if (err)
9115 return err;
9117 if (fprintf(f, "%s# log message of %s commit %s:%s",
9118 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9119 err = got_ferror(f, GOT_ERR_IO);
9121 free(logmsg);
9122 return err;
9126 * Lookup "logmsg" references of backed-out and cherrypicked commits
9127 * belonging to the current work tree. If found, and the worktree has
9128 * at least one modified file that was changed in the referenced commit,
9129 * add its log message to a new temporary file at *logmsg_path.
9130 * Add all refs found to matched_refs to be scheduled for removal on
9131 * successful commit.
9133 static const struct got_error *
9134 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9135 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9136 struct got_repository *repo)
9138 const struct got_error *err;
9139 struct got_commit_object *commit = NULL;
9140 struct got_object_id *id = NULL;
9141 struct got_reflist_head refs;
9142 struct got_reflist_entry *re, *re_match;
9143 FILE *f = NULL;
9144 char *uuidstr = NULL;
9145 int added_logmsg = 0;
9147 TAILQ_INIT(&refs);
9149 *logmsg_path = NULL;
9151 err = got_worktree_get_uuid(&uuidstr, worktree);
9152 if (err)
9153 goto done;
9155 err = got_ref_list(&refs, repo, "refs/got/worktree",
9156 got_ref_cmp_by_name, repo);
9157 if (err)
9158 goto done;
9160 TAILQ_FOREACH(re, &refs, entry) {
9161 const char *refname, *type;
9162 struct wt_commitable_path_arg wcpa;
9163 int add_logmsg = 0;
9165 refname = got_ref_get_name(re->ref);
9167 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9168 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9169 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9170 type = "cherrypicked";
9171 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9172 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9173 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9174 type = "backed-out";
9175 } else
9176 continue;
9178 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9179 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9180 else
9181 continue;
9183 err = got_repo_match_object_id(&id, NULL, refname,
9184 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9185 if (err)
9186 goto done;
9188 err = got_object_open_as_commit(&commit, repo, id);
9189 if (err)
9190 goto done;
9192 wcpa.commit_paths = paths;
9193 wcpa.has_changes = &add_logmsg;
9195 err = commit_path_changed_in_worktree(&wcpa, id,
9196 worktree, repo);
9197 if (err)
9198 goto done;
9200 if (add_logmsg) {
9201 if (f == NULL) {
9202 err = got_opentemp_named(logmsg_path, &f,
9203 "got-commit-logmsg", "");
9204 if (err)
9205 goto done;
9207 err = cat_logmsg(f, commit, refname, type,
9208 added_logmsg);
9209 if (err)
9210 goto done;
9211 if (!added_logmsg)
9212 ++added_logmsg;
9214 err = got_reflist_entry_dup(&re_match, re);
9215 if (err)
9216 goto done;
9217 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9220 got_object_commit_close(commit);
9221 commit = NULL;
9222 free(id);
9223 id = NULL;
9226 done:
9227 free(id);
9228 free(uuidstr);
9229 got_ref_list_free(&refs);
9230 if (commit)
9231 got_object_commit_close(commit);
9232 if (f && fclose(f) == EOF && err == NULL)
9233 err = got_error_from_errno("fclose");
9234 if (!added_logmsg) {
9235 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9236 err = got_error_from_errno2("unlink", *logmsg_path);
9237 *logmsg_path = NULL;
9239 return err;
9242 static const struct got_error *
9243 cmd_commit(int argc, char *argv[])
9245 const struct got_error *error = NULL;
9246 struct got_worktree *worktree = NULL;
9247 struct got_repository *repo = NULL;
9248 char *cwd = NULL, *id_str = NULL;
9249 struct got_object_id *id = NULL;
9250 const char *logmsg = NULL;
9251 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9252 struct collect_commit_logmsg_arg cl_arg;
9253 const char *author = NULL;
9254 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9255 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9256 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9257 int show_diff = 1, commit_conflicts = 0;
9258 struct got_pathlist_head paths;
9259 struct got_reflist_head refs;
9260 struct got_reflist_entry *re;
9261 int *pack_fds = NULL;
9263 TAILQ_INIT(&refs);
9264 TAILQ_INIT(&paths);
9265 cl_arg.logmsg_path = NULL;
9267 #ifndef PROFILE
9268 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9269 "unveil", NULL) == -1)
9270 err(1, "pledge");
9271 #endif
9273 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9274 switch (ch) {
9275 case 'A':
9276 author = optarg;
9277 error = valid_author(author);
9278 if (error)
9279 return error;
9280 break;
9281 case 'C':
9282 commit_conflicts = 1;
9283 break;
9284 case 'F':
9285 if (logmsg != NULL)
9286 option_conflict('F', 'm');
9287 prepared_logmsg = realpath(optarg, NULL);
9288 if (prepared_logmsg == NULL)
9289 return got_error_from_errno2("realpath",
9290 optarg);
9291 break;
9292 case 'm':
9293 if (prepared_logmsg)
9294 option_conflict('m', 'F');
9295 logmsg = optarg;
9296 break;
9297 case 'N':
9298 non_interactive = 1;
9299 break;
9300 case 'n':
9301 show_diff = 0;
9302 break;
9303 case 'S':
9304 allow_bad_symlinks = 1;
9305 break;
9306 default:
9307 usage_commit();
9308 /* NOTREACHED */
9312 argc -= optind;
9313 argv += optind;
9315 cwd = getcwd(NULL, 0);
9316 if (cwd == NULL) {
9317 error = got_error_from_errno("getcwd");
9318 goto done;
9321 error = got_repo_pack_fds_open(&pack_fds);
9322 if (error != NULL)
9323 goto done;
9325 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9326 if (error) {
9327 if (error->code == GOT_ERR_NOT_WORKTREE)
9328 error = wrap_not_worktree_error(error, "commit", cwd);
9329 goto done;
9332 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9333 if (error)
9334 goto done;
9335 if (rebase_in_progress) {
9336 error = got_error(GOT_ERR_REBASING);
9337 goto done;
9340 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9341 worktree);
9342 if (error)
9343 goto done;
9345 error = get_gitconfig_path(&gitconfig_path);
9346 if (error)
9347 goto done;
9348 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9349 gitconfig_path, pack_fds);
9350 if (error != NULL)
9351 goto done;
9353 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9354 if (error)
9355 goto done;
9356 if (merge_in_progress) {
9357 error = got_error(GOT_ERR_MERGE_BUSY);
9358 goto done;
9361 error = get_author(&committer, repo, worktree);
9362 if (error)
9363 goto done;
9365 if (author == NULL)
9366 author = committer;
9369 * unveil(2) traverses exec(2); if an editor is used we have
9370 * to apply unveil after the log message has been written.
9372 if (logmsg == NULL || strlen(logmsg) == 0)
9373 error = get_editor(&editor);
9374 else
9375 error = apply_unveil(got_repo_get_path(repo), 0,
9376 got_worktree_get_root_path(worktree));
9377 if (error)
9378 goto done;
9380 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9381 if (error)
9382 goto done;
9384 if (prepared_logmsg == NULL) {
9385 error = lookup_logmsg_ref(&merged_logmsg,
9386 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9387 if (error)
9388 goto done;
9391 cl_arg.editor = editor;
9392 cl_arg.cmdline_log = logmsg;
9393 cl_arg.prepared_log = prepared_logmsg;
9394 cl_arg.merged_log = merged_logmsg;
9395 cl_arg.non_interactive = non_interactive;
9396 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9397 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9398 if (!histedit_in_progress) {
9399 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9400 error = got_error(GOT_ERR_COMMIT_BRANCH);
9401 goto done;
9403 cl_arg.branch_name += 11;
9405 cl_arg.repo_path = got_repo_get_path(repo);
9406 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9407 allow_bad_symlinks, show_diff, commit_conflicts,
9408 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9409 if (error) {
9410 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9411 cl_arg.logmsg_path != NULL)
9412 preserve_logmsg = 1;
9413 goto done;
9416 error = got_object_id_str(&id_str, id);
9417 if (error)
9418 goto done;
9419 printf("Created commit %s\n", id_str);
9421 TAILQ_FOREACH(re, &refs, entry) {
9422 error = got_ref_delete(re->ref, repo);
9423 if (error)
9424 goto done;
9427 done:
9428 if (preserve_logmsg) {
9429 fprintf(stderr, "%s: log message preserved in %s\n",
9430 getprogname(), cl_arg.logmsg_path);
9431 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9432 error == NULL)
9433 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9434 free(cl_arg.logmsg_path);
9435 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9436 error = got_error_from_errno2("unlink", merged_logmsg);
9437 free(merged_logmsg);
9438 if (repo) {
9439 const struct got_error *close_err = got_repo_close(repo);
9440 if (error == NULL)
9441 error = close_err;
9443 if (worktree)
9444 got_worktree_close(worktree);
9445 if (pack_fds) {
9446 const struct got_error *pack_err =
9447 got_repo_pack_fds_close(pack_fds);
9448 if (error == NULL)
9449 error = pack_err;
9451 got_ref_list_free(&refs);
9452 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9453 free(cwd);
9454 free(id_str);
9455 free(gitconfig_path);
9456 free(editor);
9457 free(committer);
9458 free(prepared_logmsg);
9459 return error;
9462 __dead static void
9463 usage_send(void)
9465 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9466 "[-r repository-path] [-t tag] [remote-repository]\n",
9467 getprogname());
9468 exit(1);
9471 static void
9472 print_load_info(int print_colored, int print_found, int print_trees,
9473 int ncolored, int nfound, int ntrees)
9475 if (print_colored) {
9476 printf("%d commit%s colored", ncolored,
9477 ncolored == 1 ? "" : "s");
9479 if (print_found) {
9480 printf("%s%d object%s found",
9481 ncolored > 0 ? "; " : "",
9482 nfound, nfound == 1 ? "" : "s");
9484 if (print_trees) {
9485 printf("; %d tree%s scanned", ntrees,
9486 ntrees == 1 ? "" : "s");
9490 struct got_send_progress_arg {
9491 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9492 int verbosity;
9493 int last_ncolored;
9494 int last_nfound;
9495 int last_ntrees;
9496 int loading_done;
9497 int last_ncommits;
9498 int last_nobj_total;
9499 int last_p_deltify;
9500 int last_p_written;
9501 int last_p_sent;
9502 int printed_something;
9503 int sent_something;
9504 struct got_pathlist_head *delete_branches;
9507 static const struct got_error *
9508 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9509 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9510 int nobj_written, off_t bytes_sent, const char *refname,
9511 const char *errmsg, int success)
9513 struct got_send_progress_arg *a = arg;
9514 char scaled_packsize[FMT_SCALED_STRSIZE];
9515 char scaled_sent[FMT_SCALED_STRSIZE];
9516 int p_deltify = 0, p_written = 0, p_sent = 0;
9517 int print_colored = 0, print_found = 0, print_trees = 0;
9518 int print_searching = 0, print_total = 0;
9519 int print_deltify = 0, print_written = 0, print_sent = 0;
9521 if (a->verbosity < 0)
9522 return NULL;
9524 if (refname) {
9525 const char *status = success ? "accepted" : "rejected";
9527 if (success) {
9528 struct got_pathlist_entry *pe;
9529 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9530 const char *branchname = pe->path;
9531 if (got_path_cmp(branchname, refname,
9532 strlen(branchname), strlen(refname)) == 0) {
9533 status = "deleted";
9534 a->sent_something = 1;
9535 break;
9540 if (a->printed_something)
9541 putchar('\n');
9542 printf("Server has %s %s", status, refname);
9543 if (errmsg)
9544 printf(": %s", errmsg);
9545 a->printed_something = 1;
9546 return NULL;
9549 if (a->last_ncolored != ncolored) {
9550 print_colored = 1;
9551 a->last_ncolored = ncolored;
9554 if (a->last_nfound != nfound) {
9555 print_colored = 1;
9556 print_found = 1;
9557 a->last_nfound = nfound;
9560 if (a->last_ntrees != ntrees) {
9561 print_colored = 1;
9562 print_found = 1;
9563 print_trees = 1;
9564 a->last_ntrees = ntrees;
9567 if ((print_colored || print_found || print_trees) &&
9568 !a->loading_done) {
9569 printf("\r");
9570 print_load_info(print_colored, print_found, print_trees,
9571 ncolored, nfound, ntrees);
9572 a->printed_something = 1;
9573 fflush(stdout);
9574 return NULL;
9575 } else if (!a->loading_done) {
9576 printf("\r");
9577 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9578 printf("\n");
9579 a->loading_done = 1;
9582 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9583 return got_error_from_errno("fmt_scaled");
9584 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9585 return got_error_from_errno("fmt_scaled");
9587 if (a->last_ncommits != ncommits) {
9588 print_searching = 1;
9589 a->last_ncommits = ncommits;
9592 if (a->last_nobj_total != nobj_total) {
9593 print_searching = 1;
9594 print_total = 1;
9595 a->last_nobj_total = nobj_total;
9598 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9599 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9600 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9601 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9602 return got_error(GOT_ERR_NO_SPACE);
9605 if (nobj_deltify > 0 || nobj_written > 0) {
9606 if (nobj_deltify > 0) {
9607 p_deltify = (nobj_deltify * 100) / nobj_total;
9608 if (p_deltify != a->last_p_deltify) {
9609 a->last_p_deltify = p_deltify;
9610 print_searching = 1;
9611 print_total = 1;
9612 print_deltify = 1;
9615 if (nobj_written > 0) {
9616 p_written = (nobj_written * 100) / nobj_total;
9617 if (p_written != a->last_p_written) {
9618 a->last_p_written = p_written;
9619 print_searching = 1;
9620 print_total = 1;
9621 print_deltify = 1;
9622 print_written = 1;
9627 if (bytes_sent > 0) {
9628 p_sent = (bytes_sent * 100) / packfile_size;
9629 if (p_sent != a->last_p_sent) {
9630 a->last_p_sent = p_sent;
9631 print_searching = 1;
9632 print_total = 1;
9633 print_deltify = 1;
9634 print_written = 1;
9635 print_sent = 1;
9637 a->sent_something = 1;
9640 if (print_searching || print_total || print_deltify || print_written ||
9641 print_sent)
9642 printf("\r");
9643 if (print_searching)
9644 printf("packing %d reference%s", ncommits,
9645 ncommits == 1 ? "" : "s");
9646 if (print_total)
9647 printf("; %d object%s", nobj_total,
9648 nobj_total == 1 ? "" : "s");
9649 if (print_deltify)
9650 printf("; deltify: %d%%", p_deltify);
9651 if (print_sent)
9652 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9653 scaled_packsize, p_sent);
9654 else if (print_written)
9655 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9656 scaled_packsize, p_written);
9657 if (print_searching || print_total || print_deltify ||
9658 print_written || print_sent) {
9659 a->printed_something = 1;
9660 fflush(stdout);
9662 return NULL;
9665 static const struct got_error *
9666 cmd_send(int argc, char *argv[])
9668 const struct got_error *error = NULL;
9669 char *cwd = NULL, *repo_path = NULL;
9670 const char *remote_name;
9671 char *proto = NULL, *host = NULL, *port = NULL;
9672 char *repo_name = NULL, *server_path = NULL;
9673 const struct got_remote_repo *remotes, *remote = NULL;
9674 int nremotes, nbranches = 0, ndelete_branches = 0;
9675 struct got_repository *repo = NULL;
9676 struct got_worktree *worktree = NULL;
9677 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9678 struct got_pathlist_head branches;
9679 struct got_pathlist_head tags;
9680 struct got_reflist_head all_branches;
9681 struct got_reflist_head all_tags;
9682 struct got_pathlist_head delete_args;
9683 struct got_pathlist_head delete_branches;
9684 struct got_reflist_entry *re;
9685 struct got_pathlist_entry *pe;
9686 int i, ch, sendfd = -1, sendstatus;
9687 pid_t sendpid = -1;
9688 struct got_send_progress_arg spa;
9689 int verbosity = 0, overwrite_refs = 0;
9690 int send_all_branches = 0, send_all_tags = 0;
9691 struct got_reference *ref = NULL;
9692 int *pack_fds = NULL;
9694 TAILQ_INIT(&branches);
9695 TAILQ_INIT(&tags);
9696 TAILQ_INIT(&all_branches);
9697 TAILQ_INIT(&all_tags);
9698 TAILQ_INIT(&delete_args);
9699 TAILQ_INIT(&delete_branches);
9701 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9702 switch (ch) {
9703 case 'a':
9704 send_all_branches = 1;
9705 break;
9706 case 'b':
9707 error = got_pathlist_append(&branches, optarg, NULL);
9708 if (error)
9709 return error;
9710 nbranches++;
9711 break;
9712 case 'd':
9713 error = got_pathlist_append(&delete_args, optarg, NULL);
9714 if (error)
9715 return error;
9716 break;
9717 case 'f':
9718 overwrite_refs = 1;
9719 break;
9720 case 'q':
9721 verbosity = -1;
9722 break;
9723 case 'r':
9724 repo_path = realpath(optarg, NULL);
9725 if (repo_path == NULL)
9726 return got_error_from_errno2("realpath",
9727 optarg);
9728 got_path_strip_trailing_slashes(repo_path);
9729 break;
9730 case 'T':
9731 send_all_tags = 1;
9732 break;
9733 case 't':
9734 error = got_pathlist_append(&tags, optarg, NULL);
9735 if (error)
9736 return error;
9737 break;
9738 case 'v':
9739 if (verbosity < 0)
9740 verbosity = 0;
9741 else if (verbosity < 3)
9742 verbosity++;
9743 break;
9744 default:
9745 usage_send();
9746 /* NOTREACHED */
9749 argc -= optind;
9750 argv += optind;
9752 if (send_all_branches && !TAILQ_EMPTY(&branches))
9753 option_conflict('a', 'b');
9754 if (send_all_tags && !TAILQ_EMPTY(&tags))
9755 option_conflict('T', 't');
9758 if (argc == 0)
9759 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9760 else if (argc == 1)
9761 remote_name = argv[0];
9762 else
9763 usage_send();
9765 cwd = getcwd(NULL, 0);
9766 if (cwd == NULL) {
9767 error = got_error_from_errno("getcwd");
9768 goto done;
9771 error = got_repo_pack_fds_open(&pack_fds);
9772 if (error != NULL)
9773 goto done;
9775 if (repo_path == NULL) {
9776 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9777 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9778 goto done;
9779 else
9780 error = NULL;
9781 if (worktree) {
9782 repo_path =
9783 strdup(got_worktree_get_repo_path(worktree));
9784 if (repo_path == NULL)
9785 error = got_error_from_errno("strdup");
9786 if (error)
9787 goto done;
9788 } else {
9789 repo_path = strdup(cwd);
9790 if (repo_path == NULL) {
9791 error = got_error_from_errno("strdup");
9792 goto done;
9797 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9798 if (error)
9799 goto done;
9801 if (worktree) {
9802 worktree_conf = got_worktree_get_gotconfig(worktree);
9803 if (worktree_conf) {
9804 got_gotconfig_get_remotes(&nremotes, &remotes,
9805 worktree_conf);
9806 for (i = 0; i < nremotes; i++) {
9807 if (strcmp(remotes[i].name, remote_name) == 0) {
9808 remote = &remotes[i];
9809 break;
9814 if (remote == NULL) {
9815 repo_conf = got_repo_get_gotconfig(repo);
9816 if (repo_conf) {
9817 got_gotconfig_get_remotes(&nremotes, &remotes,
9818 repo_conf);
9819 for (i = 0; i < nremotes; i++) {
9820 if (strcmp(remotes[i].name, remote_name) == 0) {
9821 remote = &remotes[i];
9822 break;
9827 if (remote == NULL) {
9828 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9829 for (i = 0; i < nremotes; i++) {
9830 if (strcmp(remotes[i].name, remote_name) == 0) {
9831 remote = &remotes[i];
9832 break;
9836 if (remote == NULL) {
9837 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9838 goto done;
9841 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9842 &repo_name, remote->send_url);
9843 if (error)
9844 goto done;
9846 if (strcmp(proto, "git") == 0) {
9847 #ifndef PROFILE
9848 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9849 "sendfd dns inet unveil", NULL) == -1)
9850 err(1, "pledge");
9851 #endif
9852 } else if (strcmp(proto, "git+ssh") == 0 ||
9853 strcmp(proto, "ssh") == 0) {
9854 #ifndef PROFILE
9855 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9856 "sendfd unveil", NULL) == -1)
9857 err(1, "pledge");
9858 #endif
9859 } else if (strcmp(proto, "http") == 0 ||
9860 strcmp(proto, "git+http") == 0) {
9861 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9862 goto done;
9863 } else {
9864 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9865 goto done;
9868 error = got_dial_apply_unveil(proto);
9869 if (error)
9870 goto done;
9872 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9873 if (error)
9874 goto done;
9876 if (send_all_branches) {
9877 error = got_ref_list(&all_branches, repo, "refs/heads",
9878 got_ref_cmp_by_name, NULL);
9879 if (error)
9880 goto done;
9881 TAILQ_FOREACH(re, &all_branches, entry) {
9882 const char *branchname = got_ref_get_name(re->ref);
9883 error = got_pathlist_append(&branches,
9884 branchname, NULL);
9885 if (error)
9886 goto done;
9887 nbranches++;
9889 } else if (nbranches == 0) {
9890 for (i = 0; i < remote->nsend_branches; i++) {
9891 error = got_pathlist_append(&branches,
9892 remote->send_branches[i], NULL);
9893 if (error)
9894 goto done;
9898 if (send_all_tags) {
9899 error = got_ref_list(&all_tags, repo, "refs/tags",
9900 got_ref_cmp_by_name, NULL);
9901 if (error)
9902 goto done;
9903 TAILQ_FOREACH(re, &all_tags, entry) {
9904 const char *tagname = got_ref_get_name(re->ref);
9905 error = got_pathlist_append(&tags,
9906 tagname, NULL);
9907 if (error)
9908 goto done;
9913 * To prevent accidents only branches in refs/heads/ can be deleted
9914 * with 'got send -d'.
9915 * Deleting anything else requires local repository access or Git.
9917 TAILQ_FOREACH(pe, &delete_args, entry) {
9918 const char *branchname = pe->path;
9919 char *s;
9920 struct got_pathlist_entry *new;
9921 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9922 s = strdup(branchname);
9923 if (s == NULL) {
9924 error = got_error_from_errno("strdup");
9925 goto done;
9927 } else {
9928 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9929 error = got_error_from_errno("asprintf");
9930 goto done;
9933 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9934 if (error || new == NULL /* duplicate */)
9935 free(s);
9936 if (error)
9937 goto done;
9938 ndelete_branches++;
9941 if (nbranches == 0 && ndelete_branches == 0) {
9942 struct got_reference *head_ref;
9943 if (worktree)
9944 error = got_ref_open(&head_ref, repo,
9945 got_worktree_get_head_ref_name(worktree), 0);
9946 else
9947 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9948 if (error)
9949 goto done;
9950 if (got_ref_is_symbolic(head_ref)) {
9951 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9952 got_ref_close(head_ref);
9953 if (error)
9954 goto done;
9955 } else
9956 ref = head_ref;
9957 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9958 NULL);
9959 if (error)
9960 goto done;
9961 nbranches++;
9964 if (verbosity >= 0) {
9965 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9966 remote->name, proto, host,
9967 port ? ":" : "", port ? port : "",
9968 *server_path == '/' ? "" : "/", server_path);
9971 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9972 server_path, verbosity);
9973 if (error)
9974 goto done;
9976 memset(&spa, 0, sizeof(spa));
9977 spa.last_scaled_packsize[0] = '\0';
9978 spa.last_p_deltify = -1;
9979 spa.last_p_written = -1;
9980 spa.verbosity = verbosity;
9981 spa.delete_branches = &delete_branches;
9982 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9983 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9984 check_cancelled, NULL);
9985 if (spa.printed_something)
9986 putchar('\n');
9987 if (error)
9988 goto done;
9989 if (!spa.sent_something && verbosity >= 0)
9990 printf("Already up-to-date\n");
9991 done:
9992 if (sendpid > 0) {
9993 if (kill(sendpid, SIGTERM) == -1)
9994 error = got_error_from_errno("kill");
9995 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9996 error = got_error_from_errno("waitpid");
9998 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9999 error = got_error_from_errno("close");
10000 if (repo) {
10001 const struct got_error *close_err = got_repo_close(repo);
10002 if (error == NULL)
10003 error = close_err;
10005 if (worktree)
10006 got_worktree_close(worktree);
10007 if (pack_fds) {
10008 const struct got_error *pack_err =
10009 got_repo_pack_fds_close(pack_fds);
10010 if (error == NULL)
10011 error = pack_err;
10013 if (ref)
10014 got_ref_close(ref);
10015 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10016 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10017 got_ref_list_free(&all_branches);
10018 got_ref_list_free(&all_tags);
10019 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10020 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10021 free(cwd);
10022 free(repo_path);
10023 free(proto);
10024 free(host);
10025 free(port);
10026 free(server_path);
10027 free(repo_name);
10028 return error;
10032 * Print and if delete is set delete all ref_prefix references.
10033 * If wanted_ref is not NULL, only print or delete this reference.
10035 static const struct got_error *
10036 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10037 const char *wanted_ref, int delete, struct got_worktree *worktree,
10038 struct got_repository *repo)
10040 const struct got_error *err;
10041 struct got_pathlist_head paths;
10042 struct got_reflist_head refs;
10043 struct got_reflist_entry *re;
10044 struct got_reflist_object_id_map *refs_idmap = NULL;
10045 struct got_commit_object *commit = NULL;
10046 struct got_object_id *id = NULL;
10047 const char *header_prefix;
10048 char *uuidstr = NULL;
10049 int found = 0;
10051 TAILQ_INIT(&refs);
10052 TAILQ_INIT(&paths);
10054 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10055 if (err)
10056 goto done;
10058 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10059 if (err)
10060 goto done;
10062 if (worktree != NULL) {
10063 err = got_worktree_get_uuid(&uuidstr, worktree);
10064 if (err)
10065 goto done;
10068 if (wanted_ref) {
10069 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10070 wanted_ref += 11;
10073 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10074 header_prefix = "backout";
10075 else
10076 header_prefix = "cherrypick";
10078 TAILQ_FOREACH(re, &refs, entry) {
10079 const char *refname, *wt;
10081 refname = got_ref_get_name(re->ref);
10083 err = check_cancelled(NULL);
10084 if (err)
10085 goto done;
10087 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10088 refname += prefix_len + 1; /* skip '-' delimiter */
10089 else
10090 continue;
10092 wt = refname;
10094 if (worktree == NULL || strncmp(refname, uuidstr,
10095 GOT_WORKTREE_UUID_STRLEN) == 0)
10096 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10097 else
10098 continue;
10100 err = got_repo_match_object_id(&id, NULL, refname,
10101 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10102 if (err)
10103 goto done;
10105 err = got_object_open_as_commit(&commit, repo, id);
10106 if (err)
10107 goto done;
10109 if (wanted_ref)
10110 found = strncmp(wanted_ref, refname,
10111 strlen(wanted_ref)) == 0;
10112 if (wanted_ref && !found) {
10113 struct got_reflist_head *ci_refs;
10115 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10116 id);
10118 if (ci_refs) {
10119 char *refs_str = NULL;
10120 char const *r = NULL;
10122 err = build_refs_str(&refs_str, ci_refs, id,
10123 repo, 1);
10124 if (err)
10125 goto done;
10127 r = refs_str;
10128 while (r) {
10129 if (strncmp(r, wanted_ref,
10130 strlen(wanted_ref)) == 0) {
10131 found = 1;
10132 break;
10134 r = strchr(r, ' ');
10135 if (r)
10136 ++r;
10138 free(refs_str);
10142 if (wanted_ref == NULL || found) {
10143 if (delete) {
10144 err = got_ref_delete(re->ref, repo);
10145 if (err)
10146 goto done;
10147 printf("Deleted: ");
10148 err = print_commit_oneline(commit, id, repo,
10149 refs_idmap);
10150 } else {
10152 * Print paths modified by commit to help
10153 * associate commits with worktree changes.
10155 err = get_changed_paths(&paths, commit,
10156 repo, NULL);
10157 if (err)
10158 goto done;
10160 err = print_commit(commit, id, repo, NULL,
10161 &paths, NULL, 0, 0, refs_idmap, NULL,
10162 header_prefix);
10163 got_pathlist_free(&paths,
10164 GOT_PATHLIST_FREE_ALL);
10166 if (worktree == NULL)
10167 printf("work tree: %.*s\n\n",
10168 GOT_WORKTREE_UUID_STRLEN, wt);
10170 if (err || found)
10171 goto done;
10174 got_object_commit_close(commit);
10175 commit = NULL;
10176 free(id);
10177 id = NULL;
10180 if (wanted_ref != NULL && !found)
10181 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10183 done:
10184 free(id);
10185 free(uuidstr);
10186 got_ref_list_free(&refs);
10187 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10188 if (refs_idmap)
10189 got_reflist_object_id_map_free(refs_idmap);
10190 if (commit)
10191 got_object_commit_close(commit);
10192 return err;
10196 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10197 * identified by id for log messages to prepopulate the editor on commit.
10199 static const struct got_error *
10200 logmsg_ref(struct got_object_id *id, const char *prefix,
10201 struct got_worktree *worktree, struct got_repository *repo)
10203 const struct got_error *err = NULL;
10204 char *idstr, *ref = NULL, *refname = NULL;
10205 int histedit_in_progress;
10206 int rebase_in_progress, merge_in_progress;
10209 * Silenty refuse to create merge reference if any histedit, merge,
10210 * or rebase operation is in progress.
10212 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10213 worktree);
10214 if (err)
10215 return err;
10216 if (histedit_in_progress)
10217 return NULL;
10219 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10220 if (err)
10221 return err;
10222 if (rebase_in_progress)
10223 return NULL;
10225 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10226 repo);
10227 if (err)
10228 return err;
10229 if (merge_in_progress)
10230 return NULL;
10232 err = got_object_id_str(&idstr, id);
10233 if (err)
10234 return err;
10236 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10237 if (err)
10238 goto done;
10240 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10241 err = got_error_from_errno("asprintf");
10242 goto done;
10245 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10246 -1, repo);
10247 done:
10248 free(ref);
10249 free(idstr);
10250 free(refname);
10251 return err;
10254 __dead static void
10255 usage_cherrypick(void)
10257 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10258 getprogname());
10259 exit(1);
10262 static const struct got_error *
10263 cmd_cherrypick(int argc, char *argv[])
10265 const struct got_error *error = NULL;
10266 struct got_worktree *worktree = NULL;
10267 struct got_repository *repo = NULL;
10268 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10269 struct got_object_id *commit_id = NULL;
10270 struct got_commit_object *commit = NULL;
10271 struct got_object_qid *pid;
10272 int ch, list_refs = 0, remove_refs = 0;
10273 struct got_update_progress_arg upa;
10274 int *pack_fds = NULL;
10276 #ifndef PROFILE
10277 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10278 "unveil", NULL) == -1)
10279 err(1, "pledge");
10280 #endif
10282 while ((ch = getopt(argc, argv, "lX")) != -1) {
10283 switch (ch) {
10284 case 'l':
10285 list_refs = 1;
10286 break;
10287 case 'X':
10288 remove_refs = 1;
10289 break;
10290 default:
10291 usage_cherrypick();
10292 /* NOTREACHED */
10296 argc -= optind;
10297 argv += optind;
10299 if (list_refs || remove_refs) {
10300 if (argc != 0 && argc != 1)
10301 usage_cherrypick();
10302 } else if (argc != 1)
10303 usage_cherrypick();
10304 if (list_refs && remove_refs)
10305 option_conflict('l', 'X');
10307 cwd = getcwd(NULL, 0);
10308 if (cwd == NULL) {
10309 error = got_error_from_errno("getcwd");
10310 goto done;
10313 error = got_repo_pack_fds_open(&pack_fds);
10314 if (error != NULL)
10315 goto done;
10317 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10318 if (error) {
10319 if (list_refs || remove_refs) {
10320 if (error->code != GOT_ERR_NOT_WORKTREE)
10321 goto done;
10322 } else {
10323 if (error->code == GOT_ERR_NOT_WORKTREE)
10324 error = wrap_not_worktree_error(error,
10325 "cherrypick", cwd);
10326 goto done;
10330 error = got_repo_open(&repo,
10331 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10332 NULL, pack_fds);
10333 if (error != NULL)
10334 goto done;
10336 error = apply_unveil(got_repo_get_path(repo), 0,
10337 worktree ? got_worktree_get_root_path(worktree) : NULL);
10338 if (error)
10339 goto done;
10341 if (list_refs || remove_refs) {
10342 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10343 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10344 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10345 goto done;
10348 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10349 if (error != NULL)
10350 goto done;
10352 error = got_repo_match_object_id(&commit_id, NULL,
10353 keyword_idstr != NULL ? keyword_idstr : argv[0],
10354 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10355 if (error)
10356 goto done;
10357 error = got_object_id_str(&commit_id_str, commit_id);
10358 if (error)
10359 goto done;
10361 error = got_object_open_as_commit(&commit, repo, commit_id);
10362 if (error)
10363 goto done;
10364 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10365 memset(&upa, 0, sizeof(upa));
10366 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10367 commit_id, repo, update_progress, &upa, check_cancelled,
10368 NULL);
10369 if (error != NULL)
10370 goto done;
10372 if (upa.did_something) {
10373 error = logmsg_ref(commit_id,
10374 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10375 if (error)
10376 goto done;
10377 printf("Merged commit %s\n", commit_id_str);
10379 print_merge_progress_stats(&upa);
10380 done:
10381 free(cwd);
10382 free(keyword_idstr);
10383 if (commit)
10384 got_object_commit_close(commit);
10385 free(commit_id_str);
10386 if (worktree)
10387 got_worktree_close(worktree);
10388 if (repo) {
10389 const struct got_error *close_err = got_repo_close(repo);
10390 if (error == NULL)
10391 error = close_err;
10393 if (pack_fds) {
10394 const struct got_error *pack_err =
10395 got_repo_pack_fds_close(pack_fds);
10396 if (error == NULL)
10397 error = pack_err;
10400 return error;
10403 __dead static void
10404 usage_backout(void)
10406 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10407 exit(1);
10410 static const struct got_error *
10411 cmd_backout(int argc, char *argv[])
10413 const struct got_error *error = NULL;
10414 struct got_worktree *worktree = NULL;
10415 struct got_repository *repo = NULL;
10416 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10417 struct got_object_id *commit_id = NULL;
10418 struct got_commit_object *commit = NULL;
10419 struct got_object_qid *pid;
10420 int ch, list_refs = 0, remove_refs = 0;
10421 struct got_update_progress_arg upa;
10422 int *pack_fds = NULL;
10424 #ifndef PROFILE
10425 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10426 "unveil", NULL) == -1)
10427 err(1, "pledge");
10428 #endif
10430 while ((ch = getopt(argc, argv, "lX")) != -1) {
10431 switch (ch) {
10432 case 'l':
10433 list_refs = 1;
10434 break;
10435 case 'X':
10436 remove_refs = 1;
10437 break;
10438 default:
10439 usage_backout();
10440 /* NOTREACHED */
10444 argc -= optind;
10445 argv += optind;
10447 if (list_refs || remove_refs) {
10448 if (argc != 0 && argc != 1)
10449 usage_backout();
10450 } else if (argc != 1)
10451 usage_backout();
10452 if (list_refs && remove_refs)
10453 option_conflict('l', 'X');
10455 cwd = getcwd(NULL, 0);
10456 if (cwd == NULL) {
10457 error = got_error_from_errno("getcwd");
10458 goto done;
10461 error = got_repo_pack_fds_open(&pack_fds);
10462 if (error != NULL)
10463 goto done;
10465 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10466 if (error) {
10467 if (list_refs || remove_refs) {
10468 if (error->code != GOT_ERR_NOT_WORKTREE)
10469 goto done;
10470 } else {
10471 if (error->code == GOT_ERR_NOT_WORKTREE)
10472 error = wrap_not_worktree_error(error,
10473 "backout", cwd);
10474 goto done;
10478 error = got_repo_open(&repo,
10479 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10480 NULL, pack_fds);
10481 if (error != NULL)
10482 goto done;
10484 error = apply_unveil(got_repo_get_path(repo), 0,
10485 worktree ? got_worktree_get_root_path(worktree) : NULL);
10486 if (error)
10487 goto done;
10489 if (list_refs || remove_refs) {
10490 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10491 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10492 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10493 goto done;
10496 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10497 if (error != NULL)
10498 goto done;
10500 error = got_repo_match_object_id(&commit_id, NULL,
10501 keyword_idstr != NULL ? keyword_idstr : argv[0],
10502 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10503 if (error)
10504 goto done;
10505 error = got_object_id_str(&commit_id_str, commit_id);
10506 if (error)
10507 goto done;
10509 error = got_object_open_as_commit(&commit, repo, commit_id);
10510 if (error)
10511 goto done;
10512 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10513 if (pid == NULL) {
10514 error = got_error(GOT_ERR_ROOT_COMMIT);
10515 goto done;
10518 memset(&upa, 0, sizeof(upa));
10519 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10520 repo, update_progress, &upa, check_cancelled, NULL);
10521 if (error != NULL)
10522 goto done;
10524 if (upa.did_something) {
10525 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10526 worktree, repo);
10527 if (error)
10528 goto done;
10529 printf("Backed out commit %s\n", commit_id_str);
10531 print_merge_progress_stats(&upa);
10532 done:
10533 free(cwd);
10534 free(keyword_idstr);
10535 if (commit)
10536 got_object_commit_close(commit);
10537 free(commit_id_str);
10538 if (worktree)
10539 got_worktree_close(worktree);
10540 if (repo) {
10541 const struct got_error *close_err = got_repo_close(repo);
10542 if (error == NULL)
10543 error = close_err;
10545 if (pack_fds) {
10546 const struct got_error *pack_err =
10547 got_repo_pack_fds_close(pack_fds);
10548 if (error == NULL)
10549 error = pack_err;
10551 return error;
10554 __dead static void
10555 usage_rebase(void)
10557 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10558 exit(1);
10561 static void
10562 trim_logmsg(char *logmsg, int limit)
10564 char *nl;
10565 size_t len;
10567 len = strlen(logmsg);
10568 if (len > limit)
10569 len = limit;
10570 logmsg[len] = '\0';
10571 nl = strchr(logmsg, '\n');
10572 if (nl)
10573 *nl = '\0';
10576 static const struct got_error *
10577 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10579 const struct got_error *err;
10580 char *logmsg0 = NULL;
10581 const char *s;
10583 err = got_object_commit_get_logmsg(&logmsg0, commit);
10584 if (err)
10585 return err;
10587 s = logmsg0;
10588 while (isspace((unsigned char)s[0]))
10589 s++;
10591 *logmsg = strdup(s);
10592 if (*logmsg == NULL) {
10593 err = got_error_from_errno("strdup");
10594 goto done;
10597 trim_logmsg(*logmsg, limit);
10598 done:
10599 free(logmsg0);
10600 return err;
10603 static const struct got_error *
10604 show_rebase_merge_conflict(struct got_object_id *id,
10605 struct got_repository *repo)
10607 const struct got_error *err;
10608 struct got_commit_object *commit = NULL;
10609 char *id_str = NULL, *logmsg = NULL;
10611 err = got_object_open_as_commit(&commit, repo, id);
10612 if (err)
10613 return err;
10615 err = got_object_id_str(&id_str, id);
10616 if (err)
10617 goto done;
10619 id_str[12] = '\0';
10621 err = get_short_logmsg(&logmsg, 42, commit);
10622 if (err)
10623 goto done;
10625 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10626 done:
10627 free(id_str);
10628 got_object_commit_close(commit);
10629 free(logmsg);
10630 return err;
10633 static const struct got_error *
10634 show_rebase_progress(struct got_commit_object *commit,
10635 struct got_object_id *old_id, struct got_object_id *new_id)
10637 const struct got_error *err;
10638 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10640 err = got_object_id_str(&old_id_str, old_id);
10641 if (err)
10642 goto done;
10644 if (new_id) {
10645 err = got_object_id_str(&new_id_str, new_id);
10646 if (err)
10647 goto done;
10650 old_id_str[12] = '\0';
10651 if (new_id_str)
10652 new_id_str[12] = '\0';
10654 err = get_short_logmsg(&logmsg, 42, commit);
10655 if (err)
10656 goto done;
10658 printf("%s -> %s: %s\n", old_id_str,
10659 new_id_str ? new_id_str : "no-op change", logmsg);
10660 done:
10661 free(old_id_str);
10662 free(new_id_str);
10663 free(logmsg);
10664 return err;
10667 static const struct got_error *
10668 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10669 struct got_reference *branch, struct got_reference *tmp_branch,
10670 struct got_repository *repo, int create_backup)
10672 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10673 return got_worktree_rebase_complete(worktree, fileindex,
10674 tmp_branch, branch, repo, create_backup);
10677 static const struct got_error *
10678 rebase_commit(struct got_pathlist_head *merged_paths,
10679 struct got_worktree *worktree, struct got_fileindex *fileindex,
10680 struct got_reference *tmp_branch, const char *committer,
10681 struct got_object_id *commit_id, int allow_conflict,
10682 struct got_repository *repo)
10684 const struct got_error *error;
10685 struct got_commit_object *commit;
10686 struct got_object_id *new_commit_id;
10688 error = got_object_open_as_commit(&commit, repo, commit_id);
10689 if (error)
10690 return error;
10692 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10693 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10694 allow_conflict, repo);
10695 if (error) {
10696 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10697 goto done;
10698 error = show_rebase_progress(commit, commit_id, NULL);
10699 } else {
10700 error = show_rebase_progress(commit, commit_id, new_commit_id);
10701 free(new_commit_id);
10703 done:
10704 got_object_commit_close(commit);
10705 return error;
10708 struct check_path_prefix_arg {
10709 const char *path_prefix;
10710 size_t len;
10711 int errcode;
10714 static const struct got_error *
10715 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10716 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10717 struct got_object_id *id1, struct got_object_id *id2,
10718 const char *path1, const char *path2,
10719 mode_t mode1, mode_t mode2, struct got_repository *repo)
10721 struct check_path_prefix_arg *a = arg;
10723 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10724 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10725 return got_error(a->errcode);
10727 return NULL;
10730 static const struct got_error *
10731 check_path_prefix(struct got_object_id *parent_id,
10732 struct got_object_id *commit_id, const char *path_prefix,
10733 int errcode, struct got_repository *repo)
10735 const struct got_error *err;
10736 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10737 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10738 struct check_path_prefix_arg cpp_arg;
10740 if (got_path_is_root_dir(path_prefix))
10741 return NULL;
10743 err = got_object_open_as_commit(&commit, repo, commit_id);
10744 if (err)
10745 goto done;
10747 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10748 if (err)
10749 goto done;
10751 err = got_object_open_as_tree(&tree1, repo,
10752 got_object_commit_get_tree_id(parent_commit));
10753 if (err)
10754 goto done;
10756 err = got_object_open_as_tree(&tree2, repo,
10757 got_object_commit_get_tree_id(commit));
10758 if (err)
10759 goto done;
10761 cpp_arg.path_prefix = path_prefix;
10762 while (cpp_arg.path_prefix[0] == '/')
10763 cpp_arg.path_prefix++;
10764 cpp_arg.len = strlen(cpp_arg.path_prefix);
10765 cpp_arg.errcode = errcode;
10766 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10767 check_path_prefix_in_diff, &cpp_arg, 0);
10768 done:
10769 if (tree1)
10770 got_object_tree_close(tree1);
10771 if (tree2)
10772 got_object_tree_close(tree2);
10773 if (commit)
10774 got_object_commit_close(commit);
10775 if (parent_commit)
10776 got_object_commit_close(parent_commit);
10777 return err;
10780 static const struct got_error *
10781 collect_commits(struct got_object_id_queue *commits,
10782 struct got_object_id *initial_commit_id,
10783 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10784 const char *path_prefix, int path_prefix_errcode,
10785 struct got_repository *repo)
10787 const struct got_error *err = NULL;
10788 struct got_commit_graph *graph = NULL;
10789 struct got_object_id parent_id, commit_id;
10790 struct got_object_qid *qid;
10792 err = got_commit_graph_open(&graph, "/", 1);
10793 if (err)
10794 return err;
10796 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10797 check_cancelled, NULL);
10798 if (err)
10799 goto done;
10801 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10802 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10803 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10804 check_cancelled, NULL);
10805 if (err) {
10806 if (err->code == GOT_ERR_ITER_COMPLETED) {
10807 err = got_error_msg(GOT_ERR_ANCESTRY,
10808 "ran out of commits to rebase before "
10809 "youngest common ancestor commit has "
10810 "been reached?!?");
10812 goto done;
10813 } else {
10814 err = check_path_prefix(&parent_id, &commit_id,
10815 path_prefix, path_prefix_errcode, repo);
10816 if (err)
10817 goto done;
10819 err = got_object_qid_alloc(&qid, &commit_id);
10820 if (err)
10821 goto done;
10822 STAILQ_INSERT_HEAD(commits, qid, entry);
10824 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10827 done:
10828 got_commit_graph_close(graph);
10829 return err;
10832 static const struct got_error *
10833 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10835 const struct got_error *err = NULL;
10836 time_t committer_time;
10837 struct tm tm;
10838 char datebuf[11]; /* YYYY-MM-DD + NUL */
10839 char *author0 = NULL, *author, *smallerthan;
10840 char *logmsg0 = NULL, *logmsg, *newline;
10842 committer_time = got_object_commit_get_committer_time(commit);
10843 if (gmtime_r(&committer_time, &tm) == NULL)
10844 return got_error_from_errno("gmtime_r");
10845 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10846 return got_error(GOT_ERR_NO_SPACE);
10848 author0 = strdup(got_object_commit_get_author(commit));
10849 if (author0 == NULL)
10850 return got_error_from_errno("strdup");
10851 author = author0;
10852 smallerthan = strchr(author, '<');
10853 if (smallerthan && smallerthan[1] != '\0')
10854 author = smallerthan + 1;
10855 author[strcspn(author, "@>")] = '\0';
10857 err = got_object_commit_get_logmsg(&logmsg0, commit);
10858 if (err)
10859 goto done;
10860 logmsg = logmsg0;
10861 while (*logmsg == '\n')
10862 logmsg++;
10863 newline = strchr(logmsg, '\n');
10864 if (newline)
10865 *newline = '\0';
10867 if (asprintf(brief_str, "%s %s %s",
10868 datebuf, author, logmsg) == -1)
10869 err = got_error_from_errno("asprintf");
10870 done:
10871 free(author0);
10872 free(logmsg0);
10873 return err;
10876 static const struct got_error *
10877 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10878 struct got_repository *repo)
10880 const struct got_error *err;
10881 char *id_str;
10883 err = got_object_id_str(&id_str, id);
10884 if (err)
10885 return err;
10887 err = got_ref_delete(ref, repo);
10888 if (err)
10889 goto done;
10891 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10892 done:
10893 free(id_str);
10894 return err;
10897 static const struct got_error *
10898 print_backup_ref(const char *branch_name, const char *new_id_str,
10899 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10900 struct got_reflist_object_id_map *refs_idmap,
10901 struct got_repository *repo)
10903 const struct got_error *err = NULL;
10904 struct got_reflist_head *refs;
10905 char *refs_str = NULL;
10906 struct got_object_id *new_commit_id = NULL;
10907 struct got_commit_object *new_commit = NULL;
10908 char *new_commit_brief_str = NULL;
10909 struct got_object_id *yca_id = NULL;
10910 struct got_commit_object *yca_commit = NULL;
10911 char *yca_id_str = NULL, *yca_brief_str = NULL;
10912 char *custom_refs_str;
10914 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10915 return got_error_from_errno("asprintf");
10917 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10918 0, 0, refs_idmap, custom_refs_str, NULL);
10919 if (err)
10920 goto done;
10922 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10923 if (err)
10924 goto done;
10926 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10927 if (refs) {
10928 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10929 if (err)
10930 goto done;
10933 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10934 if (err)
10935 goto done;
10937 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10938 if (err)
10939 goto done;
10941 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10942 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10943 if (err)
10944 goto done;
10946 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10947 refs_str ? " (" : "", refs_str ? refs_str : "",
10948 refs_str ? ")" : "", new_commit_brief_str);
10949 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10950 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10951 free(refs_str);
10952 refs_str = NULL;
10954 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10955 if (err)
10956 goto done;
10958 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10959 if (err)
10960 goto done;
10962 err = got_object_id_str(&yca_id_str, yca_id);
10963 if (err)
10964 goto done;
10966 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10967 if (refs) {
10968 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10969 if (err)
10970 goto done;
10972 printf("history forked at %s%s%s%s\n %s\n",
10973 yca_id_str,
10974 refs_str ? " (" : "", refs_str ? refs_str : "",
10975 refs_str ? ")" : "", yca_brief_str);
10977 done:
10978 free(custom_refs_str);
10979 free(new_commit_id);
10980 free(refs_str);
10981 free(yca_id);
10982 free(yca_id_str);
10983 free(yca_brief_str);
10984 if (new_commit)
10985 got_object_commit_close(new_commit);
10986 if (yca_commit)
10987 got_object_commit_close(yca_commit);
10989 return err;
10992 static const struct got_error *
10993 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10994 struct got_repository *repo)
10996 const struct got_error *err;
10997 struct got_reflist_head refs;
10998 struct got_reflist_entry *re;
10999 char *uuidstr = NULL;
11000 static char msg[160];
11002 TAILQ_INIT(&refs);
11004 err = got_worktree_get_uuid(&uuidstr, worktree);
11005 if (err)
11006 goto done;
11008 err = got_ref_list(&refs, repo, "refs/got/worktree",
11009 got_ref_cmp_by_name, repo);
11010 if (err)
11011 goto done;
11013 TAILQ_FOREACH(re, &refs, entry) {
11014 const char *cmd, *refname, *type;
11016 refname = got_ref_get_name(re->ref);
11018 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11019 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11020 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11021 cmd = "cherrypick";
11022 type = "cherrypicked";
11023 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11024 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11025 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11026 cmd = "backout";
11027 type = "backed-out";
11028 } else
11029 continue;
11031 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11032 continue;
11034 snprintf(msg, sizeof(msg),
11035 "work tree has references created by %s commits which "
11036 "must be removed with 'got %s -X' before running the %s "
11037 "command", type, cmd, caller);
11038 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11039 goto done;
11042 done:
11043 free(uuidstr);
11044 got_ref_list_free(&refs);
11045 return err;
11048 static const struct got_error *
11049 process_backup_refs(const char *backup_ref_prefix,
11050 const char *wanted_branch_name,
11051 int delete, struct got_repository *repo)
11053 const struct got_error *err;
11054 struct got_reflist_head refs, backup_refs;
11055 struct got_reflist_entry *re;
11056 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11057 struct got_object_id *old_commit_id = NULL;
11058 char *branch_name = NULL;
11059 struct got_commit_object *old_commit = NULL;
11060 struct got_reflist_object_id_map *refs_idmap = NULL;
11061 int wanted_branch_found = 0;
11063 TAILQ_INIT(&refs);
11064 TAILQ_INIT(&backup_refs);
11066 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11067 if (err)
11068 return err;
11070 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11071 if (err)
11072 goto done;
11074 if (wanted_branch_name) {
11075 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11076 wanted_branch_name += 11;
11079 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11080 got_ref_cmp_by_commit_timestamp_descending, repo);
11081 if (err)
11082 goto done;
11084 TAILQ_FOREACH(re, &backup_refs, entry) {
11085 const char *refname = got_ref_get_name(re->ref);
11086 char *slash;
11088 err = check_cancelled(NULL);
11089 if (err)
11090 break;
11092 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11093 if (err)
11094 break;
11096 err = got_object_open_as_commit(&old_commit, repo,
11097 old_commit_id);
11098 if (err)
11099 break;
11101 if (strncmp(backup_ref_prefix, refname,
11102 backup_ref_prefix_len) == 0)
11103 refname += backup_ref_prefix_len;
11105 while (refname[0] == '/')
11106 refname++;
11108 branch_name = strdup(refname);
11109 if (branch_name == NULL) {
11110 err = got_error_from_errno("strdup");
11111 break;
11113 slash = strrchr(branch_name, '/');
11114 if (slash) {
11115 *slash = '\0';
11116 refname += strlen(branch_name) + 1;
11119 if (wanted_branch_name == NULL ||
11120 strcmp(wanted_branch_name, branch_name) == 0) {
11121 wanted_branch_found = 1;
11122 if (delete) {
11123 err = delete_backup_ref(re->ref,
11124 old_commit_id, repo);
11125 } else {
11126 err = print_backup_ref(branch_name, refname,
11127 old_commit_id, old_commit, refs_idmap,
11128 repo);
11130 if (err)
11131 break;
11134 free(old_commit_id);
11135 old_commit_id = NULL;
11136 free(branch_name);
11137 branch_name = NULL;
11138 got_object_commit_close(old_commit);
11139 old_commit = NULL;
11142 if (wanted_branch_name && !wanted_branch_found) {
11143 err = got_error_fmt(GOT_ERR_NOT_REF,
11144 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11146 done:
11147 if (refs_idmap)
11148 got_reflist_object_id_map_free(refs_idmap);
11149 got_ref_list_free(&refs);
11150 got_ref_list_free(&backup_refs);
11151 free(old_commit_id);
11152 free(branch_name);
11153 if (old_commit)
11154 got_object_commit_close(old_commit);
11155 return err;
11158 static const struct got_error *
11159 abort_progress(void *arg, unsigned char status, const char *path)
11162 * Unversioned files should not clutter progress output when
11163 * an operation is aborted.
11165 if (status == GOT_STATUS_UNVERSIONED)
11166 return NULL;
11168 return update_progress(arg, status, path);
11171 static const struct got_error *
11172 cmd_rebase(int argc, char *argv[])
11174 const struct got_error *error = NULL;
11175 struct got_worktree *worktree = NULL;
11176 struct got_repository *repo = NULL;
11177 struct got_fileindex *fileindex = NULL;
11178 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11179 struct got_reference *branch = NULL;
11180 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11181 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11182 struct got_object_id *resume_commit_id = NULL;
11183 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11184 struct got_object_id *head_commit_id = NULL;
11185 struct got_reference *head_ref = NULL;
11186 struct got_commit_object *commit = NULL;
11187 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11188 int histedit_in_progress = 0, merge_in_progress = 0;
11189 int create_backup = 1, list_backups = 0, delete_backups = 0;
11190 int allow_conflict = 0;
11191 struct got_object_id_queue commits;
11192 struct got_pathlist_head merged_paths;
11193 const struct got_object_id_queue *parent_ids;
11194 struct got_object_qid *qid, *pid;
11195 struct got_update_progress_arg upa;
11196 int *pack_fds = NULL;
11198 STAILQ_INIT(&commits);
11199 TAILQ_INIT(&merged_paths);
11200 memset(&upa, 0, sizeof(upa));
11202 #ifndef PROFILE
11203 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11204 "unveil", NULL) == -1)
11205 err(1, "pledge");
11206 #endif
11208 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11209 switch (ch) {
11210 case 'a':
11211 abort_rebase = 1;
11212 break;
11213 case 'C':
11214 allow_conflict = 1;
11215 break;
11216 case 'c':
11217 continue_rebase = 1;
11218 break;
11219 case 'l':
11220 list_backups = 1;
11221 break;
11222 case 'X':
11223 delete_backups = 1;
11224 break;
11225 default:
11226 usage_rebase();
11227 /* NOTREACHED */
11231 argc -= optind;
11232 argv += optind;
11234 if (list_backups) {
11235 if (abort_rebase)
11236 option_conflict('l', 'a');
11237 if (allow_conflict)
11238 option_conflict('l', 'C');
11239 if (continue_rebase)
11240 option_conflict('l', 'c');
11241 if (delete_backups)
11242 option_conflict('l', 'X');
11243 if (argc != 0 && argc != 1)
11244 usage_rebase();
11245 } else if (delete_backups) {
11246 if (abort_rebase)
11247 option_conflict('X', 'a');
11248 if (allow_conflict)
11249 option_conflict('X', 'C');
11250 if (continue_rebase)
11251 option_conflict('X', 'c');
11252 if (list_backups)
11253 option_conflict('l', 'X');
11254 if (argc != 0 && argc != 1)
11255 usage_rebase();
11256 } else if (allow_conflict) {
11257 if (abort_rebase)
11258 option_conflict('C', 'a');
11259 if (!continue_rebase)
11260 errx(1, "-C option requires -c");
11261 } else {
11262 if (abort_rebase && continue_rebase)
11263 usage_rebase();
11264 else if (abort_rebase || continue_rebase) {
11265 if (argc != 0)
11266 usage_rebase();
11267 } else if (argc != 1)
11268 usage_rebase();
11271 cwd = getcwd(NULL, 0);
11272 if (cwd == NULL) {
11273 error = got_error_from_errno("getcwd");
11274 goto done;
11277 error = got_repo_pack_fds_open(&pack_fds);
11278 if (error != NULL)
11279 goto done;
11281 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11282 if (error) {
11283 if (list_backups || delete_backups) {
11284 if (error->code != GOT_ERR_NOT_WORKTREE)
11285 goto done;
11286 } else {
11287 if (error->code == GOT_ERR_NOT_WORKTREE)
11288 error = wrap_not_worktree_error(error,
11289 "rebase", cwd);
11290 goto done;
11294 error = get_gitconfig_path(&gitconfig_path);
11295 if (error)
11296 goto done;
11297 error = got_repo_open(&repo,
11298 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11299 gitconfig_path, pack_fds);
11300 if (error != NULL)
11301 goto done;
11303 if (worktree != NULL && !list_backups && !delete_backups) {
11304 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11305 if (error)
11306 goto done;
11309 error = get_author(&committer, repo, worktree);
11310 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11311 goto done;
11313 error = apply_unveil(got_repo_get_path(repo), 0,
11314 worktree ? got_worktree_get_root_path(worktree) : NULL);
11315 if (error)
11316 goto done;
11318 if (list_backups || delete_backups) {
11319 error = process_backup_refs(
11320 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11321 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11322 goto done; /* nothing else to do */
11325 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11326 worktree);
11327 if (error)
11328 goto done;
11329 if (histedit_in_progress) {
11330 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11331 goto done;
11334 error = got_worktree_merge_in_progress(&merge_in_progress,
11335 worktree, repo);
11336 if (error)
11337 goto done;
11338 if (merge_in_progress) {
11339 error = got_error(GOT_ERR_MERGE_BUSY);
11340 goto done;
11343 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11344 if (error)
11345 goto done;
11347 if (abort_rebase) {
11348 if (!rebase_in_progress) {
11349 error = got_error(GOT_ERR_NOT_REBASING);
11350 goto done;
11352 error = got_worktree_rebase_continue(&resume_commit_id,
11353 &new_base_branch, &tmp_branch, &branch, &fileindex,
11354 worktree, repo);
11355 if (error)
11356 goto done;
11357 printf("Switching work tree to %s\n",
11358 got_ref_get_symref_target(new_base_branch));
11359 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11360 new_base_branch, abort_progress, &upa);
11361 if (error)
11362 goto done;
11363 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11364 print_merge_progress_stats(&upa);
11365 goto done; /* nothing else to do */
11368 if (continue_rebase) {
11369 if (!rebase_in_progress) {
11370 error = got_error(GOT_ERR_NOT_REBASING);
11371 goto done;
11373 error = got_worktree_rebase_continue(&resume_commit_id,
11374 &new_base_branch, &tmp_branch, &branch, &fileindex,
11375 worktree, repo);
11376 if (error)
11377 goto done;
11379 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11380 committer, resume_commit_id, allow_conflict, repo);
11381 if (error)
11382 goto done;
11384 yca_id = got_object_id_dup(resume_commit_id);
11385 if (yca_id == NULL) {
11386 error = got_error_from_errno("got_object_id_dup");
11387 goto done;
11389 } else {
11390 error = got_ref_open(&branch, repo, argv[0], 0);
11391 if (error != NULL)
11392 goto done;
11393 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11394 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11395 "will not rebase a branch which lives outside "
11396 "the \"refs/heads/\" reference namespace");
11397 goto done;
11401 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11402 if (error)
11403 goto done;
11405 if (!continue_rebase) {
11406 struct got_object_id *base_commit_id;
11408 error = got_ref_open(&head_ref, repo,
11409 got_worktree_get_head_ref_name(worktree), 0);
11410 if (error)
11411 goto done;
11412 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11413 if (error)
11414 goto done;
11415 base_commit_id = got_worktree_get_base_commit_id(worktree);
11416 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11417 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11418 goto done;
11421 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11422 base_commit_id, branch_head_commit_id, 1, repo,
11423 check_cancelled, NULL);
11424 if (error) {
11425 if (error->code == GOT_ERR_ANCESTRY) {
11426 error = got_error_msg(GOT_ERR_ANCESTRY,
11427 "specified branch shares no common "
11428 "ancestry with work tree's branch");
11430 goto done;
11433 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11434 struct got_pathlist_head paths;
11435 printf("%s is already based on %s\n",
11436 got_ref_get_name(branch),
11437 got_worktree_get_head_ref_name(worktree));
11438 error = switch_head_ref(branch, branch_head_commit_id,
11439 worktree, repo);
11440 if (error)
11441 goto done;
11442 error = got_worktree_set_base_commit_id(worktree, repo,
11443 branch_head_commit_id);
11444 if (error)
11445 goto done;
11446 TAILQ_INIT(&paths);
11447 error = got_pathlist_append(&paths, "", NULL);
11448 if (error)
11449 goto done;
11450 error = got_worktree_checkout_files(worktree,
11451 &paths, repo, update_progress, &upa,
11452 check_cancelled, NULL);
11453 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11454 if (error)
11455 goto done;
11456 if (upa.did_something) {
11457 char *id_str;
11458 error = got_object_id_str(&id_str,
11459 branch_head_commit_id);
11460 if (error)
11461 goto done;
11462 printf("Updated to %s: %s\n",
11463 got_worktree_get_head_ref_name(worktree),
11464 id_str);
11465 free(id_str);
11466 } else
11467 printf("Already up-to-date\n");
11468 print_update_progress_stats(&upa);
11469 goto done;
11473 commit_id = branch_head_commit_id;
11474 error = got_object_open_as_commit(&commit, repo, commit_id);
11475 if (error)
11476 goto done;
11478 parent_ids = got_object_commit_get_parent_ids(commit);
11479 pid = STAILQ_FIRST(parent_ids);
11480 if (pid) {
11481 error = collect_commits(&commits, commit_id, &pid->id,
11482 yca_id, got_worktree_get_path_prefix(worktree),
11483 GOT_ERR_REBASE_PATH, repo);
11484 if (error)
11485 goto done;
11488 got_object_commit_close(commit);
11489 commit = NULL;
11491 if (!continue_rebase) {
11492 error = got_worktree_rebase_prepare(&new_base_branch,
11493 &tmp_branch, &fileindex, worktree, branch, repo);
11494 if (error)
11495 goto done;
11498 if (STAILQ_EMPTY(&commits)) {
11499 if (continue_rebase) {
11500 error = rebase_complete(worktree, fileindex,
11501 branch, tmp_branch, repo, create_backup);
11502 goto done;
11503 } else {
11504 /* Fast-forward the reference of the branch. */
11505 struct got_object_id *new_head_commit_id;
11506 char *id_str;
11507 error = got_ref_resolve(&new_head_commit_id, repo,
11508 new_base_branch);
11509 if (error)
11510 goto done;
11511 error = got_object_id_str(&id_str, new_head_commit_id);
11512 if (error)
11513 goto done;
11514 printf("Forwarding %s to commit %s\n",
11515 got_ref_get_name(branch), id_str);
11516 free(id_str);
11517 error = got_ref_change_ref(branch,
11518 new_head_commit_id);
11519 if (error)
11520 goto done;
11521 /* No backup needed since objects did not change. */
11522 create_backup = 0;
11526 pid = NULL;
11527 STAILQ_FOREACH(qid, &commits, entry) {
11529 commit_id = &qid->id;
11530 parent_id = pid ? &pid->id : yca_id;
11531 pid = qid;
11533 memset(&upa, 0, sizeof(upa));
11534 error = got_worktree_rebase_merge_files(&merged_paths,
11535 worktree, fileindex, parent_id, commit_id, repo,
11536 update_progress, &upa, check_cancelled, NULL);
11537 if (error)
11538 goto done;
11540 print_merge_progress_stats(&upa);
11541 if (upa.conflicts > 0 || upa.missing > 0 ||
11542 upa.not_deleted > 0 || upa.unversioned > 0) {
11543 if (upa.conflicts > 0) {
11544 error = show_rebase_merge_conflict(&qid->id,
11545 repo);
11546 if (error)
11547 goto done;
11549 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11550 break;
11553 error = rebase_commit(&merged_paths, worktree, fileindex,
11554 tmp_branch, committer, commit_id, 0, repo);
11555 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11556 if (error)
11557 goto done;
11560 if (upa.conflicts > 0 || upa.missing > 0 ||
11561 upa.not_deleted > 0 || upa.unversioned > 0) {
11562 error = got_worktree_rebase_postpone(worktree, fileindex);
11563 if (error)
11564 goto done;
11565 if (upa.conflicts > 0 && upa.missing == 0 &&
11566 upa.not_deleted == 0 && upa.unversioned == 0) {
11567 error = got_error_msg(GOT_ERR_CONFLICTS,
11568 "conflicts must be resolved before rebasing "
11569 "can continue");
11570 } else if (upa.conflicts > 0) {
11571 error = got_error_msg(GOT_ERR_CONFLICTS,
11572 "conflicts must be resolved before rebasing "
11573 "can continue; changes destined for some "
11574 "files were not yet merged and should be "
11575 "merged manually if required before the "
11576 "rebase operation is continued");
11577 } else {
11578 error = got_error_msg(GOT_ERR_CONFLICTS,
11579 "changes destined for some files were not "
11580 "yet merged and should be merged manually "
11581 "if required before the rebase operation "
11582 "is continued");
11584 } else
11585 error = rebase_complete(worktree, fileindex, branch,
11586 tmp_branch, repo, create_backup);
11587 done:
11588 free(cwd);
11589 free(committer);
11590 free(gitconfig_path);
11591 got_object_id_queue_free(&commits);
11592 free(branch_head_commit_id);
11593 free(resume_commit_id);
11594 free(head_commit_id);
11595 free(yca_id);
11596 if (commit)
11597 got_object_commit_close(commit);
11598 if (branch)
11599 got_ref_close(branch);
11600 if (new_base_branch)
11601 got_ref_close(new_base_branch);
11602 if (tmp_branch)
11603 got_ref_close(tmp_branch);
11604 if (head_ref)
11605 got_ref_close(head_ref);
11606 if (worktree)
11607 got_worktree_close(worktree);
11608 if (repo) {
11609 const struct got_error *close_err = got_repo_close(repo);
11610 if (error == NULL)
11611 error = close_err;
11613 if (pack_fds) {
11614 const struct got_error *pack_err =
11615 got_repo_pack_fds_close(pack_fds);
11616 if (error == NULL)
11617 error = pack_err;
11619 return error;
11622 __dead static void
11623 usage_histedit(void)
11625 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11626 "[branch]\n", getprogname());
11627 exit(1);
11630 #define GOT_HISTEDIT_PICK 'p'
11631 #define GOT_HISTEDIT_EDIT 'e'
11632 #define GOT_HISTEDIT_FOLD 'f'
11633 #define GOT_HISTEDIT_DROP 'd'
11634 #define GOT_HISTEDIT_MESG 'm'
11636 static const struct got_histedit_cmd {
11637 unsigned char code;
11638 const char *name;
11639 const char *desc;
11640 } got_histedit_cmds[] = {
11641 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11642 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11643 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11644 "be used" },
11645 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11646 { GOT_HISTEDIT_MESG, "mesg",
11647 "single-line log message for commit above (open editor if empty)" },
11650 struct got_histedit_list_entry {
11651 TAILQ_ENTRY(got_histedit_list_entry) entry;
11652 struct got_object_id *commit_id;
11653 const struct got_histedit_cmd *cmd;
11654 char *logmsg;
11656 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11658 static const struct got_error *
11659 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11660 FILE *f, struct got_repository *repo)
11662 const struct got_error *err = NULL;
11663 char *logmsg = NULL, *id_str = NULL;
11664 struct got_commit_object *commit = NULL;
11665 int n;
11667 err = got_object_open_as_commit(&commit, repo, commit_id);
11668 if (err)
11669 goto done;
11671 err = get_short_logmsg(&logmsg, 34, commit);
11672 if (err)
11673 goto done;
11675 err = got_object_id_str(&id_str, commit_id);
11676 if (err)
11677 goto done;
11679 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11680 if (n < 0)
11681 err = got_ferror(f, GOT_ERR_IO);
11682 done:
11683 if (commit)
11684 got_object_commit_close(commit);
11685 free(id_str);
11686 free(logmsg);
11687 return err;
11690 static const struct got_error *
11691 histedit_write_commit_list(struct got_object_id_queue *commits,
11692 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11693 int edit_only, struct got_repository *repo)
11695 const struct got_error *err = NULL;
11696 struct got_object_qid *qid;
11697 const char *histedit_cmd = NULL;
11699 if (STAILQ_EMPTY(commits))
11700 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11702 STAILQ_FOREACH(qid, commits, entry) {
11703 histedit_cmd = got_histedit_cmds[0].name;
11704 if (drop_only)
11705 histedit_cmd = "drop";
11706 else if (edit_only)
11707 histedit_cmd = "edit";
11708 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11709 histedit_cmd = "fold";
11710 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11711 if (err)
11712 break;
11713 if (edit_logmsg_only) {
11714 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11715 if (n < 0) {
11716 err = got_ferror(f, GOT_ERR_IO);
11717 break;
11722 return err;
11725 static const struct got_error *
11726 write_cmd_list(FILE *f, const char *branch_name,
11727 struct got_object_id_queue *commits)
11729 const struct got_error *err = NULL;
11730 size_t i;
11731 int n;
11732 char *id_str;
11733 struct got_object_qid *qid;
11735 qid = STAILQ_FIRST(commits);
11736 err = got_object_id_str(&id_str, &qid->id);
11737 if (err)
11738 return err;
11740 n = fprintf(f,
11741 "# Editing the history of branch '%s' starting at\n"
11742 "# commit %s\n"
11743 "# Commits will be processed in order from top to "
11744 "bottom of this file.\n", branch_name, id_str);
11745 if (n < 0) {
11746 err = got_ferror(f, GOT_ERR_IO);
11747 goto done;
11750 n = fprintf(f, "# Available histedit commands:\n");
11751 if (n < 0) {
11752 err = got_ferror(f, GOT_ERR_IO);
11753 goto done;
11756 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11757 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11758 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11759 cmd->desc);
11760 if (n < 0) {
11761 err = got_ferror(f, GOT_ERR_IO);
11762 break;
11765 done:
11766 free(id_str);
11767 return err;
11770 static const struct got_error *
11771 histedit_syntax_error(int lineno)
11773 static char msg[42];
11774 int ret;
11776 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11777 lineno);
11778 if (ret < 0 || (size_t)ret >= sizeof(msg))
11779 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11781 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11784 static const struct got_error *
11785 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11786 char *logmsg, struct got_repository *repo)
11788 const struct got_error *err;
11789 struct got_commit_object *folded_commit = NULL;
11790 char *id_str, *folded_logmsg = NULL;
11792 err = got_object_id_str(&id_str, hle->commit_id);
11793 if (err)
11794 return err;
11796 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11797 if (err)
11798 goto done;
11800 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11801 if (err)
11802 goto done;
11803 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11804 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11805 folded_logmsg) == -1) {
11806 err = got_error_from_errno("asprintf");
11808 done:
11809 if (folded_commit)
11810 got_object_commit_close(folded_commit);
11811 free(id_str);
11812 free(folded_logmsg);
11813 return err;
11816 static struct got_histedit_list_entry *
11817 get_folded_commits(struct got_histedit_list_entry *hle)
11819 struct got_histedit_list_entry *prev, *folded = NULL;
11821 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11822 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11823 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11824 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11825 folded = prev;
11826 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11829 return folded;
11832 static const struct got_error *
11833 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11834 struct got_repository *repo)
11836 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11837 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11838 const struct got_error *err = NULL;
11839 struct got_commit_object *commit = NULL;
11840 int logmsg_len;
11841 int fd = -1;
11842 struct got_histedit_list_entry *folded = NULL;
11844 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11845 if (err)
11846 return err;
11848 folded = get_folded_commits(hle);
11849 if (folded) {
11850 while (folded != hle) {
11851 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11852 folded = TAILQ_NEXT(folded, entry);
11853 continue;
11855 err = append_folded_commit_msg(&new_msg, folded,
11856 logmsg, repo);
11857 if (err)
11858 goto done;
11859 free(logmsg);
11860 logmsg = new_msg;
11861 folded = TAILQ_NEXT(folded, entry);
11865 err = got_object_id_str(&id_str, hle->commit_id);
11866 if (err)
11867 goto done;
11868 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11869 if (err)
11870 goto done;
11871 logmsg_len = asprintf(&new_msg,
11872 "%s\n# original log message of commit %s: %s",
11873 logmsg ? logmsg : "", id_str, orig_logmsg);
11874 if (logmsg_len == -1) {
11875 err = got_error_from_errno("asprintf");
11876 goto done;
11878 free(logmsg);
11879 logmsg = new_msg;
11881 err = got_object_id_str(&id_str, hle->commit_id);
11882 if (err)
11883 goto done;
11885 err = got_opentemp_named_fd(&logmsg_path, &fd,
11886 GOT_TMPDIR_STR "/got-logmsg", "");
11887 if (err)
11888 goto done;
11890 if (write(fd, logmsg, logmsg_len) == -1) {
11891 err = got_error_from_errno2("write", logmsg_path);
11892 goto done;
11894 if (close(fd) == -1) {
11895 err = got_error_from_errno2("close", logmsg_path);
11896 goto done;
11898 fd = -1;
11900 err = get_editor(&editor);
11901 if (err)
11902 goto done;
11904 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11905 logmsg_len, 0);
11906 if (err) {
11907 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11908 goto done;
11909 err = NULL;
11910 hle->logmsg = strdup(new_msg);
11911 if (hle->logmsg == NULL)
11912 err = got_error_from_errno("strdup");
11914 done:
11915 if (fd != -1 && close(fd) == -1 && err == NULL)
11916 err = got_error_from_errno2("close", logmsg_path);
11917 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11918 err = got_error_from_errno2("unlink", logmsg_path);
11919 free(logmsg_path);
11920 free(logmsg);
11921 free(orig_logmsg);
11922 free(editor);
11923 if (commit)
11924 got_object_commit_close(commit);
11925 return err;
11928 static const struct got_error *
11929 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11930 FILE *f, struct got_repository *repo)
11932 const struct got_error *err = NULL;
11933 char *line = NULL, *p, *end;
11934 size_t i, linesize = 0;
11935 ssize_t linelen;
11936 int lineno = 0, lastcmd = -1;
11937 const struct got_histedit_cmd *cmd;
11938 struct got_object_id *commit_id = NULL;
11939 struct got_histedit_list_entry *hle = NULL;
11941 for (;;) {
11942 linelen = getline(&line, &linesize, f);
11943 if (linelen == -1) {
11944 const struct got_error *getline_err;
11945 if (feof(f))
11946 break;
11947 getline_err = got_error_from_errno("getline");
11948 err = got_ferror(f, getline_err->code);
11949 break;
11951 lineno++;
11952 p = line;
11953 while (isspace((unsigned char)p[0]))
11954 p++;
11955 if (p[0] == '#' || p[0] == '\0')
11956 continue;
11957 cmd = NULL;
11958 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11959 cmd = &got_histedit_cmds[i];
11960 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11961 isspace((unsigned char)p[strlen(cmd->name)])) {
11962 p += strlen(cmd->name);
11963 break;
11965 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11966 p++;
11967 break;
11970 if (i == nitems(got_histedit_cmds)) {
11971 err = histedit_syntax_error(lineno);
11972 break;
11974 while (isspace((unsigned char)p[0]))
11975 p++;
11976 if (cmd->code == GOT_HISTEDIT_MESG) {
11977 if (lastcmd != GOT_HISTEDIT_PICK &&
11978 lastcmd != GOT_HISTEDIT_EDIT) {
11979 err = got_error(GOT_ERR_HISTEDIT_CMD);
11980 break;
11982 if (p[0] == '\0') {
11983 err = histedit_edit_logmsg(hle, repo);
11984 if (err)
11985 break;
11986 } else {
11987 hle->logmsg = strdup(p);
11988 if (hle->logmsg == NULL) {
11989 err = got_error_from_errno("strdup");
11990 break;
11993 lastcmd = cmd->code;
11994 continue;
11995 } else {
11996 end = p;
11997 while (end[0] && !isspace((unsigned char)end[0]))
11998 end++;
11999 *end = '\0';
12001 err = got_object_resolve_id_str(&commit_id, repo, p);
12002 if (err) {
12003 /* override error code */
12004 err = histedit_syntax_error(lineno);
12005 break;
12008 hle = malloc(sizeof(*hle));
12009 if (hle == NULL) {
12010 err = got_error_from_errno("malloc");
12011 break;
12013 hle->cmd = cmd;
12014 hle->commit_id = commit_id;
12015 hle->logmsg = NULL;
12016 commit_id = NULL;
12017 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12018 lastcmd = cmd->code;
12021 free(line);
12022 free(commit_id);
12023 return err;
12026 static const struct got_error *
12027 histedit_check_script(struct got_histedit_list *histedit_cmds,
12028 struct got_object_id_queue *commits, struct got_repository *repo)
12030 const struct got_error *err = NULL;
12031 struct got_object_qid *qid;
12032 struct got_histedit_list_entry *hle;
12033 static char msg[92];
12034 char *id_str;
12036 if (TAILQ_EMPTY(histedit_cmds))
12037 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12038 "histedit script contains no commands");
12039 if (STAILQ_EMPTY(commits))
12040 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12042 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12043 struct got_histedit_list_entry *hle2;
12044 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12045 if (hle == hle2)
12046 continue;
12047 if (got_object_id_cmp(hle->commit_id,
12048 hle2->commit_id) != 0)
12049 continue;
12050 err = got_object_id_str(&id_str, hle->commit_id);
12051 if (err)
12052 return err;
12053 snprintf(msg, sizeof(msg), "commit %s is listed "
12054 "more than once in histedit script", id_str);
12055 free(id_str);
12056 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12060 STAILQ_FOREACH(qid, commits, entry) {
12061 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12062 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12063 break;
12065 if (hle == NULL) {
12066 err = got_object_id_str(&id_str, &qid->id);
12067 if (err)
12068 return err;
12069 snprintf(msg, sizeof(msg),
12070 "commit %s missing from histedit script", id_str);
12071 free(id_str);
12072 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12076 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12077 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12078 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12079 "last commit in histedit script cannot be folded");
12081 return NULL;
12084 static const struct got_error *
12085 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12086 const char *path, struct got_object_id_queue *commits,
12087 struct got_repository *repo)
12089 const struct got_error *err = NULL;
12090 struct stat st, st2;
12091 struct timespec timeout;
12092 char *editor;
12093 FILE *f = NULL;
12095 err = get_editor(&editor);
12096 if (err)
12097 return err;
12099 if (stat(path, &st) == -1) {
12100 err = got_error_from_errno2("stat", path);
12101 goto done;
12104 if (spawn_editor(editor, path) == -1) {
12105 err = got_error_from_errno("failed spawning editor");
12106 goto done;
12109 timeout.tv_sec = 0;
12110 timeout.tv_nsec = 1;
12111 nanosleep(&timeout, NULL);
12113 if (stat(path, &st2) == -1) {
12114 err = got_error_from_errno2("stat", path);
12115 goto done;
12118 if (st.st_size == st2.st_size &&
12119 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12120 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12121 "no changes made to histedit script, aborting");
12122 goto done;
12125 f = fopen(path, "re");
12126 if (f == NULL) {
12127 err = got_error_from_errno("fopen");
12128 goto done;
12130 err = histedit_parse_list(histedit_cmds, f, repo);
12131 if (err)
12132 goto done;
12134 err = histedit_check_script(histedit_cmds, commits, repo);
12135 done:
12136 if (f && fclose(f) == EOF && err == NULL)
12137 err = got_error_from_errno("fclose");
12138 free(editor);
12139 return err;
12142 static const struct got_error *
12143 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12144 struct got_object_id_queue *, const char *, const char *,
12145 struct got_repository *);
12147 static const struct got_error *
12148 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12149 struct got_object_id_queue *commits, const char *branch_name,
12150 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12151 struct got_repository *repo)
12153 const struct got_error *err;
12154 FILE *f = NULL;
12155 char *path = NULL;
12157 err = got_opentemp_named(&path, &f, "got-histedit", "");
12158 if (err)
12159 return err;
12161 err = write_cmd_list(f, branch_name, commits);
12162 if (err)
12163 goto done;
12165 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12166 fold_only, drop_only, edit_only, repo);
12167 if (err)
12168 goto done;
12170 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12171 rewind(f);
12172 err = histedit_parse_list(histedit_cmds, f, repo);
12173 } else {
12174 if (fclose(f) == EOF) {
12175 err = got_error_from_errno("fclose");
12176 goto done;
12178 f = NULL;
12179 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12180 if (err) {
12181 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12182 err->code != GOT_ERR_HISTEDIT_CMD)
12183 goto done;
12184 err = histedit_edit_list_retry(histedit_cmds, err,
12185 commits, path, branch_name, repo);
12188 done:
12189 if (f && fclose(f) == EOF && err == NULL)
12190 err = got_error_from_errno("fclose");
12191 if (path && unlink(path) != 0 && err == NULL)
12192 err = got_error_from_errno2("unlink", path);
12193 free(path);
12194 return err;
12197 static const struct got_error *
12198 histedit_save_list(struct got_histedit_list *histedit_cmds,
12199 struct got_worktree *worktree, struct got_repository *repo)
12201 const struct got_error *err = NULL;
12202 char *path = NULL;
12203 FILE *f = NULL;
12204 struct got_histedit_list_entry *hle;
12205 struct got_commit_object *commit = NULL;
12207 err = got_worktree_get_histedit_script_path(&path, worktree);
12208 if (err)
12209 return err;
12211 f = fopen(path, "we");
12212 if (f == NULL) {
12213 err = got_error_from_errno2("fopen", path);
12214 goto done;
12216 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12217 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12218 repo);
12219 if (err)
12220 break;
12222 if (hle->logmsg) {
12223 int n = fprintf(f, "%c %s\n",
12224 GOT_HISTEDIT_MESG, hle->logmsg);
12225 if (n < 0) {
12226 err = got_ferror(f, GOT_ERR_IO);
12227 break;
12231 done:
12232 if (f && fclose(f) == EOF && err == NULL)
12233 err = got_error_from_errno("fclose");
12234 free(path);
12235 if (commit)
12236 got_object_commit_close(commit);
12237 return err;
12240 static void
12241 histedit_free_list(struct got_histedit_list *histedit_cmds)
12243 struct got_histedit_list_entry *hle;
12245 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12246 TAILQ_REMOVE(histedit_cmds, hle, entry);
12247 free(hle);
12251 static const struct got_error *
12252 histedit_load_list(struct got_histedit_list *histedit_cmds,
12253 const char *path, struct got_repository *repo)
12255 const struct got_error *err = NULL;
12256 FILE *f = NULL;
12258 f = fopen(path, "re");
12259 if (f == NULL) {
12260 err = got_error_from_errno2("fopen", path);
12261 goto done;
12264 err = histedit_parse_list(histedit_cmds, f, repo);
12265 done:
12266 if (f && fclose(f) == EOF && err == NULL)
12267 err = got_error_from_errno("fclose");
12268 return err;
12271 static const struct got_error *
12272 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12273 const struct got_error *edit_err, struct got_object_id_queue *commits,
12274 const char *path, const char *branch_name, struct got_repository *repo)
12276 const struct got_error *err = NULL, *prev_err = edit_err;
12277 int resp = ' ';
12279 while (resp != 'c' && resp != 'r' && resp != 'a') {
12280 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12281 "or (a)bort: ", getprogname(), prev_err->msg);
12282 resp = getchar();
12283 if (resp == '\n')
12284 resp = getchar();
12285 if (resp == 'c') {
12286 histedit_free_list(histedit_cmds);
12287 err = histedit_run_editor(histedit_cmds, path, commits,
12288 repo);
12289 if (err) {
12290 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12291 err->code != GOT_ERR_HISTEDIT_CMD)
12292 break;
12293 prev_err = err;
12294 resp = ' ';
12295 continue;
12297 break;
12298 } else if (resp == 'r') {
12299 histedit_free_list(histedit_cmds);
12300 err = histedit_edit_script(histedit_cmds,
12301 commits, branch_name, 0, 0, 0, 0, repo);
12302 if (err) {
12303 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12304 err->code != GOT_ERR_HISTEDIT_CMD)
12305 break;
12306 prev_err = err;
12307 resp = ' ';
12308 continue;
12310 break;
12311 } else if (resp == 'a') {
12312 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12313 break;
12314 } else
12315 printf("invalid response '%c'\n", resp);
12318 return err;
12321 static const struct got_error *
12322 histedit_complete(struct got_worktree *worktree,
12323 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12324 struct got_reference *branch, struct got_repository *repo)
12326 printf("Switching work tree to %s\n",
12327 got_ref_get_symref_target(branch));
12328 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12329 branch, repo);
12332 static const struct got_error *
12333 show_histedit_progress(struct got_commit_object *commit,
12334 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12336 const struct got_error *err;
12337 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12339 err = got_object_id_str(&old_id_str, hle->commit_id);
12340 if (err)
12341 goto done;
12343 if (new_id) {
12344 err = got_object_id_str(&new_id_str, new_id);
12345 if (err)
12346 goto done;
12349 old_id_str[12] = '\0';
12350 if (new_id_str)
12351 new_id_str[12] = '\0';
12353 if (hle->logmsg) {
12354 logmsg = strdup(hle->logmsg);
12355 if (logmsg == NULL) {
12356 err = got_error_from_errno("strdup");
12357 goto done;
12359 trim_logmsg(logmsg, 42);
12360 } else {
12361 err = get_short_logmsg(&logmsg, 42, commit);
12362 if (err)
12363 goto done;
12366 switch (hle->cmd->code) {
12367 case GOT_HISTEDIT_PICK:
12368 case GOT_HISTEDIT_EDIT:
12369 printf("%s -> %s: %s\n", old_id_str,
12370 new_id_str ? new_id_str : "no-op change", logmsg);
12371 break;
12372 case GOT_HISTEDIT_DROP:
12373 case GOT_HISTEDIT_FOLD:
12374 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12375 logmsg);
12376 break;
12377 default:
12378 break;
12380 done:
12381 free(old_id_str);
12382 free(new_id_str);
12383 return err;
12386 static const struct got_error *
12387 histedit_commit(struct got_pathlist_head *merged_paths,
12388 struct got_worktree *worktree, struct got_fileindex *fileindex,
12389 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12390 const char *committer, int allow_conflict, struct got_repository *repo)
12392 const struct got_error *err;
12393 struct got_commit_object *commit;
12394 struct got_object_id *new_commit_id;
12396 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12397 && hle->logmsg == NULL) {
12398 err = histedit_edit_logmsg(hle, repo);
12399 if (err)
12400 return err;
12403 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12404 if (err)
12405 return err;
12407 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12408 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12409 hle->logmsg, allow_conflict, repo);
12410 if (err) {
12411 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12412 goto done;
12413 err = show_histedit_progress(commit, hle, NULL);
12414 } else {
12415 err = show_histedit_progress(commit, hle, new_commit_id);
12416 free(new_commit_id);
12418 done:
12419 got_object_commit_close(commit);
12420 return err;
12423 static const struct got_error *
12424 histedit_skip_commit(struct got_histedit_list_entry *hle,
12425 struct got_worktree *worktree, struct got_repository *repo)
12427 const struct got_error *error;
12428 struct got_commit_object *commit;
12430 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12431 repo);
12432 if (error)
12433 return error;
12435 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12436 if (error)
12437 return error;
12439 error = show_histedit_progress(commit, hle, NULL);
12440 got_object_commit_close(commit);
12441 return error;
12444 static const struct got_error *
12445 check_local_changes(void *arg, unsigned char status,
12446 unsigned char staged_status, const char *path,
12447 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12448 struct got_object_id *commit_id, int dirfd, const char *de_name)
12450 int *have_local_changes = arg;
12452 switch (status) {
12453 case GOT_STATUS_ADD:
12454 case GOT_STATUS_DELETE:
12455 case GOT_STATUS_MODIFY:
12456 case GOT_STATUS_CONFLICT:
12457 *have_local_changes = 1;
12458 return got_error(GOT_ERR_CANCELLED);
12459 default:
12460 break;
12463 switch (staged_status) {
12464 case GOT_STATUS_ADD:
12465 case GOT_STATUS_DELETE:
12466 case GOT_STATUS_MODIFY:
12467 *have_local_changes = 1;
12468 return got_error(GOT_ERR_CANCELLED);
12469 default:
12470 break;
12473 return NULL;
12476 static const struct got_error *
12477 cmd_histedit(int argc, char *argv[])
12479 const struct got_error *error = NULL;
12480 struct got_worktree *worktree = NULL;
12481 struct got_fileindex *fileindex = NULL;
12482 struct got_repository *repo = NULL;
12483 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12484 struct got_reference *branch = NULL;
12485 struct got_reference *tmp_branch = NULL;
12486 struct got_object_id *resume_commit_id = NULL;
12487 struct got_object_id *base_commit_id = NULL;
12488 struct got_object_id *head_commit_id = NULL;
12489 struct got_commit_object *commit = NULL;
12490 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12491 struct got_update_progress_arg upa;
12492 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12493 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12494 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12495 const char *edit_script_path = NULL;
12496 struct got_object_id_queue commits;
12497 struct got_pathlist_head merged_paths;
12498 const struct got_object_id_queue *parent_ids;
12499 struct got_object_qid *pid;
12500 struct got_histedit_list histedit_cmds;
12501 struct got_histedit_list_entry *hle;
12502 int *pack_fds = NULL;
12504 STAILQ_INIT(&commits);
12505 TAILQ_INIT(&histedit_cmds);
12506 TAILQ_INIT(&merged_paths);
12507 memset(&upa, 0, sizeof(upa));
12509 #ifndef PROFILE
12510 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12511 "unveil", NULL) == -1)
12512 err(1, "pledge");
12513 #endif
12515 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12516 switch (ch) {
12517 case 'a':
12518 abort_edit = 1;
12519 break;
12520 case 'C':
12521 allow_conflict = 1;
12522 break;
12523 case 'c':
12524 continue_edit = 1;
12525 break;
12526 case 'd':
12527 drop_only = 1;
12528 break;
12529 case 'e':
12530 edit_only = 1;
12531 break;
12532 case 'F':
12533 edit_script_path = optarg;
12534 break;
12535 case 'f':
12536 fold_only = 1;
12537 break;
12538 case 'l':
12539 list_backups = 1;
12540 break;
12541 case 'm':
12542 edit_logmsg_only = 1;
12543 break;
12544 case 'X':
12545 delete_backups = 1;
12546 break;
12547 default:
12548 usage_histedit();
12549 /* NOTREACHED */
12553 argc -= optind;
12554 argv += optind;
12556 if (abort_edit && allow_conflict)
12557 option_conflict('a', 'C');
12558 if (abort_edit && continue_edit)
12559 option_conflict('a', 'c');
12560 if (edit_script_path && allow_conflict)
12561 option_conflict('F', 'C');
12562 if (edit_script_path && edit_logmsg_only)
12563 option_conflict('F', 'm');
12564 if (abort_edit && edit_logmsg_only)
12565 option_conflict('a', 'm');
12566 if (edit_logmsg_only && allow_conflict)
12567 option_conflict('m', 'C');
12568 if (continue_edit && edit_logmsg_only)
12569 option_conflict('c', 'm');
12570 if (abort_edit && fold_only)
12571 option_conflict('a', 'f');
12572 if (fold_only && allow_conflict)
12573 option_conflict('f', 'C');
12574 if (continue_edit && fold_only)
12575 option_conflict('c', 'f');
12576 if (fold_only && edit_logmsg_only)
12577 option_conflict('f', 'm');
12578 if (edit_script_path && fold_only)
12579 option_conflict('F', 'f');
12580 if (abort_edit && edit_only)
12581 option_conflict('a', 'e');
12582 if (continue_edit && edit_only)
12583 option_conflict('c', 'e');
12584 if (edit_only && edit_logmsg_only)
12585 option_conflict('e', 'm');
12586 if (edit_script_path && edit_only)
12587 option_conflict('F', 'e');
12588 if (fold_only && edit_only)
12589 option_conflict('f', 'e');
12590 if (drop_only && abort_edit)
12591 option_conflict('d', 'a');
12592 if (drop_only && allow_conflict)
12593 option_conflict('d', 'C');
12594 if (drop_only && continue_edit)
12595 option_conflict('d', 'c');
12596 if (drop_only && edit_logmsg_only)
12597 option_conflict('d', 'm');
12598 if (drop_only && edit_only)
12599 option_conflict('d', 'e');
12600 if (drop_only && edit_script_path)
12601 option_conflict('d', 'F');
12602 if (drop_only && fold_only)
12603 option_conflict('d', 'f');
12604 if (list_backups) {
12605 if (abort_edit)
12606 option_conflict('l', 'a');
12607 if (allow_conflict)
12608 option_conflict('l', 'C');
12609 if (continue_edit)
12610 option_conflict('l', 'c');
12611 if (edit_script_path)
12612 option_conflict('l', 'F');
12613 if (edit_logmsg_only)
12614 option_conflict('l', 'm');
12615 if (drop_only)
12616 option_conflict('l', 'd');
12617 if (fold_only)
12618 option_conflict('l', 'f');
12619 if (edit_only)
12620 option_conflict('l', 'e');
12621 if (delete_backups)
12622 option_conflict('l', 'X');
12623 if (argc != 0 && argc != 1)
12624 usage_histedit();
12625 } else if (delete_backups) {
12626 if (abort_edit)
12627 option_conflict('X', 'a');
12628 if (allow_conflict)
12629 option_conflict('X', 'C');
12630 if (continue_edit)
12631 option_conflict('X', 'c');
12632 if (drop_only)
12633 option_conflict('X', 'd');
12634 if (edit_script_path)
12635 option_conflict('X', 'F');
12636 if (edit_logmsg_only)
12637 option_conflict('X', 'm');
12638 if (fold_only)
12639 option_conflict('X', 'f');
12640 if (edit_only)
12641 option_conflict('X', 'e');
12642 if (list_backups)
12643 option_conflict('X', 'l');
12644 if (argc != 0 && argc != 1)
12645 usage_histedit();
12646 } else if (allow_conflict && !continue_edit)
12647 errx(1, "-C option requires -c");
12648 else if (argc != 0)
12649 usage_histedit();
12652 * This command cannot apply unveil(2) in all cases because the
12653 * user may choose to run an editor to edit the histedit script
12654 * and to edit individual commit log messages.
12655 * unveil(2) traverses exec(2); if an editor is used we have to
12656 * apply unveil after edit script and log messages have been written.
12657 * XXX TODO: Make use of unveil(2) where possible.
12660 cwd = getcwd(NULL, 0);
12661 if (cwd == NULL) {
12662 error = got_error_from_errno("getcwd");
12663 goto done;
12666 error = got_repo_pack_fds_open(&pack_fds);
12667 if (error != NULL)
12668 goto done;
12670 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12671 if (error) {
12672 if (list_backups || delete_backups) {
12673 if (error->code != GOT_ERR_NOT_WORKTREE)
12674 goto done;
12675 } else {
12676 if (error->code == GOT_ERR_NOT_WORKTREE)
12677 error = wrap_not_worktree_error(error,
12678 "histedit", cwd);
12679 goto done;
12683 if (list_backups || delete_backups) {
12684 error = got_repo_open(&repo,
12685 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12686 NULL, pack_fds);
12687 if (error != NULL)
12688 goto done;
12689 error = apply_unveil(got_repo_get_path(repo), 0,
12690 worktree ? got_worktree_get_root_path(worktree) : NULL);
12691 if (error)
12692 goto done;
12693 error = process_backup_refs(
12694 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12695 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12696 goto done; /* nothing else to do */
12699 error = get_gitconfig_path(&gitconfig_path);
12700 if (error)
12701 goto done;
12702 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12703 gitconfig_path, pack_fds);
12704 if (error != NULL)
12705 goto done;
12707 if (worktree != NULL && !list_backups && !delete_backups) {
12708 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12709 if (error)
12710 goto done;
12713 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12714 if (error)
12715 goto done;
12716 if (rebase_in_progress) {
12717 error = got_error(GOT_ERR_REBASING);
12718 goto done;
12721 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12722 repo);
12723 if (error)
12724 goto done;
12725 if (merge_in_progress) {
12726 error = got_error(GOT_ERR_MERGE_BUSY);
12727 goto done;
12730 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12731 if (error)
12732 goto done;
12734 if (edit_in_progress && edit_logmsg_only) {
12735 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12736 "histedit operation is in progress in this "
12737 "work tree and must be continued or aborted "
12738 "before the -m option can be used");
12739 goto done;
12741 if (edit_in_progress && drop_only) {
12742 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12743 "histedit operation is in progress in this "
12744 "work tree and must be continued or aborted "
12745 "before the -d option can be used");
12746 goto done;
12748 if (edit_in_progress && fold_only) {
12749 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12750 "histedit operation is in progress in this "
12751 "work tree and must be continued or aborted "
12752 "before the -f option can be used");
12753 goto done;
12755 if (edit_in_progress && edit_only) {
12756 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12757 "histedit operation is in progress in this "
12758 "work tree and must be continued or aborted "
12759 "before the -e option can be used");
12760 goto done;
12763 if (edit_in_progress && abort_edit) {
12764 error = got_worktree_histedit_continue(&resume_commit_id,
12765 &tmp_branch, &branch, &base_commit_id, &fileindex,
12766 worktree, repo);
12767 if (error)
12768 goto done;
12769 printf("Switching work tree to %s\n",
12770 got_ref_get_symref_target(branch));
12771 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12772 branch, base_commit_id, abort_progress, &upa);
12773 if (error)
12774 goto done;
12775 printf("Histedit of %s aborted\n",
12776 got_ref_get_symref_target(branch));
12777 print_merge_progress_stats(&upa);
12778 goto done; /* nothing else to do */
12779 } else if (abort_edit) {
12780 error = got_error(GOT_ERR_NOT_HISTEDIT);
12781 goto done;
12784 error = get_author(&committer, repo, worktree);
12785 if (error)
12786 goto done;
12788 if (continue_edit) {
12789 char *path;
12791 if (!edit_in_progress) {
12792 error = got_error(GOT_ERR_NOT_HISTEDIT);
12793 goto done;
12796 error = got_worktree_get_histedit_script_path(&path, worktree);
12797 if (error)
12798 goto done;
12800 error = histedit_load_list(&histedit_cmds, path, repo);
12801 free(path);
12802 if (error)
12803 goto done;
12805 error = got_worktree_histedit_continue(&resume_commit_id,
12806 &tmp_branch, &branch, &base_commit_id, &fileindex,
12807 worktree, repo);
12808 if (error)
12809 goto done;
12811 error = got_ref_resolve(&head_commit_id, repo, branch);
12812 if (error)
12813 goto done;
12815 error = got_object_open_as_commit(&commit, repo,
12816 head_commit_id);
12817 if (error)
12818 goto done;
12819 parent_ids = got_object_commit_get_parent_ids(commit);
12820 pid = STAILQ_FIRST(parent_ids);
12821 if (pid == NULL) {
12822 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12823 goto done;
12825 error = collect_commits(&commits, head_commit_id, &pid->id,
12826 base_commit_id, got_worktree_get_path_prefix(worktree),
12827 GOT_ERR_HISTEDIT_PATH, repo);
12828 got_object_commit_close(commit);
12829 commit = NULL;
12830 if (error)
12831 goto done;
12832 } else {
12833 if (edit_in_progress) {
12834 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12835 goto done;
12838 error = got_ref_open(&branch, repo,
12839 got_worktree_get_head_ref_name(worktree), 0);
12840 if (error != NULL)
12841 goto done;
12843 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12844 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12845 "will not edit commit history of a branch outside "
12846 "the \"refs/heads/\" reference namespace");
12847 goto done;
12850 error = got_ref_resolve(&head_commit_id, repo, branch);
12851 got_ref_close(branch);
12852 branch = NULL;
12853 if (error)
12854 goto done;
12856 error = got_object_open_as_commit(&commit, repo,
12857 head_commit_id);
12858 if (error)
12859 goto done;
12860 parent_ids = got_object_commit_get_parent_ids(commit);
12861 pid = STAILQ_FIRST(parent_ids);
12862 if (pid == NULL) {
12863 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12864 goto done;
12866 error = collect_commits(&commits, head_commit_id, &pid->id,
12867 got_worktree_get_base_commit_id(worktree),
12868 got_worktree_get_path_prefix(worktree),
12869 GOT_ERR_HISTEDIT_PATH, repo);
12870 got_object_commit_close(commit);
12871 commit = NULL;
12872 if (error)
12873 goto done;
12875 if (STAILQ_EMPTY(&commits)) {
12876 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12877 goto done;
12880 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12881 &base_commit_id, &fileindex, worktree, repo);
12882 if (error)
12883 goto done;
12885 if (edit_script_path) {
12886 error = histedit_load_list(&histedit_cmds,
12887 edit_script_path, repo);
12888 if (error) {
12889 got_worktree_histedit_abort(worktree, fileindex,
12890 repo, branch, base_commit_id,
12891 abort_progress, &upa);
12892 print_merge_progress_stats(&upa);
12893 goto done;
12895 } else {
12896 const char *branch_name;
12897 branch_name = got_ref_get_symref_target(branch);
12898 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12899 branch_name += 11;
12900 error = histedit_edit_script(&histedit_cmds, &commits,
12901 branch_name, edit_logmsg_only, fold_only,
12902 drop_only, edit_only, repo);
12903 if (error) {
12904 got_worktree_histedit_abort(worktree, fileindex,
12905 repo, branch, base_commit_id,
12906 abort_progress, &upa);
12907 print_merge_progress_stats(&upa);
12908 goto done;
12913 error = histedit_save_list(&histedit_cmds, worktree,
12914 repo);
12915 if (error) {
12916 got_worktree_histedit_abort(worktree, fileindex,
12917 repo, branch, base_commit_id,
12918 abort_progress, &upa);
12919 print_merge_progress_stats(&upa);
12920 goto done;
12925 error = histedit_check_script(&histedit_cmds, &commits, repo);
12926 if (error)
12927 goto done;
12929 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12930 if (resume_commit_id) {
12931 if (got_object_id_cmp(hle->commit_id,
12932 resume_commit_id) != 0)
12933 continue;
12935 resume_commit_id = NULL;
12936 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12937 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12938 error = histedit_skip_commit(hle, worktree,
12939 repo);
12940 if (error)
12941 goto done;
12942 } else {
12943 struct got_pathlist_head paths;
12944 int have_changes = 0;
12946 TAILQ_INIT(&paths);
12947 error = got_pathlist_append(&paths, "", NULL);
12948 if (error)
12949 goto done;
12950 error = got_worktree_status(worktree, &paths,
12951 repo, 0, check_local_changes, &have_changes,
12952 check_cancelled, NULL);
12953 got_pathlist_free(&paths,
12954 GOT_PATHLIST_FREE_NONE);
12955 if (error) {
12956 if (error->code != GOT_ERR_CANCELLED)
12957 goto done;
12958 if (sigint_received || sigpipe_received)
12959 goto done;
12961 if (have_changes) {
12962 error = histedit_commit(NULL, worktree,
12963 fileindex, tmp_branch, hle,
12964 committer, allow_conflict, repo);
12965 if (error)
12966 goto done;
12967 } else {
12968 error = got_object_open_as_commit(
12969 &commit, repo, hle->commit_id);
12970 if (error)
12971 goto done;
12972 error = show_histedit_progress(commit,
12973 hle, NULL);
12974 got_object_commit_close(commit);
12975 commit = NULL;
12976 if (error)
12977 goto done;
12980 continue;
12983 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12984 error = histedit_skip_commit(hle, worktree, repo);
12985 if (error)
12986 goto done;
12987 continue;
12990 error = got_object_open_as_commit(&commit, repo,
12991 hle->commit_id);
12992 if (error)
12993 goto done;
12994 parent_ids = got_object_commit_get_parent_ids(commit);
12995 pid = STAILQ_FIRST(parent_ids);
12997 error = got_worktree_histedit_merge_files(&merged_paths,
12998 worktree, fileindex, &pid->id, hle->commit_id, repo,
12999 update_progress, &upa, check_cancelled, NULL);
13000 if (error)
13001 goto done;
13002 got_object_commit_close(commit);
13003 commit = NULL;
13005 print_merge_progress_stats(&upa);
13006 if (upa.conflicts > 0 || upa.missing > 0 ||
13007 upa.not_deleted > 0 || upa.unversioned > 0) {
13008 if (upa.conflicts > 0) {
13009 error = show_rebase_merge_conflict(
13010 hle->commit_id, repo);
13011 if (error)
13012 goto done;
13014 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13015 break;
13018 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13019 char *id_str;
13020 error = got_object_id_str(&id_str, hle->commit_id);
13021 if (error)
13022 goto done;
13023 printf("Stopping histedit for amending commit %s\n",
13024 id_str);
13025 free(id_str);
13026 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13027 error = got_worktree_histedit_postpone(worktree,
13028 fileindex);
13029 goto done;
13032 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13033 error = histedit_skip_commit(hle, worktree, repo);
13034 if (error)
13035 goto done;
13036 continue;
13039 error = histedit_commit(&merged_paths, worktree, fileindex,
13040 tmp_branch, hle, committer, allow_conflict, repo);
13041 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13042 if (error)
13043 goto done;
13046 if (upa.conflicts > 0 || upa.missing > 0 ||
13047 upa.not_deleted > 0 || upa.unversioned > 0) {
13048 error = got_worktree_histedit_postpone(worktree, fileindex);
13049 if (error)
13050 goto done;
13051 if (upa.conflicts > 0 && upa.missing == 0 &&
13052 upa.not_deleted == 0 && upa.unversioned == 0) {
13053 error = got_error_msg(GOT_ERR_CONFLICTS,
13054 "conflicts must be resolved before histedit "
13055 "can continue");
13056 } else if (upa.conflicts > 0) {
13057 error = got_error_msg(GOT_ERR_CONFLICTS,
13058 "conflicts must be resolved before histedit "
13059 "can continue; changes destined for some "
13060 "files were not yet merged and should be "
13061 "merged manually if required before the "
13062 "histedit operation is continued");
13063 } else {
13064 error = got_error_msg(GOT_ERR_CONFLICTS,
13065 "changes destined for some files were not "
13066 "yet merged and should be merged manually "
13067 "if required before the histedit operation "
13068 "is continued");
13070 } else
13071 error = histedit_complete(worktree, fileindex, tmp_branch,
13072 branch, repo);
13073 done:
13074 free(cwd);
13075 free(committer);
13076 free(gitconfig_path);
13077 got_object_id_queue_free(&commits);
13078 histedit_free_list(&histedit_cmds);
13079 free(head_commit_id);
13080 free(base_commit_id);
13081 free(resume_commit_id);
13082 if (commit)
13083 got_object_commit_close(commit);
13084 if (branch)
13085 got_ref_close(branch);
13086 if (tmp_branch)
13087 got_ref_close(tmp_branch);
13088 if (worktree)
13089 got_worktree_close(worktree);
13090 if (repo) {
13091 const struct got_error *close_err = got_repo_close(repo);
13092 if (error == NULL)
13093 error = close_err;
13095 if (pack_fds) {
13096 const struct got_error *pack_err =
13097 got_repo_pack_fds_close(pack_fds);
13098 if (error == NULL)
13099 error = pack_err;
13101 return error;
13104 __dead static void
13105 usage_integrate(void)
13107 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13108 exit(1);
13111 static const struct got_error *
13112 cmd_integrate(int argc, char *argv[])
13114 const struct got_error *error = NULL;
13115 struct got_repository *repo = NULL;
13116 struct got_worktree *worktree = NULL;
13117 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13118 const char *branch_arg = NULL;
13119 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13120 struct got_fileindex *fileindex = NULL;
13121 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13122 int ch;
13123 struct got_update_progress_arg upa;
13124 int *pack_fds = NULL;
13126 #ifndef PROFILE
13127 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13128 "unveil", NULL) == -1)
13129 err(1, "pledge");
13130 #endif
13132 while ((ch = getopt(argc, argv, "")) != -1) {
13133 switch (ch) {
13134 default:
13135 usage_integrate();
13136 /* NOTREACHED */
13140 argc -= optind;
13141 argv += optind;
13143 if (argc != 1)
13144 usage_integrate();
13145 branch_arg = argv[0];
13147 cwd = getcwd(NULL, 0);
13148 if (cwd == NULL) {
13149 error = got_error_from_errno("getcwd");
13150 goto done;
13153 error = got_repo_pack_fds_open(&pack_fds);
13154 if (error != NULL)
13155 goto done;
13157 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13158 if (error) {
13159 if (error->code == GOT_ERR_NOT_WORKTREE)
13160 error = wrap_not_worktree_error(error, "integrate",
13161 cwd);
13162 goto done;
13165 error = check_rebase_or_histedit_in_progress(worktree);
13166 if (error)
13167 goto done;
13169 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13170 NULL, pack_fds);
13171 if (error != NULL)
13172 goto done;
13174 error = apply_unveil(got_repo_get_path(repo), 0,
13175 got_worktree_get_root_path(worktree));
13176 if (error)
13177 goto done;
13179 error = check_merge_in_progress(worktree, repo);
13180 if (error)
13181 goto done;
13183 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13184 error = got_error_from_errno("asprintf");
13185 goto done;
13188 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13189 &base_branch_ref, worktree, refname, repo);
13190 if (error)
13191 goto done;
13193 refname = strdup(got_ref_get_name(branch_ref));
13194 if (refname == NULL) {
13195 error = got_error_from_errno("strdup");
13196 got_worktree_integrate_abort(worktree, fileindex, repo,
13197 branch_ref, base_branch_ref);
13198 goto done;
13200 base_refname = strdup(got_ref_get_name(base_branch_ref));
13201 if (base_refname == NULL) {
13202 error = got_error_from_errno("strdup");
13203 got_worktree_integrate_abort(worktree, fileindex, repo,
13204 branch_ref, base_branch_ref);
13205 goto done;
13207 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13208 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13209 got_worktree_integrate_abort(worktree, fileindex, repo,
13210 branch_ref, base_branch_ref);
13211 goto done;
13214 error = got_ref_resolve(&commit_id, repo, branch_ref);
13215 if (error)
13216 goto done;
13218 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13219 if (error)
13220 goto done;
13222 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13223 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13224 "specified branch has already been integrated");
13225 got_worktree_integrate_abort(worktree, fileindex, repo,
13226 branch_ref, base_branch_ref);
13227 goto done;
13230 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13231 if (error) {
13232 if (error->code == GOT_ERR_ANCESTRY)
13233 error = got_error(GOT_ERR_REBASE_REQUIRED);
13234 got_worktree_integrate_abort(worktree, fileindex, repo,
13235 branch_ref, base_branch_ref);
13236 goto done;
13239 memset(&upa, 0, sizeof(upa));
13240 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13241 branch_ref, base_branch_ref, update_progress, &upa,
13242 check_cancelled, NULL);
13243 if (error)
13244 goto done;
13246 printf("Integrated %s into %s\n", refname, base_refname);
13247 print_update_progress_stats(&upa);
13248 done:
13249 if (repo) {
13250 const struct got_error *close_err = got_repo_close(repo);
13251 if (error == NULL)
13252 error = close_err;
13254 if (worktree)
13255 got_worktree_close(worktree);
13256 if (pack_fds) {
13257 const struct got_error *pack_err =
13258 got_repo_pack_fds_close(pack_fds);
13259 if (error == NULL)
13260 error = pack_err;
13262 free(cwd);
13263 free(base_commit_id);
13264 free(commit_id);
13265 free(refname);
13266 free(base_refname);
13267 return error;
13270 __dead static void
13271 usage_merge(void)
13273 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13274 exit(1);
13277 static const struct got_error *
13278 cmd_merge(int argc, char *argv[])
13280 const struct got_error *error = NULL;
13281 struct got_worktree *worktree = NULL;
13282 struct got_repository *repo = NULL;
13283 struct got_fileindex *fileindex = NULL;
13284 char *cwd = NULL, *id_str = NULL, *author = NULL;
13285 char *gitconfig_path = NULL;
13286 struct got_reference *branch = NULL, *wt_branch = NULL;
13287 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13288 struct got_object_id *wt_branch_tip = NULL;
13289 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13290 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13291 struct got_update_progress_arg upa;
13292 struct got_object_id *merge_commit_id = NULL;
13293 char *branch_name = NULL;
13294 int *pack_fds = NULL;
13296 memset(&upa, 0, sizeof(upa));
13298 #ifndef PROFILE
13299 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13300 "unveil", NULL) == -1)
13301 err(1, "pledge");
13302 #endif
13304 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13305 switch (ch) {
13306 case 'a':
13307 abort_merge = 1;
13308 break;
13309 case 'C':
13310 allow_conflict = 1;
13311 break;
13312 case 'c':
13313 continue_merge = 1;
13314 break;
13315 case 'M':
13316 prefer_fast_forward = 0;
13317 break;
13318 case 'n':
13319 interrupt_merge = 1;
13320 break;
13321 default:
13322 usage_merge();
13323 /* NOTREACHED */
13327 argc -= optind;
13328 argv += optind;
13330 if (abort_merge) {
13331 if (continue_merge)
13332 option_conflict('a', 'c');
13333 if (!prefer_fast_forward)
13334 option_conflict('a', 'M');
13335 if (interrupt_merge)
13336 option_conflict('a', 'n');
13337 } else if (continue_merge) {
13338 if (!prefer_fast_forward)
13339 option_conflict('c', 'M');
13340 if (interrupt_merge)
13341 option_conflict('c', 'n');
13343 if (allow_conflict) {
13344 if (!continue_merge)
13345 errx(1, "-C option requires -c");
13347 if (abort_merge || continue_merge) {
13348 if (argc != 0)
13349 usage_merge();
13350 } else if (argc != 1)
13351 usage_merge();
13353 cwd = getcwd(NULL, 0);
13354 if (cwd == NULL) {
13355 error = got_error_from_errno("getcwd");
13356 goto done;
13359 error = got_repo_pack_fds_open(&pack_fds);
13360 if (error != NULL)
13361 goto done;
13363 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13364 if (error) {
13365 if (error->code == GOT_ERR_NOT_WORKTREE)
13366 error = wrap_not_worktree_error(error,
13367 "merge", cwd);
13368 goto done;
13371 error = get_gitconfig_path(&gitconfig_path);
13372 if (error)
13373 goto done;
13374 error = got_repo_open(&repo,
13375 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13376 gitconfig_path, pack_fds);
13377 if (error != NULL)
13378 goto done;
13380 if (worktree != NULL) {
13381 error = worktree_has_logmsg_ref("merge", worktree, repo);
13382 if (error)
13383 goto done;
13386 error = apply_unveil(got_repo_get_path(repo), 0,
13387 worktree ? got_worktree_get_root_path(worktree) : NULL);
13388 if (error)
13389 goto done;
13391 error = check_rebase_or_histedit_in_progress(worktree);
13392 if (error)
13393 goto done;
13395 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13396 repo);
13397 if (error)
13398 goto done;
13400 if (merge_in_progress && !(abort_merge || continue_merge)) {
13401 error = got_error(GOT_ERR_MERGE_BUSY);
13402 goto done;
13405 if (!merge_in_progress && (abort_merge || continue_merge)) {
13406 error = got_error(GOT_ERR_NOT_MERGING);
13407 goto done;
13410 if (abort_merge) {
13411 error = got_worktree_merge_continue(&branch_name,
13412 &branch_tip, &fileindex, worktree, repo);
13413 if (error)
13414 goto done;
13415 error = got_worktree_merge_abort(worktree, fileindex, repo,
13416 abort_progress, &upa);
13417 if (error)
13418 goto done;
13419 printf("Merge of %s aborted\n", branch_name);
13420 goto done; /* nothing else to do */
13423 if (strncmp(got_worktree_get_head_ref_name(worktree),
13424 "refs/heads/", 11) != 0) {
13425 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13426 "work tree's current branch %s is outside the "
13427 "\"refs/heads/\" reference namespace; "
13428 "update -b required",
13429 got_worktree_get_head_ref_name(worktree));
13430 goto done;
13433 error = get_author(&author, repo, worktree);
13434 if (error)
13435 goto done;
13437 error = got_ref_open(&wt_branch, repo,
13438 got_worktree_get_head_ref_name(worktree), 0);
13439 if (error)
13440 goto done;
13441 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13442 if (error)
13443 goto done;
13445 if (continue_merge) {
13446 struct got_object_id *base_commit_id;
13447 base_commit_id = got_worktree_get_base_commit_id(worktree);
13448 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13449 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13450 goto done;
13452 error = got_worktree_merge_continue(&branch_name,
13453 &branch_tip, &fileindex, worktree, repo);
13454 if (error)
13455 goto done;
13456 } else {
13457 error = got_ref_open(&branch, repo, argv[0], 0);
13458 if (error != NULL)
13459 goto done;
13460 branch_name = strdup(got_ref_get_name(branch));
13461 if (branch_name == NULL) {
13462 error = got_error_from_errno("strdup");
13463 goto done;
13465 error = got_ref_resolve(&branch_tip, repo, branch);
13466 if (error)
13467 goto done;
13470 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13471 wt_branch_tip, branch_tip, 0, repo,
13472 check_cancelled, NULL);
13473 if (error && error->code != GOT_ERR_ANCESTRY)
13474 goto done;
13476 if (!continue_merge) {
13477 error = check_path_prefix(wt_branch_tip, branch_tip,
13478 got_worktree_get_path_prefix(worktree),
13479 GOT_ERR_MERGE_PATH, repo);
13480 if (error)
13481 goto done;
13482 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13483 if (error)
13484 goto done;
13485 if (prefer_fast_forward && yca_id &&
13486 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13487 struct got_pathlist_head paths;
13488 if (interrupt_merge) {
13489 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13490 "there are no changes to merge since %s "
13491 "is already based on %s; merge cannot be "
13492 "interrupted for amending; -n",
13493 branch_name, got_ref_get_name(wt_branch));
13494 goto done;
13496 printf("Forwarding %s to %s\n",
13497 got_ref_get_name(wt_branch), branch_name);
13498 error = got_ref_change_ref(wt_branch, branch_tip);
13499 if (error)
13500 goto done;
13501 error = got_ref_write(wt_branch, repo);
13502 if (error)
13503 goto done;
13504 error = got_worktree_set_base_commit_id(worktree, repo,
13505 branch_tip);
13506 if (error)
13507 goto done;
13508 TAILQ_INIT(&paths);
13509 error = got_pathlist_append(&paths, "", NULL);
13510 if (error)
13511 goto done;
13512 error = got_worktree_checkout_files(worktree,
13513 &paths, repo, update_progress, &upa,
13514 check_cancelled, NULL);
13515 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13516 if (error)
13517 goto done;
13518 if (upa.did_something) {
13519 char *id_str;
13520 error = got_object_id_str(&id_str, branch_tip);
13521 if (error)
13522 goto done;
13523 printf("Updated to commit %s\n", id_str);
13524 free(id_str);
13525 } else
13526 printf("Already up-to-date\n");
13527 print_update_progress_stats(&upa);
13528 goto done;
13530 error = got_worktree_merge_write_refs(worktree, branch, repo);
13531 if (error)
13532 goto done;
13534 error = got_worktree_merge_branch(worktree, fileindex,
13535 yca_id, branch_tip, repo, update_progress, &upa,
13536 check_cancelled, NULL);
13537 if (error)
13538 goto done;
13539 print_merge_progress_stats(&upa);
13540 if (!upa.did_something) {
13541 error = got_worktree_merge_abort(worktree, fileindex,
13542 repo, abort_progress, &upa);
13543 if (error)
13544 goto done;
13545 printf("Already up-to-date\n");
13546 goto done;
13550 if (interrupt_merge) {
13551 error = got_worktree_merge_postpone(worktree, fileindex);
13552 if (error)
13553 goto done;
13554 printf("Merge of %s interrupted on request\n", branch_name);
13555 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13556 upa.not_deleted > 0 || upa.unversioned > 0) {
13557 error = got_worktree_merge_postpone(worktree, fileindex);
13558 if (error)
13559 goto done;
13560 if (upa.conflicts > 0 && upa.missing == 0 &&
13561 upa.not_deleted == 0 && upa.unversioned == 0) {
13562 error = got_error_msg(GOT_ERR_CONFLICTS,
13563 "conflicts must be resolved before merging "
13564 "can continue");
13565 } else if (upa.conflicts > 0) {
13566 error = got_error_msg(GOT_ERR_CONFLICTS,
13567 "conflicts must be resolved before merging "
13568 "can continue; changes destined for some "
13569 "files were not yet merged and "
13570 "should be merged manually if required before the "
13571 "merge operation is continued");
13572 } else {
13573 error = got_error_msg(GOT_ERR_CONFLICTS,
13574 "changes destined for some "
13575 "files were not yet merged and should be "
13576 "merged manually if required before the "
13577 "merge operation is continued");
13579 goto done;
13580 } else {
13581 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13582 fileindex, author, NULL, 1, branch_tip, branch_name,
13583 allow_conflict, repo, continue_merge ? print_status : NULL,
13584 NULL);
13585 if (error)
13586 goto done;
13587 error = got_worktree_merge_complete(worktree, fileindex, repo);
13588 if (error)
13589 goto done;
13590 error = got_object_id_str(&id_str, merge_commit_id);
13591 if (error)
13592 goto done;
13593 printf("Merged %s into %s: %s\n", branch_name,
13594 got_worktree_get_head_ref_name(worktree),
13595 id_str);
13598 done:
13599 free(gitconfig_path);
13600 free(id_str);
13601 free(merge_commit_id);
13602 free(author);
13603 free(branch_tip);
13604 free(branch_name);
13605 free(yca_id);
13606 if (branch)
13607 got_ref_close(branch);
13608 if (wt_branch)
13609 got_ref_close(wt_branch);
13610 if (worktree)
13611 got_worktree_close(worktree);
13612 if (repo) {
13613 const struct got_error *close_err = got_repo_close(repo);
13614 if (error == NULL)
13615 error = close_err;
13617 if (pack_fds) {
13618 const struct got_error *pack_err =
13619 got_repo_pack_fds_close(pack_fds);
13620 if (error == NULL)
13621 error = pack_err;
13623 return error;
13626 __dead static void
13627 usage_stage(void)
13629 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13630 "[path ...]\n", getprogname());
13631 exit(1);
13634 static const struct got_error *
13635 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13636 const char *path, struct got_object_id *blob_id,
13637 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13638 int dirfd, const char *de_name)
13640 const struct got_error *err = NULL;
13641 char *id_str = NULL;
13643 if (staged_status != GOT_STATUS_ADD &&
13644 staged_status != GOT_STATUS_MODIFY &&
13645 staged_status != GOT_STATUS_DELETE)
13646 return NULL;
13648 if (staged_status == GOT_STATUS_ADD ||
13649 staged_status == GOT_STATUS_MODIFY)
13650 err = got_object_id_str(&id_str, staged_blob_id);
13651 else
13652 err = got_object_id_str(&id_str, blob_id);
13653 if (err)
13654 return err;
13656 printf("%s %c %s\n", id_str, staged_status, path);
13657 free(id_str);
13658 return NULL;
13661 static const struct got_error *
13662 cmd_stage(int argc, char *argv[])
13664 const struct got_error *error = NULL;
13665 struct got_repository *repo = NULL;
13666 struct got_worktree *worktree = NULL;
13667 char *cwd = NULL;
13668 struct got_pathlist_head paths;
13669 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13670 FILE *patch_script_file = NULL;
13671 const char *patch_script_path = NULL;
13672 struct choose_patch_arg cpa;
13673 int *pack_fds = NULL;
13675 TAILQ_INIT(&paths);
13677 #ifndef PROFILE
13678 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13679 "unveil", NULL) == -1)
13680 err(1, "pledge");
13681 #endif
13683 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13684 switch (ch) {
13685 case 'F':
13686 patch_script_path = optarg;
13687 break;
13688 case 'l':
13689 list_stage = 1;
13690 break;
13691 case 'p':
13692 pflag = 1;
13693 break;
13694 case 'S':
13695 allow_bad_symlinks = 1;
13696 break;
13697 default:
13698 usage_stage();
13699 /* NOTREACHED */
13703 argc -= optind;
13704 argv += optind;
13706 if (list_stage && (pflag || patch_script_path))
13707 errx(1, "-l option cannot be used with other options");
13708 if (patch_script_path && !pflag)
13709 errx(1, "-F option can only be used together with -p option");
13711 cwd = getcwd(NULL, 0);
13712 if (cwd == NULL) {
13713 error = got_error_from_errno("getcwd");
13714 goto done;
13717 error = got_repo_pack_fds_open(&pack_fds);
13718 if (error != NULL)
13719 goto done;
13721 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13722 if (error) {
13723 if (error->code == GOT_ERR_NOT_WORKTREE)
13724 error = wrap_not_worktree_error(error, "stage", cwd);
13725 goto done;
13728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13729 NULL, pack_fds);
13730 if (error != NULL)
13731 goto done;
13733 if (patch_script_path) {
13734 patch_script_file = fopen(patch_script_path, "re");
13735 if (patch_script_file == NULL) {
13736 error = got_error_from_errno2("fopen",
13737 patch_script_path);
13738 goto done;
13741 error = apply_unveil(got_repo_get_path(repo), 0,
13742 got_worktree_get_root_path(worktree));
13743 if (error)
13744 goto done;
13746 error = check_merge_in_progress(worktree, repo);
13747 if (error)
13748 goto done;
13750 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13751 if (error)
13752 goto done;
13754 if (list_stage)
13755 error = got_worktree_status(worktree, &paths, repo, 0,
13756 print_stage, NULL, check_cancelled, NULL);
13757 else {
13758 cpa.patch_script_file = patch_script_file;
13759 cpa.action = "stage";
13760 error = got_worktree_stage(worktree, &paths,
13761 pflag ? NULL : print_status, NULL,
13762 pflag ? choose_patch : NULL, &cpa,
13763 allow_bad_symlinks, repo);
13765 done:
13766 if (patch_script_file && fclose(patch_script_file) == EOF &&
13767 error == NULL)
13768 error = got_error_from_errno2("fclose", patch_script_path);
13769 if (repo) {
13770 const struct got_error *close_err = got_repo_close(repo);
13771 if (error == NULL)
13772 error = close_err;
13774 if (worktree)
13775 got_worktree_close(worktree);
13776 if (pack_fds) {
13777 const struct got_error *pack_err =
13778 got_repo_pack_fds_close(pack_fds);
13779 if (error == NULL)
13780 error = pack_err;
13782 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13783 free(cwd);
13784 return error;
13787 __dead static void
13788 usage_unstage(void)
13790 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13791 "[path ...]\n", getprogname());
13792 exit(1);
13796 static const struct got_error *
13797 cmd_unstage(int argc, char *argv[])
13799 const struct got_error *error = NULL;
13800 struct got_repository *repo = NULL;
13801 struct got_worktree *worktree = NULL;
13802 char *cwd = NULL;
13803 struct got_pathlist_head paths;
13804 int ch, pflag = 0;
13805 struct got_update_progress_arg upa;
13806 FILE *patch_script_file = NULL;
13807 const char *patch_script_path = NULL;
13808 struct choose_patch_arg cpa;
13809 int *pack_fds = NULL;
13811 TAILQ_INIT(&paths);
13813 #ifndef PROFILE
13814 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13815 "unveil", NULL) == -1)
13816 err(1, "pledge");
13817 #endif
13819 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13820 switch (ch) {
13821 case 'F':
13822 patch_script_path = optarg;
13823 break;
13824 case 'p':
13825 pflag = 1;
13826 break;
13827 default:
13828 usage_unstage();
13829 /* NOTREACHED */
13833 argc -= optind;
13834 argv += optind;
13836 if (patch_script_path && !pflag)
13837 errx(1, "-F option can only be used together with -p option");
13839 cwd = getcwd(NULL, 0);
13840 if (cwd == NULL) {
13841 error = got_error_from_errno("getcwd");
13842 goto done;
13845 error = got_repo_pack_fds_open(&pack_fds);
13846 if (error != NULL)
13847 goto done;
13849 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13850 if (error) {
13851 if (error->code == GOT_ERR_NOT_WORKTREE)
13852 error = wrap_not_worktree_error(error, "unstage", cwd);
13853 goto done;
13856 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13857 NULL, pack_fds);
13858 if (error != NULL)
13859 goto done;
13861 if (patch_script_path) {
13862 patch_script_file = fopen(patch_script_path, "re");
13863 if (patch_script_file == NULL) {
13864 error = got_error_from_errno2("fopen",
13865 patch_script_path);
13866 goto done;
13870 error = apply_unveil(got_repo_get_path(repo), 0,
13871 got_worktree_get_root_path(worktree));
13872 if (error)
13873 goto done;
13875 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13876 if (error)
13877 goto done;
13879 cpa.patch_script_file = patch_script_file;
13880 cpa.action = "unstage";
13881 memset(&upa, 0, sizeof(upa));
13882 error = got_worktree_unstage(worktree, &paths, update_progress,
13883 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13884 if (!error)
13885 print_merge_progress_stats(&upa);
13886 done:
13887 if (patch_script_file && fclose(patch_script_file) == EOF &&
13888 error == NULL)
13889 error = got_error_from_errno2("fclose", patch_script_path);
13890 if (repo) {
13891 const struct got_error *close_err = got_repo_close(repo);
13892 if (error == NULL)
13893 error = close_err;
13895 if (worktree)
13896 got_worktree_close(worktree);
13897 if (pack_fds) {
13898 const struct got_error *pack_err =
13899 got_repo_pack_fds_close(pack_fds);
13900 if (error == NULL)
13901 error = pack_err;
13903 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13904 free(cwd);
13905 return error;
13908 __dead static void
13909 usage_cat(void)
13911 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13912 "arg ...\n", getprogname());
13913 exit(1);
13916 static const struct got_error *
13917 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13919 const struct got_error *err;
13920 struct got_blob_object *blob;
13921 int fd = -1;
13923 fd = got_opentempfd();
13924 if (fd == -1)
13925 return got_error_from_errno("got_opentempfd");
13927 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13928 if (err)
13929 goto done;
13931 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13932 done:
13933 if (fd != -1 && close(fd) == -1 && err == NULL)
13934 err = got_error_from_errno("close");
13935 if (blob)
13936 got_object_blob_close(blob);
13937 return err;
13940 static const struct got_error *
13941 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13943 const struct got_error *err;
13944 struct got_tree_object *tree;
13945 int nentries, i;
13947 err = got_object_open_as_tree(&tree, repo, id);
13948 if (err)
13949 return err;
13951 nentries = got_object_tree_get_nentries(tree);
13952 for (i = 0; i < nentries; i++) {
13953 struct got_tree_entry *te;
13954 char *id_str;
13955 if (sigint_received || sigpipe_received)
13956 break;
13957 te = got_object_tree_get_entry(tree, i);
13958 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13959 if (err)
13960 break;
13961 fprintf(outfile, "%s %.7o %s\n", id_str,
13962 got_tree_entry_get_mode(te),
13963 got_tree_entry_get_name(te));
13964 free(id_str);
13967 got_object_tree_close(tree);
13968 return err;
13971 static const struct got_error *
13972 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13974 const struct got_error *err;
13975 struct got_commit_object *commit;
13976 const struct got_object_id_queue *parent_ids;
13977 struct got_object_qid *pid;
13978 char *id_str = NULL;
13979 const char *logmsg = NULL;
13980 char gmtoff[6];
13982 err = got_object_open_as_commit(&commit, repo, id);
13983 if (err)
13984 return err;
13986 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13987 if (err)
13988 goto done;
13990 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13991 parent_ids = got_object_commit_get_parent_ids(commit);
13992 fprintf(outfile, "numparents %d\n",
13993 got_object_commit_get_nparents(commit));
13994 STAILQ_FOREACH(pid, parent_ids, entry) {
13995 char *pid_str;
13996 err = got_object_id_str(&pid_str, &pid->id);
13997 if (err)
13998 goto done;
13999 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14000 free(pid_str);
14002 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14003 got_object_commit_get_author_gmtoff(commit));
14004 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14005 got_object_commit_get_author(commit),
14006 (long long)got_object_commit_get_author_time(commit),
14007 gmtoff);
14009 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14010 got_object_commit_get_committer_gmtoff(commit));
14011 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14012 got_object_commit_get_committer(commit),
14013 (long long)got_object_commit_get_committer_time(commit),
14014 gmtoff);
14016 logmsg = got_object_commit_get_logmsg_raw(commit);
14017 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14018 fprintf(outfile, "%s", logmsg);
14019 done:
14020 free(id_str);
14021 got_object_commit_close(commit);
14022 return err;
14025 static const struct got_error *
14026 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14028 const struct got_error *err;
14029 struct got_tag_object *tag;
14030 char *id_str = NULL;
14031 const char *tagmsg = NULL;
14032 char gmtoff[6];
14034 err = got_object_open_as_tag(&tag, repo, id);
14035 if (err)
14036 return err;
14038 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14039 if (err)
14040 goto done;
14042 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14044 switch (got_object_tag_get_object_type(tag)) {
14045 case GOT_OBJ_TYPE_BLOB:
14046 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14047 GOT_OBJ_LABEL_BLOB);
14048 break;
14049 case GOT_OBJ_TYPE_TREE:
14050 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14051 GOT_OBJ_LABEL_TREE);
14052 break;
14053 case GOT_OBJ_TYPE_COMMIT:
14054 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14055 GOT_OBJ_LABEL_COMMIT);
14056 break;
14057 case GOT_OBJ_TYPE_TAG:
14058 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14059 GOT_OBJ_LABEL_TAG);
14060 break;
14061 default:
14062 break;
14065 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14066 got_object_tag_get_name(tag));
14068 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14069 got_object_tag_get_tagger_gmtoff(tag));
14070 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14071 got_object_tag_get_tagger(tag),
14072 (long long)got_object_tag_get_tagger_time(tag),
14073 gmtoff);
14075 tagmsg = got_object_tag_get_message(tag);
14076 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14077 fprintf(outfile, "%s", tagmsg);
14078 done:
14079 free(id_str);
14080 got_object_tag_close(tag);
14081 return err;
14084 static const struct got_error *
14085 cmd_cat(int argc, char *argv[])
14087 const struct got_error *error;
14088 struct got_repository *repo = NULL;
14089 struct got_worktree *worktree = NULL;
14090 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14091 char *keyword_idstr = NULL;
14092 const char *commit_id_str = NULL;
14093 struct got_object_id *id = NULL, *commit_id = NULL;
14094 struct got_commit_object *commit = NULL;
14095 int ch, obj_type, i, force_path = 0;
14096 struct got_reflist_head refs;
14097 int *pack_fds = NULL;
14099 TAILQ_INIT(&refs);
14101 #ifndef PROFILE
14102 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14103 NULL) == -1)
14104 err(1, "pledge");
14105 #endif
14107 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14108 switch (ch) {
14109 case 'c':
14110 commit_id_str = optarg;
14111 break;
14112 case 'P':
14113 force_path = 1;
14114 break;
14115 case 'r':
14116 repo_path = realpath(optarg, NULL);
14117 if (repo_path == NULL)
14118 return got_error_from_errno2("realpath",
14119 optarg);
14120 got_path_strip_trailing_slashes(repo_path);
14121 break;
14122 default:
14123 usage_cat();
14124 /* NOTREACHED */
14128 argc -= optind;
14129 argv += optind;
14131 cwd = getcwd(NULL, 0);
14132 if (cwd == NULL) {
14133 error = got_error_from_errno("getcwd");
14134 goto done;
14137 error = got_repo_pack_fds_open(&pack_fds);
14138 if (error != NULL)
14139 goto done;
14141 if (repo_path == NULL) {
14142 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14143 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14144 goto done;
14145 if (worktree) {
14146 repo_path = strdup(
14147 got_worktree_get_repo_path(worktree));
14148 if (repo_path == NULL) {
14149 error = got_error_from_errno("strdup");
14150 goto done;
14153 if (commit_id_str == NULL) {
14154 /* Release work tree lock. */
14155 got_worktree_close(worktree);
14156 worktree = NULL;
14161 if (repo_path == NULL) {
14162 repo_path = strdup(cwd);
14163 if (repo_path == NULL)
14164 return got_error_from_errno("strdup");
14167 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14168 free(repo_path);
14169 if (error != NULL)
14170 goto done;
14172 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14173 if (error)
14174 goto done;
14176 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14177 if (error)
14178 goto done;
14180 if (commit_id_str != NULL) {
14181 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14182 repo, worktree);
14183 if (error != NULL)
14184 goto done;
14185 if (keyword_idstr != NULL)
14186 commit_id_str = keyword_idstr;
14187 if (worktree != NULL) {
14188 got_worktree_close(worktree);
14189 worktree = NULL;
14191 } else
14192 commit_id_str = GOT_REF_HEAD;
14193 error = got_repo_match_object_id(&commit_id, NULL,
14194 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14195 if (error)
14196 goto done;
14198 error = got_object_open_as_commit(&commit, repo, commit_id);
14199 if (error)
14200 goto done;
14202 for (i = 0; i < argc; i++) {
14203 if (force_path) {
14204 error = got_object_id_by_path(&id, repo, commit,
14205 argv[i]);
14206 if (error)
14207 break;
14208 } else {
14209 error = got_repo_match_object_id(&id, &label, argv[i],
14210 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14211 repo);
14212 if (error) {
14213 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14214 error->code != GOT_ERR_NOT_REF)
14215 break;
14216 error = got_object_id_by_path(&id, repo,
14217 commit, argv[i]);
14218 if (error)
14219 break;
14223 error = got_object_get_type(&obj_type, repo, id);
14224 if (error)
14225 break;
14227 switch (obj_type) {
14228 case GOT_OBJ_TYPE_BLOB:
14229 error = cat_blob(id, repo, stdout);
14230 break;
14231 case GOT_OBJ_TYPE_TREE:
14232 error = cat_tree(id, repo, stdout);
14233 break;
14234 case GOT_OBJ_TYPE_COMMIT:
14235 error = cat_commit(id, repo, stdout);
14236 break;
14237 case GOT_OBJ_TYPE_TAG:
14238 error = cat_tag(id, repo, stdout);
14239 break;
14240 default:
14241 error = got_error(GOT_ERR_OBJ_TYPE);
14242 break;
14244 if (error)
14245 break;
14246 free(label);
14247 label = NULL;
14248 free(id);
14249 id = NULL;
14251 done:
14252 free(label);
14253 free(id);
14254 free(commit_id);
14255 free(keyword_idstr);
14256 if (commit)
14257 got_object_commit_close(commit);
14258 if (worktree)
14259 got_worktree_close(worktree);
14260 if (repo) {
14261 const struct got_error *close_err = got_repo_close(repo);
14262 if (error == NULL)
14263 error = close_err;
14265 if (pack_fds) {
14266 const struct got_error *pack_err =
14267 got_repo_pack_fds_close(pack_fds);
14268 if (error == NULL)
14269 error = pack_err;
14272 got_ref_list_free(&refs);
14273 return error;
14276 __dead static void
14277 usage_info(void)
14279 fprintf(stderr, "usage: %s info [path ...]\n",
14280 getprogname());
14281 exit(1);
14284 static const struct got_error *
14285 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14286 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14287 struct got_object_id *commit_id)
14289 const struct got_error *err = NULL;
14290 char *id_str = NULL;
14291 char datebuf[128];
14292 struct tm mytm, *tm;
14293 struct got_pathlist_head *paths = arg;
14294 struct got_pathlist_entry *pe;
14297 * Clear error indication from any of the path arguments which
14298 * would cause this file index entry to be displayed.
14300 TAILQ_FOREACH(pe, paths, entry) {
14301 if (got_path_cmp(path, pe->path, strlen(path),
14302 pe->path_len) == 0 ||
14303 got_path_is_child(path, pe->path, pe->path_len))
14304 pe->data = NULL; /* no error */
14307 printf(GOT_COMMIT_SEP_STR);
14308 if (S_ISLNK(mode))
14309 printf("symlink: %s\n", path);
14310 else if (S_ISREG(mode)) {
14311 printf("file: %s\n", path);
14312 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14313 } else if (S_ISDIR(mode))
14314 printf("directory: %s\n", path);
14315 else
14316 printf("something: %s\n", path);
14318 tm = localtime_r(&mtime, &mytm);
14319 if (tm == NULL)
14320 return NULL;
14321 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14322 return got_error(GOT_ERR_NO_SPACE);
14323 printf("timestamp: %s\n", datebuf);
14325 if (blob_id) {
14326 err = got_object_id_str(&id_str, blob_id);
14327 if (err)
14328 return err;
14329 printf("based on blob: %s\n", id_str);
14330 free(id_str);
14333 if (staged_blob_id) {
14334 err = got_object_id_str(&id_str, staged_blob_id);
14335 if (err)
14336 return err;
14337 printf("based on staged blob: %s\n", id_str);
14338 free(id_str);
14341 if (commit_id) {
14342 err = got_object_id_str(&id_str, commit_id);
14343 if (err)
14344 return err;
14345 printf("based on commit: %s\n", id_str);
14346 free(id_str);
14349 return NULL;
14352 static const struct got_error *
14353 cmd_info(int argc, char *argv[])
14355 const struct got_error *error = NULL;
14356 struct got_worktree *worktree = NULL;
14357 char *cwd = NULL, *id_str = NULL;
14358 struct got_pathlist_head paths;
14359 char *uuidstr = NULL;
14360 int ch, show_files = 0;
14362 TAILQ_INIT(&paths);
14364 #ifndef PROFILE
14365 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14366 NULL) == -1)
14367 err(1, "pledge");
14368 #endif
14370 while ((ch = getopt(argc, argv, "")) != -1) {
14371 switch (ch) {
14372 default:
14373 usage_info();
14374 /* NOTREACHED */
14378 argc -= optind;
14379 argv += optind;
14381 cwd = getcwd(NULL, 0);
14382 if (cwd == NULL) {
14383 error = got_error_from_errno("getcwd");
14384 goto done;
14387 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14388 if (error) {
14389 if (error->code == GOT_ERR_NOT_WORKTREE)
14390 error = wrap_not_worktree_error(error, "info", cwd);
14391 goto done;
14394 #ifndef PROFILE
14395 /* Remove "wpath cpath proc exec sendfd" promises. */
14396 if (pledge("stdio rpath flock unveil", NULL) == -1)
14397 err(1, "pledge");
14398 #endif
14399 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14400 if (error)
14401 goto done;
14403 if (argc >= 1) {
14404 error = get_worktree_paths_from_argv(&paths, argc, argv,
14405 worktree);
14406 if (error)
14407 goto done;
14408 show_files = 1;
14411 error = got_object_id_str(&id_str,
14412 got_worktree_get_base_commit_id(worktree));
14413 if (error)
14414 goto done;
14416 error = got_worktree_get_uuid(&uuidstr, worktree);
14417 if (error)
14418 goto done;
14420 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14421 printf("work tree base commit: %s\n", id_str);
14422 printf("work tree path prefix: %s\n",
14423 got_worktree_get_path_prefix(worktree));
14424 printf("work tree branch reference: %s\n",
14425 got_worktree_get_head_ref_name(worktree));
14426 printf("work tree UUID: %s\n", uuidstr);
14427 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14429 if (show_files) {
14430 struct got_pathlist_entry *pe;
14431 TAILQ_FOREACH(pe, &paths, entry) {
14432 if (pe->path_len == 0)
14433 continue;
14435 * Assume this path will fail. This will be corrected
14436 * in print_path_info() in case the path does suceeed.
14438 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14440 error = got_worktree_path_info(worktree, &paths,
14441 print_path_info, &paths, check_cancelled, NULL);
14442 if (error)
14443 goto done;
14444 TAILQ_FOREACH(pe, &paths, entry) {
14445 if (pe->data != NULL) {
14446 const struct got_error *perr;
14448 perr = pe->data;
14449 error = got_error_fmt(perr->code, "%s",
14450 pe->path);
14451 break;
14455 done:
14456 if (worktree)
14457 got_worktree_close(worktree);
14458 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14459 free(cwd);
14460 free(id_str);
14461 free(uuidstr);
14462 return error;