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 <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.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>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 #ifndef GOT_DEFAULT_EDITOR
72 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
73 #endif
75 static volatile sig_atomic_t sigint_received;
76 static volatile sig_atomic_t sigpipe_received;
78 static void
79 catch_sigint(int signo)
80 {
81 sigint_received = 1;
82 }
84 static void
85 catch_sigpipe(int signo)
86 {
87 sigpipe_received = 1;
88 }
91 struct got_cmd {
92 const char *cmd_name;
93 const struct got_error *(*cmd_main)(int, char *[]);
94 void (*cmd_usage)(void);
95 const char *cmd_alias;
96 };
98 __dead static void usage(int, int);
99 __dead static void usage_import(void);
100 __dead static void usage_clone(void);
101 __dead static void usage_fetch(void);
102 __dead static void usage_checkout(void);
103 __dead static void usage_update(void);
104 __dead static void usage_log(void);
105 __dead static void usage_diff(void);
106 __dead static void usage_blame(void);
107 __dead static void usage_tree(void);
108 __dead static void usage_status(void);
109 __dead static void usage_ref(void);
110 __dead static void usage_branch(void);
111 __dead static void usage_tag(void);
112 __dead static void usage_add(void);
113 __dead static void usage_remove(void);
114 __dead static void usage_patch(void);
115 __dead static void usage_revert(void);
116 __dead static void usage_commit(void);
117 __dead static void usage_send(void);
118 __dead static void usage_cherrypick(void);
119 __dead static void usage_backout(void);
120 __dead static void usage_rebase(void);
121 __dead static void usage_histedit(void);
122 __dead static void usage_integrate(void);
123 __dead static void usage_merge(void);
124 __dead static void usage_stage(void);
125 __dead static void usage_unstage(void);
126 __dead static void usage_cat(void);
127 __dead static void usage_info(void);
129 static const struct got_error* cmd_import(int, char *[]);
130 static const struct got_error* cmd_clone(int, char *[]);
131 static const struct got_error* cmd_fetch(int, char *[]);
132 static const struct got_error* cmd_checkout(int, char *[]);
133 static const struct got_error* cmd_update(int, char *[]);
134 static const struct got_error* cmd_log(int, char *[]);
135 static const struct got_error* cmd_diff(int, char *[]);
136 static const struct got_error* cmd_blame(int, char *[]);
137 static const struct got_error* cmd_tree(int, char *[]);
138 static const struct got_error* cmd_status(int, char *[]);
139 static const struct got_error* cmd_ref(int, char *[]);
140 static const struct got_error* cmd_branch(int, char *[]);
141 static const struct got_error* cmd_tag(int, char *[]);
142 static const struct got_error* cmd_add(int, char *[]);
143 static const struct got_error* cmd_remove(int, char *[]);
144 static const struct got_error* cmd_patch(int, char *[]);
145 static const struct got_error* cmd_revert(int, char *[]);
146 static const struct got_error* cmd_commit(int, char *[]);
147 static const struct got_error* cmd_send(int, char *[]);
148 static const struct got_error* cmd_cherrypick(int, char *[]);
149 static const struct got_error* cmd_backout(int, char *[]);
150 static const struct got_error* cmd_rebase(int, char *[]);
151 static const struct got_error* cmd_histedit(int, char *[]);
152 static const struct got_error* cmd_integrate(int, char *[]);
153 static const struct got_error* cmd_merge(int, char *[]);
154 static const struct got_error* cmd_stage(int, char *[]);
155 static const struct got_error* cmd_unstage(int, char *[]);
156 static const struct got_error* cmd_cat(int, char *[]);
157 static const struct got_error* cmd_info(int, char *[]);
159 static const struct got_cmd got_commands[] = {
160 { "import", cmd_import, usage_import, "im" },
161 { "clone", cmd_clone, usage_clone, "cl" },
162 { "fetch", cmd_fetch, usage_fetch, "fe" },
163 { "checkout", cmd_checkout, usage_checkout, "co" },
164 { "update", cmd_update, usage_update, "up" },
165 { "log", cmd_log, usage_log, "" },
166 { "diff", cmd_diff, usage_diff, "di" },
167 { "blame", cmd_blame, usage_blame, "bl" },
168 { "tree", cmd_tree, usage_tree, "tr" },
169 { "status", cmd_status, usage_status, "st" },
170 { "ref", cmd_ref, usage_ref, "" },
171 { "branch", cmd_branch, usage_branch, "br" },
172 { "tag", cmd_tag, usage_tag, "" },
173 { "add", cmd_add, usage_add, "" },
174 { "remove", cmd_remove, usage_remove, "rm" },
175 { "patch", cmd_patch, usage_patch, "pa" },
176 { "revert", cmd_revert, usage_revert, "rv" },
177 { "commit", cmd_commit, usage_commit, "ci" },
178 { "send", cmd_send, usage_send, "se" },
179 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
180 { "backout", cmd_backout, usage_backout, "bo" },
181 { "rebase", cmd_rebase, usage_rebase, "rb" },
182 { "histedit", cmd_histedit, usage_histedit, "he" },
183 { "integrate", cmd_integrate, usage_integrate,"ig" },
184 { "merge", cmd_merge, usage_merge, "mg" },
185 { "stage", cmd_stage, usage_stage, "sg" },
186 { "unstage", cmd_unstage, usage_unstage, "ug" },
187 { "cat", cmd_cat, usage_cat, "" },
188 { "info", cmd_info, usage_info, "" },
189 };
191 static void
192 list_commands(FILE *fp)
194 size_t i;
196 fprintf(fp, "commands:");
197 for (i = 0; i < nitems(got_commands); i++) {
198 const struct got_cmd *cmd = &got_commands[i];
199 fprintf(fp, " %s", cmd->cmd_name);
201 fputc('\n', fp);
204 __dead static void
205 option_conflict(char a, char b)
207 errx(1, "-%c and -%c options are mutually exclusive", a, b);
210 int
211 main(int argc, char *argv[])
213 const struct got_cmd *cmd;
214 size_t i;
215 int ch;
216 int hflag = 0, Vflag = 0;
217 static const struct option longopts[] = {
218 { "version", no_argument, NULL, 'V' },
219 { NULL, 0, NULL, 0 }
220 };
222 setlocale(LC_CTYPE, "");
224 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
225 switch (ch) {
226 case 'h':
227 hflag = 1;
228 break;
229 case 'V':
230 Vflag = 1;
231 break;
232 default:
233 usage(hflag, 1);
234 /* NOTREACHED */
238 argc -= optind;
239 argv += optind;
240 optind = 1;
241 optreset = 1;
243 if (Vflag) {
244 got_version_print_str();
245 return 0;
248 if (argc <= 0)
249 usage(hflag, hflag ? 0 : 1);
251 signal(SIGINT, catch_sigint);
252 signal(SIGPIPE, catch_sigpipe);
254 for (i = 0; i < nitems(got_commands); i++) {
255 const struct got_error *error;
257 cmd = &got_commands[i];
259 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
260 strcmp(cmd->cmd_alias, argv[0]) != 0)
261 continue;
263 if (hflag)
264 cmd->cmd_usage();
266 error = cmd->cmd_main(argc, argv);
267 if (error && error->code != GOT_ERR_CANCELLED &&
268 error->code != GOT_ERR_PRIVSEP_EXIT &&
269 !(sigpipe_received &&
270 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
271 !(sigint_received &&
272 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
273 fflush(stdout);
274 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
275 return 1;
278 return 0;
281 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
282 list_commands(stderr);
283 return 1;
286 __dead static void
287 usage(int hflag, int status)
289 FILE *fp = (status == 0) ? stdout : stderr;
291 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
292 getprogname());
293 if (hflag)
294 list_commands(fp);
295 exit(status);
298 static const struct got_error *
299 get_editor(char **abspath)
301 const struct got_error *err = NULL;
302 const char *editor;
304 *abspath = NULL;
306 editor = getenv("VISUAL");
307 if (editor == NULL)
308 editor = getenv("EDITOR");
310 if (editor) {
311 err = got_path_find_prog(abspath, editor);
312 if (err)
313 return err;
316 if (*abspath == NULL) {
317 *abspath = strdup(GOT_DEFAULT_EDITOR);
318 if (*abspath == NULL)
319 return got_error_from_errno("strdup");
322 return NULL;
325 static const struct got_error *
326 apply_unveil(const char *repo_path, int repo_read_only,
327 const char *worktree_path)
329 const struct got_error *err;
331 #ifdef PROFILE
332 if (unveil("gmon.out", "rwc") != 0)
333 return got_error_from_errno2("unveil", "gmon.out");
334 #endif
335 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
336 return got_error_from_errno2("unveil", repo_path);
338 if (worktree_path && unveil(worktree_path, "rwc") != 0)
339 return got_error_from_errno2("unveil", worktree_path);
341 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
342 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
344 err = got_privsep_unveil_exec_helpers();
345 if (err != NULL)
346 return err;
348 if (unveil(NULL, NULL) != 0)
349 return got_error_from_errno("unveil");
351 return NULL;
354 __dead static void
355 usage_import(void)
357 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
358 "[-r repository-path] directory\n", getprogname());
359 exit(1);
362 static int
363 spawn_editor(const char *editor, const char *file)
365 pid_t pid;
366 sig_t sighup, sigint, sigquit;
367 int st = -1;
369 sighup = signal(SIGHUP, SIG_IGN);
370 sigint = signal(SIGINT, SIG_IGN);
371 sigquit = signal(SIGQUIT, SIG_IGN);
373 switch (pid = fork()) {
374 case -1:
375 goto doneediting;
376 case 0:
377 execl(editor, editor, file, (char *)NULL);
378 _exit(127);
381 while (waitpid(pid, &st, 0) == -1)
382 if (errno != EINTR)
383 break;
385 doneediting:
386 (void)signal(SIGHUP, sighup);
387 (void)signal(SIGINT, sigint);
388 (void)signal(SIGQUIT, sigquit);
390 if (!WIFEXITED(st)) {
391 errno = EINTR;
392 return -1;
395 return WEXITSTATUS(st);
398 static const struct got_error *
399 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
401 const struct got_error *err = NULL;
402 char *line = NULL;
403 size_t linesize = 0;
405 *logmsg = NULL;
406 *len = 0;
408 if (fseeko(fp, 0L, SEEK_SET) == -1)
409 return got_error_from_errno("fseeko");
411 *logmsg = malloc(filesize + 1);
412 if (*logmsg == NULL)
413 return got_error_from_errno("malloc");
414 (*logmsg)[0] = '\0';
416 while (getline(&line, &linesize, fp) != -1) {
417 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
418 continue; /* remove comments and leading empty lines */
419 *len = strlcat(*logmsg, line, filesize + 1);
420 if (*len >= filesize + 1) {
421 err = got_error(GOT_ERR_NO_SPACE);
422 goto done;
425 if (ferror(fp)) {
426 err = got_ferror(fp, GOT_ERR_IO);
427 goto done;
430 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
431 (*logmsg)[*len - 1] = '\0';
432 (*len)--;
434 done:
435 free(line);
436 if (err) {
437 free(*logmsg);
438 *logmsg = NULL;
439 *len = 0;
441 return err;
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 struct stat st, st2;
451 FILE *fp = NULL;
452 size_t logmsg_len;
454 *logmsg = NULL;
456 if (stat(logmsg_path, &st) == -1)
457 return got_error_from_errno2("stat", logmsg_path);
459 if (spawn_editor(editor, logmsg_path) == -1)
460 return got_error_from_errno("failed spawning editor");
462 if (require_modification) {
463 struct timespec timeout;
465 timeout.tv_sec = 0;
466 timeout.tv_nsec = 1;
467 nanosleep(&timeout, NULL);
470 if (stat(logmsg_path, &st2) == -1)
471 return got_error_from_errno2("stat", logmsg_path);
473 if (require_modification && st.st_size == st2.st_size &&
474 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
475 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "no changes made to commit message, aborting");
478 fp = fopen(logmsg_path, "re");
479 if (fp == NULL) {
480 err = got_error_from_errno("fopen");
481 goto done;
484 /* strip comments and leading/trailing newlines */
485 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
486 if (err)
487 goto done;
488 if (logmsg_len == 0) {
489 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
490 "commit message cannot be empty, aborting");
491 goto done;
493 done:
494 if (fp && fclose(fp) == EOF && err == NULL)
495 err = got_error_from_errno("fclose");
496 if (err) {
497 free(*logmsg);
498 *logmsg = NULL;
500 return err;
503 static const struct got_error *
504 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
505 const char *path_dir, const char *branch_name)
507 char *initial_content = NULL;
508 const struct got_error *err = NULL;
509 int initial_content_len;
510 int fd = -1;
512 initial_content_len = asprintf(&initial_content,
513 "\n# %s to be imported to branch %s\n", path_dir,
514 branch_name);
515 if (initial_content_len == -1)
516 return got_error_from_errno("asprintf");
518 err = got_opentemp_named_fd(logmsg_path, &fd,
519 GOT_TMPDIR_STR "/got-importmsg", "");
520 if (err)
521 goto done;
523 if (write(fd, initial_content, initial_content_len) == -1) {
524 err = got_error_from_errno2("write", *logmsg_path);
525 goto done;
527 if (close(fd) == -1) {
528 err = got_error_from_errno2("close", *logmsg_path);
529 goto done;
531 fd = -1;
533 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
534 initial_content_len, 1);
535 done:
536 if (fd != -1 && close(fd) == -1 && err == NULL)
537 err = got_error_from_errno2("close", *logmsg_path);
538 free(initial_content);
539 if (err) {
540 free(*logmsg_path);
541 *logmsg_path = NULL;
543 return err;
546 static const struct got_error *
547 import_progress(void *arg, const char *path)
549 printf("A %s\n", path);
550 return NULL;
553 static const struct got_error *
554 valid_author(const char *author)
556 const char *email = author;
558 /*
559 * Git' expects the author (or committer) to be in the form
560 * "name <email>", which are mostly free form (see the
561 * "committer" description in git-fast-import(1)). We're only
562 * doing this to avoid git's object parser breaking on commits
563 * we create.
564 */
566 while (*author && *author != '\n' && *author != '<' && *author != '>')
567 author++;
568 if (author != email && *author == '<' && *(author - 1) != ' ')
569 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
570 "between author name and email required", email);
571 if (*author++ != '<')
572 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
573 while (*author && *author != '\n' && *author != '<' && *author != '>')
574 author++;
575 if (strcmp(author, ">") != 0)
576 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
577 return NULL;
580 static const struct got_error *
581 get_author(char **author, struct got_repository *repo,
582 struct got_worktree *worktree)
584 const struct got_error *err = NULL;
585 const char *got_author = NULL, *name, *email;
586 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
588 *author = NULL;
590 if (worktree)
591 worktree_conf = got_worktree_get_gotconfig(worktree);
592 repo_conf = got_repo_get_gotconfig(repo);
594 /*
595 * Priority of potential author information sources, from most
596 * significant to least significant:
597 * 1) work tree's .got/got.conf file
598 * 2) repository's got.conf file
599 * 3) repository's git config file
600 * 4) environment variables
601 * 5) global git config files (in user's home directory or /etc)
602 */
604 if (worktree_conf)
605 got_author = got_gotconfig_get_author(worktree_conf);
606 if (got_author == NULL)
607 got_author = got_gotconfig_get_author(repo_conf);
608 if (got_author == NULL) {
609 name = got_repo_get_gitconfig_author_name(repo);
610 email = got_repo_get_gitconfig_author_email(repo);
611 if (name && email) {
612 if (asprintf(author, "%s <%s>", name, email) == -1)
613 return got_error_from_errno("asprintf");
614 return NULL;
617 got_author = getenv("GOT_AUTHOR");
618 if (got_author == NULL) {
619 name = got_repo_get_global_gitconfig_author_name(repo);
620 email = got_repo_get_global_gitconfig_author_email(
621 repo);
622 if (name && email) {
623 if (asprintf(author, "%s <%s>", name, email)
624 == -1)
625 return got_error_from_errno("asprintf");
626 return NULL;
628 /* TODO: Look up user in password database? */
629 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
633 *author = strdup(got_author);
634 if (*author == NULL)
635 return got_error_from_errno("strdup");
637 err = valid_author(*author);
638 if (err) {
639 free(*author);
640 *author = NULL;
642 return err;
645 static const struct got_error *
646 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
647 struct got_worktree *worktree)
649 const char *got_allowed_signers = NULL;
650 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
652 *allowed_signers = NULL;
654 if (worktree)
655 worktree_conf = got_worktree_get_gotconfig(worktree);
656 repo_conf = got_repo_get_gotconfig(repo);
658 /*
659 * Priority of potential author information sources, from most
660 * significant to least significant:
661 * 1) work tree's .got/got.conf file
662 * 2) repository's got.conf file
663 */
665 if (worktree_conf)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 worktree_conf);
668 if (got_allowed_signers == NULL)
669 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
670 repo_conf);
672 if (got_allowed_signers) {
673 *allowed_signers = strdup(got_allowed_signers);
674 if (*allowed_signers == NULL)
675 return got_error_from_errno("strdup");
677 return NULL;
680 static const struct got_error *
681 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
682 struct got_worktree *worktree)
684 const char *got_revoked_signers = NULL;
685 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
687 *revoked_signers = NULL;
689 if (worktree)
690 worktree_conf = got_worktree_get_gotconfig(worktree);
691 repo_conf = got_repo_get_gotconfig(repo);
693 /*
694 * Priority of potential author information sources, from most
695 * significant to least significant:
696 * 1) work tree's .got/got.conf file
697 * 2) repository's got.conf file
698 */
700 if (worktree_conf)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 worktree_conf);
703 if (got_revoked_signers == NULL)
704 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
705 repo_conf);
707 if (got_revoked_signers) {
708 *revoked_signers = strdup(got_revoked_signers);
709 if (*revoked_signers == NULL)
710 return got_error_from_errno("strdup");
712 return NULL;
715 static const char *
716 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
718 const char *got_signer_id = NULL;
719 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 return got_signer_id;
740 static const struct got_error *
741 get_gitconfig_path(char **gitconfig_path)
743 const char *homedir = getenv("HOME");
745 *gitconfig_path = NULL;
746 if (homedir) {
747 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
748 return got_error_from_errno("asprintf");
751 return NULL;
754 static const struct got_error *
755 cmd_import(int argc, char *argv[])
757 const struct got_error *error = NULL;
758 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
759 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
760 const char *branch_name = NULL;
761 char *id_str = NULL, *logmsg_path = NULL;
762 char refname[PATH_MAX] = "refs/heads/";
763 struct got_repository *repo = NULL;
764 struct got_reference *branch_ref = NULL, *head_ref = NULL;
765 struct got_object_id *new_commit_id = NULL;
766 int ch, n = 0;
767 struct got_pathlist_head ignores;
768 struct got_pathlist_entry *pe;
769 int preserve_logmsg = 0;
770 int *pack_fds = NULL;
772 TAILQ_INIT(&ignores);
774 #ifndef PROFILE
775 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
776 "unveil",
777 NULL) == -1)
778 err(1, "pledge");
779 #endif
781 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
782 switch (ch) {
783 case 'b':
784 branch_name = optarg;
785 break;
786 case 'I':
787 if (optarg[0] == '\0')
788 break;
789 error = got_pathlist_insert(&pe, &ignores, optarg,
790 NULL);
791 if (error)
792 goto done;
793 break;
794 case 'm':
795 logmsg = strdup(optarg);
796 if (logmsg == NULL) {
797 error = got_error_from_errno("strdup");
798 goto done;
800 break;
801 case 'r':
802 repo_path = realpath(optarg, NULL);
803 if (repo_path == NULL) {
804 error = got_error_from_errno2("realpath",
805 optarg);
806 goto done;
808 break;
809 default:
810 usage_import();
811 /* NOTREACHED */
815 argc -= optind;
816 argv += optind;
818 if (argc != 1)
819 usage_import();
821 if (repo_path == NULL) {
822 repo_path = getcwd(NULL, 0);
823 if (repo_path == NULL)
824 return got_error_from_errno("getcwd");
826 got_path_strip_trailing_slashes(repo_path);
827 error = get_gitconfig_path(&gitconfig_path);
828 if (error)
829 goto done;
830 error = got_repo_pack_fds_open(&pack_fds);
831 if (error != NULL)
832 goto done;
833 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
834 if (error)
835 goto done;
837 path_dir = realpath(argv[0], NULL);
838 if (path_dir == NULL) {
839 error = got_error_from_errno2("realpath", argv[0]);
840 goto done;
842 got_path_strip_trailing_slashes(path_dir);
844 error = get_editor(&editor);
845 if (error)
846 goto done;
848 if (unveil(path_dir, "r") != 0) {
849 error = got_error_from_errno2("unveil", path_dir);
850 goto done;
852 if (unveil(editor, "x") != 0) {
853 error = got_error_from_errno2("unveil", editor);
854 goto done;
856 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
857 if (error)
858 goto done;
860 error = get_author(&author, repo, NULL);
861 if (error)
862 return error;
864 /*
865 * Don't let the user create a branch name with a leading '-'.
866 * While technically a valid reference name, this case is usually
867 * an unintended typo.
868 */
869 if (branch_name && branch_name[0] == '-')
870 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
872 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
873 if (error && error->code != GOT_ERR_NOT_REF)
874 goto done;
876 if (branch_name)
877 n = strlcat(refname, branch_name, sizeof(refname));
878 else if (head_ref && got_ref_is_symbolic(head_ref))
879 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
880 sizeof(refname));
881 else
882 n = strlcat(refname, "main", sizeof(refname));
883 if (n >= sizeof(refname)) {
884 error = got_error(GOT_ERR_NO_SPACE);
885 goto done;
888 error = got_ref_open(&branch_ref, repo, refname, 0);
889 if (error) {
890 if (error->code != GOT_ERR_NOT_REF)
891 goto done;
892 } else {
893 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
894 "import target branch already exists");
895 goto done;
898 if (logmsg == NULL || *logmsg == '\0') {
899 free(logmsg);
900 error = collect_import_msg(&logmsg, &logmsg_path, editor,
901 path_dir, refname);
902 if (error) {
903 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
904 logmsg_path != NULL)
905 preserve_logmsg = 1;
906 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes;
2291 struct got_remote_repo *remote = NULL;
2292 int nremotes;
2293 char *id_str = NULL;
2294 struct got_repository *repo = NULL;
2295 struct got_worktree *worktree = NULL;
2296 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2297 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2298 char *head_refname = NULL;
2299 struct got_pathlist_entry *pe;
2300 struct got_reflist_head remote_refs;
2301 struct got_reflist_entry *re;
2302 struct got_object_id *pack_hash = NULL;
2303 int i, ch, fetchfd = -1, fetchstatus;
2304 pid_t fetchpid = -1;
2305 struct got_fetch_progress_arg fpa;
2306 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2307 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2308 int *pack_fds = NULL, have_bflag = 0;
2309 const char *remote_head = NULL, *worktree_branch = NULL;
2311 TAILQ_INIT(&refs);
2312 TAILQ_INIT(&symrefs);
2313 TAILQ_INIT(&remote_refs);
2314 TAILQ_INIT(&wanted_branches);
2315 TAILQ_INIT(&wanted_refs);
2317 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2318 switch (ch) {
2319 case 'a':
2320 fetch_all_branches = 1;
2321 break;
2322 case 'b':
2323 error = got_pathlist_append(&wanted_branches,
2324 optarg, NULL);
2325 if (error)
2326 return error;
2327 have_bflag = 1;
2328 break;
2329 case 'd':
2330 delete_refs = 1;
2331 break;
2332 case 'l':
2333 list_refs_only = 1;
2334 break;
2335 case 'q':
2336 verbosity = -1;
2337 break;
2338 case 'R':
2339 error = got_pathlist_append(&wanted_refs,
2340 optarg, NULL);
2341 if (error)
2342 return error;
2343 break;
2344 case 'r':
2345 repo_path = realpath(optarg, NULL);
2346 if (repo_path == NULL)
2347 return got_error_from_errno2("realpath",
2348 optarg);
2349 got_path_strip_trailing_slashes(repo_path);
2350 break;
2351 case 't':
2352 replace_tags = 1;
2353 break;
2354 case 'v':
2355 if (verbosity < 0)
2356 verbosity = 0;
2357 else if (verbosity < 3)
2358 verbosity++;
2359 break;
2360 case 'X':
2361 delete_remote = 1;
2362 break;
2363 default:
2364 usage_fetch();
2365 break;
2368 argc -= optind;
2369 argv += optind;
2371 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2372 option_conflict('a', 'b');
2373 if (list_refs_only) {
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('l', 'b');
2376 if (fetch_all_branches)
2377 option_conflict('l', 'a');
2378 if (delete_refs)
2379 option_conflict('l', 'd');
2380 if (delete_remote)
2381 option_conflict('l', 'X');
2383 if (delete_remote) {
2384 if (fetch_all_branches)
2385 option_conflict('X', 'a');
2386 if (!TAILQ_EMPTY(&wanted_branches))
2387 option_conflict('X', 'b');
2388 if (delete_refs)
2389 option_conflict('X', 'd');
2390 if (replace_tags)
2391 option_conflict('X', 't');
2392 if (!TAILQ_EMPTY(&wanted_refs))
2393 option_conflict('X', 'R');
2396 if (argc == 0) {
2397 if (delete_remote)
2398 errx(1, "-X option requires a remote name");
2399 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2400 } else if (argc == 1)
2401 remote_name = argv[0];
2402 else
2403 usage_fetch();
2405 cwd = getcwd(NULL, 0);
2406 if (cwd == NULL) {
2407 error = got_error_from_errno("getcwd");
2408 goto done;
2411 error = got_repo_pack_fds_open(&pack_fds);
2412 if (error != NULL)
2413 goto done;
2415 if (repo_path == NULL) {
2416 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2417 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2418 goto done;
2419 else
2420 error = NULL;
2421 if (worktree) {
2422 repo_path =
2423 strdup(got_worktree_get_repo_path(worktree));
2424 if (repo_path == NULL)
2425 error = got_error_from_errno("strdup");
2426 if (error)
2427 goto done;
2428 } else {
2429 repo_path = strdup(cwd);
2430 if (repo_path == NULL) {
2431 error = got_error_from_errno("strdup");
2432 goto done;
2437 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2438 if (error)
2439 goto done;
2441 if (delete_remote) {
2442 error = delete_refs_for_remote(repo, remote_name);
2443 goto done; /* nothing else to do */
2446 if (worktree) {
2447 worktree_conf = got_worktree_get_gotconfig(worktree);
2448 if (worktree_conf) {
2449 got_gotconfig_get_remotes(&nremotes, &remotes,
2450 worktree_conf);
2451 for (i = 0; i < nremotes; i++) {
2452 if (strcmp(remotes[i].name, remote_name) == 0) {
2453 error = got_repo_remote_repo_dup(&remote,
2454 &remotes[i]);
2455 if (error)
2456 goto done;
2457 break;
2462 if (remote == NULL) {
2463 repo_conf = got_repo_get_gotconfig(repo);
2464 if (repo_conf) {
2465 got_gotconfig_get_remotes(&nremotes, &remotes,
2466 repo_conf);
2467 for (i = 0; i < nremotes; i++) {
2468 if (strcmp(remotes[i].name, remote_name) == 0) {
2469 error = got_repo_remote_repo_dup(&remote,
2470 &remotes[i]);
2471 if (error)
2472 goto done;
2473 break;
2478 if (remote == NULL) {
2479 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2480 for (i = 0; i < nremotes; i++) {
2481 if (strcmp(remotes[i].name, remote_name) == 0) {
2482 error = got_repo_remote_repo_dup(&remote,
2483 &remotes[i]);
2484 if (error)
2485 goto done;
2486 break;
2490 if (remote == NULL) {
2491 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2492 goto done;
2495 if (TAILQ_EMPTY(&wanted_branches)) {
2496 if (!fetch_all_branches)
2497 fetch_all_branches = remote->fetch_all_branches;
2498 for (i = 0; i < remote->nfetch_branches; i++) {
2499 error = got_pathlist_append(&wanted_branches,
2500 remote->fetch_branches[i], NULL);
2501 if (error)
2502 goto done;
2505 if (TAILQ_EMPTY(&wanted_refs)) {
2506 for (i = 0; i < remote->nfetch_refs; i++) {
2507 error = got_pathlist_append(&wanted_refs,
2508 remote->fetch_refs[i], NULL);
2509 if (error)
2510 goto done;
2514 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2515 &repo_name, remote->fetch_url);
2516 if (error)
2517 goto done;
2519 if (strcmp(proto, "git") == 0) {
2520 #ifndef PROFILE
2521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2522 "sendfd dns inet unveil", NULL) == -1)
2523 err(1, "pledge");
2524 #endif
2525 } else if (strcmp(proto, "git+ssh") == 0 ||
2526 strcmp(proto, "ssh") == 0) {
2527 #ifndef PROFILE
2528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2529 "sendfd unveil", NULL) == -1)
2530 err(1, "pledge");
2531 #endif
2532 } else if (strcmp(proto, "http") == 0 ||
2533 strcmp(proto, "git+http") == 0) {
2534 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2535 goto done;
2536 } else {
2537 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2538 goto done;
2541 error = got_dial_apply_unveil(proto);
2542 if (error)
2543 goto done;
2545 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2546 if (error)
2547 goto done;
2549 if (worktree) {
2550 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2551 if (head_refname == NULL) {
2552 error = got_error_from_errno("strdup");
2553 goto done;
2556 /* Release work tree lock. */
2557 got_worktree_close(worktree);
2558 worktree = NULL;
2561 if (verbosity >= 0) {
2562 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2563 remote->name, proto, host,
2564 port ? ":" : "", port ? port : "",
2565 *server_path == '/' ? "" : "/", server_path);
2568 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2569 server_path, verbosity);
2570 if (error)
2571 goto done;
2573 if (!have_bflag) {
2575 * If set, get this remote's HEAD ref target so
2576 * if it has changed on the server we can fetch it.
2578 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2579 got_ref_cmp_by_name, repo);
2580 if (error)
2581 goto done;
2583 TAILQ_FOREACH(re, &remote_refs, entry) {
2584 const char *remote_refname, *remote_target;
2585 size_t remote_name_len;
2587 if (!got_ref_is_symbolic(re->ref))
2588 continue;
2590 remote_name_len = strlen(remote->name);
2591 remote_refname = got_ref_get_name(re->ref);
2593 /* we only want refs/remotes/$remote->name/HEAD */
2594 if (strncmp(remote_refname + 13, remote->name,
2595 remote_name_len) != 0)
2596 continue;
2598 if (strcmp(remote_refname + remote_name_len + 14,
2599 GOT_REF_HEAD) != 0)
2600 continue;
2603 * Take the name itself because we already
2604 * only match with refs/heads/ in fetch_pack().
2606 remote_target = got_ref_get_symref_target(re->ref);
2607 remote_head = remote_target + remote_name_len + 14;
2608 break;
2611 if (head_refname &&
2612 strncmp(head_refname, "refs/heads/", 11) == 0)
2613 worktree_branch = head_refname;
2616 fpa.last_scaled_size[0] = '\0';
2617 fpa.last_p_indexed = -1;
2618 fpa.last_p_resolved = -1;
2619 fpa.verbosity = verbosity;
2620 fpa.repo = repo;
2621 fpa.create_configs = 0;
2622 fpa.configs_created = 0;
2623 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2625 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2626 remote->mirror_references, fetch_all_branches, &wanted_branches,
2627 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2628 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2629 if (error)
2630 goto done;
2632 if (list_refs_only) {
2633 error = list_remote_refs(&symrefs, &refs);
2634 goto done;
2637 if (pack_hash == NULL) {
2638 if (verbosity >= 0)
2639 printf("Already up-to-date\n");
2640 } else if (verbosity >= 0) {
2641 error = got_object_id_str(&id_str, pack_hash);
2642 if (error)
2643 goto done;
2644 printf("\nFetched %s.pack\n", id_str);
2645 free(id_str);
2646 id_str = NULL;
2649 /* Update references provided with the pack file. */
2650 TAILQ_FOREACH(pe, &refs, entry) {
2651 const char *refname = pe->path;
2652 struct got_object_id *id = pe->data;
2653 struct got_reference *ref;
2654 char *remote_refname;
2656 if (is_wanted_ref(&wanted_refs, refname) &&
2657 !remote->mirror_references) {
2658 error = update_wanted_ref(refname, id,
2659 remote->name, verbosity, repo);
2660 if (error)
2661 goto done;
2662 continue;
2665 if (remote->mirror_references ||
2666 strncmp("refs/tags/", refname, 10) == 0) {
2667 error = got_ref_open(&ref, repo, refname, 1);
2668 if (error) {
2669 if (error->code != GOT_ERR_NOT_REF)
2670 goto done;
2671 error = create_ref(refname, id, verbosity,
2672 repo);
2673 if (error)
2674 goto done;
2675 } else {
2676 error = update_ref(ref, id, replace_tags,
2677 verbosity, repo);
2678 unlock_err = got_ref_unlock(ref);
2679 if (unlock_err && error == NULL)
2680 error = unlock_err;
2681 got_ref_close(ref);
2682 if (error)
2683 goto done;
2685 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2686 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2687 remote_name, refname + 11) == -1) {
2688 error = got_error_from_errno("asprintf");
2689 goto done;
2692 error = got_ref_open(&ref, repo, remote_refname, 1);
2693 if (error) {
2694 if (error->code != GOT_ERR_NOT_REF)
2695 goto done;
2696 error = create_ref(remote_refname, id,
2697 verbosity, repo);
2698 if (error)
2699 goto done;
2700 } else {
2701 error = update_ref(ref, id, replace_tags,
2702 verbosity, repo);
2703 unlock_err = got_ref_unlock(ref);
2704 if (unlock_err && error == NULL)
2705 error = unlock_err;
2706 got_ref_close(ref);
2707 if (error)
2708 goto done;
2711 /* Also create a local branch if none exists yet. */
2712 error = got_ref_open(&ref, repo, refname, 1);
2713 if (error) {
2714 if (error->code != GOT_ERR_NOT_REF)
2715 goto done;
2716 error = create_ref(refname, id, verbosity,
2717 repo);
2718 if (error)
2719 goto done;
2720 } else {
2721 unlock_err = got_ref_unlock(ref);
2722 if (unlock_err && error == NULL)
2723 error = unlock_err;
2724 got_ref_close(ref);
2728 if (delete_refs) {
2729 error = delete_missing_refs(&refs, &symrefs, remote,
2730 verbosity, repo);
2731 if (error)
2732 goto done;
2735 if (!remote->mirror_references) {
2736 /* Update remote HEAD reference if the server provided one. */
2737 TAILQ_FOREACH(pe, &symrefs, entry) {
2738 struct got_reference *target_ref;
2739 const char *refname = pe->path;
2740 const char *target = pe->data;
2741 char *remote_refname = NULL, *remote_target = NULL;
2743 if (strcmp(refname, GOT_REF_HEAD) != 0)
2744 continue;
2746 if (strncmp("refs/heads/", target, 11) != 0)
2747 continue;
2749 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2750 remote->name, refname) == -1) {
2751 error = got_error_from_errno("asprintf");
2752 goto done;
2754 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2755 remote->name, target + 11) == -1) {
2756 error = got_error_from_errno("asprintf");
2757 free(remote_refname);
2758 goto done;
2761 error = got_ref_open(&target_ref, repo, remote_target,
2762 0);
2763 if (error) {
2764 free(remote_refname);
2765 free(remote_target);
2766 if (error->code == GOT_ERR_NOT_REF) {
2767 error = NULL;
2768 continue;
2770 goto done;
2772 error = update_symref(remote_refname, target_ref,
2773 verbosity, repo);
2774 free(remote_refname);
2775 free(remote_target);
2776 got_ref_close(target_ref);
2777 if (error)
2778 goto done;
2781 done:
2782 if (fetchpid > 0) {
2783 if (kill(fetchpid, SIGTERM) == -1)
2784 error = got_error_from_errno("kill");
2785 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2786 error = got_error_from_errno("waitpid");
2788 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2789 error = got_error_from_errno("close");
2790 if (repo) {
2791 const struct got_error *close_err = got_repo_close(repo);
2792 if (error == NULL)
2793 error = close_err;
2795 if (worktree)
2796 got_worktree_close(worktree);
2797 if (pack_fds) {
2798 const struct got_error *pack_err =
2799 got_repo_pack_fds_close(pack_fds);
2800 if (error == NULL)
2801 error = pack_err;
2803 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2804 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2805 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2806 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2807 got_ref_list_free(&remote_refs);
2808 got_repo_free_remote_repo_data(remote);
2809 free(remote);
2810 free(head_refname);
2811 free(id_str);
2812 free(cwd);
2813 free(repo_path);
2814 free(pack_hash);
2815 free(proto);
2816 free(host);
2817 free(port);
2818 free(server_path);
2819 free(repo_name);
2820 return error;
2824 __dead static void
2825 usage_checkout(void)
2827 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2828 "[-p path-prefix] repository-path [work-tree-path]\n",
2829 getprogname());
2830 exit(1);
2833 static void
2834 show_worktree_base_ref_warning(void)
2836 fprintf(stderr, "%s: warning: could not create a reference "
2837 "to the work tree's base commit; the commit could be "
2838 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2839 "repository writable and running 'got update' will prevent this\n",
2840 getprogname());
2843 struct got_checkout_progress_arg {
2844 const char *worktree_path;
2845 int had_base_commit_ref_error;
2846 int verbosity;
2849 static const struct got_error *
2850 checkout_progress(void *arg, unsigned char status, const char *path)
2852 struct got_checkout_progress_arg *a = arg;
2854 /* Base commit bump happens silently. */
2855 if (status == GOT_STATUS_BUMP_BASE)
2856 return NULL;
2858 if (status == GOT_STATUS_BASE_REF_ERR) {
2859 a->had_base_commit_ref_error = 1;
2860 return NULL;
2863 while (path[0] == '/')
2864 path++;
2866 if (a->verbosity >= 0)
2867 printf("%c %s/%s\n", status, a->worktree_path, path);
2869 return NULL;
2872 static const struct got_error *
2873 check_cancelled(void *arg)
2875 if (sigint_received || sigpipe_received)
2876 return got_error(GOT_ERR_CANCELLED);
2877 return NULL;
2880 static const struct got_error *
2881 check_linear_ancestry(struct got_object_id *commit_id,
2882 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2883 struct got_repository *repo)
2885 const struct got_error *err = NULL;
2886 struct got_object_id *yca_id;
2888 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2889 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2890 if (err)
2891 return err;
2893 if (yca_id == NULL)
2894 return got_error(GOT_ERR_ANCESTRY);
2897 * Require a straight line of history between the target commit
2898 * and the work tree's base commit.
2900 * Non-linear situations such as this require a rebase:
2902 * (commit) D F (base_commit)
2903 * \ /
2904 * C E
2905 * \ /
2906 * B (yca)
2907 * |
2908 * A
2910 * 'got update' only handles linear cases:
2911 * Update forwards in time: A (base/yca) - B - C - D (commit)
2912 * Update backwards in time: D (base) - C - B - A (commit/yca)
2914 if (allow_forwards_in_time_only) {
2915 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2916 return got_error(GOT_ERR_ANCESTRY);
2917 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2918 got_object_id_cmp(base_commit_id, yca_id) != 0)
2919 return got_error(GOT_ERR_ANCESTRY);
2921 free(yca_id);
2922 return NULL;
2925 static const struct got_error *
2926 check_same_branch(struct got_object_id *commit_id,
2927 struct got_reference *head_ref, struct got_repository *repo)
2929 const struct got_error *err = NULL;
2930 struct got_commit_graph *graph = NULL;
2931 struct got_object_id *head_commit_id = NULL;
2933 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2934 if (err)
2935 goto done;
2937 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2938 goto done;
2940 err = got_commit_graph_open(&graph, "/", 1);
2941 if (err)
2942 goto done;
2944 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2945 check_cancelled, NULL);
2946 if (err)
2947 goto done;
2949 for (;;) {
2950 struct got_object_id id;
2952 err = got_commit_graph_iter_next(&id, graph, repo,
2953 check_cancelled, NULL);
2954 if (err) {
2955 if (err->code == GOT_ERR_ITER_COMPLETED)
2956 err = got_error(GOT_ERR_ANCESTRY);
2957 break;
2960 if (got_object_id_cmp(&id, commit_id) == 0)
2961 break;
2963 done:
2964 if (graph)
2965 got_commit_graph_close(graph);
2966 free(head_commit_id);
2967 return err;
2970 static const struct got_error *
2971 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2973 static char msg[512];
2974 const char *branch_name;
2976 if (got_ref_is_symbolic(ref))
2977 branch_name = got_ref_get_symref_target(ref);
2978 else
2979 branch_name = got_ref_get_name(ref);
2981 if (strncmp("refs/heads/", branch_name, 11) == 0)
2982 branch_name += 11;
2984 snprintf(msg, sizeof(msg),
2985 "target commit is not contained in branch '%s'; "
2986 "the branch to use must be specified with -b; "
2987 "if necessary a new branch can be created for "
2988 "this commit with 'got branch -c %s BRANCH_NAME'",
2989 branch_name, commit_id_str);
2991 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2994 static const struct got_error *
2995 cmd_checkout(int argc, char *argv[])
2997 const struct got_error *close_err, *error = NULL;
2998 struct got_repository *repo = NULL;
2999 struct got_reference *head_ref = NULL, *ref = NULL;
3000 struct got_worktree *worktree = NULL;
3001 char *repo_path = NULL;
3002 char *worktree_path = NULL;
3003 const char *path_prefix = "";
3004 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3005 char *commit_id_str = NULL, *keyword_idstr = NULL;
3006 struct got_object_id *commit_id = NULL;
3007 char *cwd = NULL;
3008 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3009 struct got_pathlist_head paths;
3010 struct got_checkout_progress_arg cpa;
3011 int *pack_fds = NULL;
3013 TAILQ_INIT(&paths);
3015 #ifndef PROFILE
3016 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3017 "unveil", NULL) == -1)
3018 err(1, "pledge");
3019 #endif
3021 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3022 switch (ch) {
3023 case 'b':
3024 branch_name = optarg;
3025 break;
3026 case 'c':
3027 commit_id_str = strdup(optarg);
3028 if (commit_id_str == NULL)
3029 return got_error_from_errno("strdup");
3030 break;
3031 case 'E':
3032 allow_nonempty = 1;
3033 break;
3034 case 'p':
3035 path_prefix = optarg;
3036 break;
3037 case 'q':
3038 verbosity = -1;
3039 break;
3040 default:
3041 usage_checkout();
3042 /* NOTREACHED */
3046 argc -= optind;
3047 argv += optind;
3049 if (argc == 1) {
3050 char *base, *dotgit;
3051 const char *path;
3052 repo_path = realpath(argv[0], NULL);
3053 if (repo_path == NULL)
3054 return got_error_from_errno2("realpath", argv[0]);
3055 cwd = getcwd(NULL, 0);
3056 if (cwd == NULL) {
3057 error = got_error_from_errno("getcwd");
3058 goto done;
3060 if (path_prefix[0])
3061 path = path_prefix;
3062 else
3063 path = repo_path;
3064 error = got_path_basename(&base, path);
3065 if (error)
3066 goto done;
3067 dotgit = strstr(base, ".git");
3068 if (dotgit)
3069 *dotgit = '\0';
3070 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3071 error = got_error_from_errno("asprintf");
3072 free(base);
3073 goto done;
3075 free(base);
3076 } else if (argc == 2) {
3077 repo_path = realpath(argv[0], NULL);
3078 if (repo_path == NULL) {
3079 error = got_error_from_errno2("realpath", argv[0]);
3080 goto done;
3082 worktree_path = realpath(argv[1], NULL);
3083 if (worktree_path == NULL) {
3084 if (errno != ENOENT) {
3085 error = got_error_from_errno2("realpath",
3086 argv[1]);
3087 goto done;
3089 worktree_path = strdup(argv[1]);
3090 if (worktree_path == NULL) {
3091 error = got_error_from_errno("strdup");
3092 goto done;
3095 } else
3096 usage_checkout();
3098 got_path_strip_trailing_slashes(repo_path);
3099 got_path_strip_trailing_slashes(worktree_path);
3101 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3102 got_path_is_child(repo_path, worktree_path,
3103 strlen(worktree_path))) {
3104 error = got_error_fmt(GOT_ERR_BAD_PATH,
3105 "work tree and repository paths may not overlap: %s",
3106 worktree_path);
3107 goto done;
3110 error = got_repo_pack_fds_open(&pack_fds);
3111 if (error != NULL)
3112 goto done;
3114 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3115 if (error != NULL)
3116 goto done;
3118 /* Pre-create work tree path for unveil(2) */
3119 error = got_path_mkdir(worktree_path);
3120 if (error) {
3121 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3122 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3123 goto done;
3124 if (!allow_nonempty &&
3125 !got_path_dir_is_empty(worktree_path)) {
3126 error = got_error_path(worktree_path,
3127 GOT_ERR_DIR_NOT_EMPTY);
3128 goto done;
3132 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3133 if (error)
3134 goto done;
3136 error = got_ref_open(&head_ref, repo, branch_name, 0);
3137 if (error != NULL)
3138 goto done;
3140 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3141 GOT_WORKTREE_GOT_DIR, repo);
3142 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3143 goto done;
3145 error = got_worktree_open(&worktree, worktree_path,
3146 GOT_WORKTREE_GOT_DIR);
3147 if (error != NULL)
3148 goto done;
3150 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3151 path_prefix);
3152 if (error != NULL)
3153 goto done;
3154 if (!same_path_prefix) {
3155 error = got_error(GOT_ERR_PATH_PREFIX);
3156 goto done;
3159 if (commit_id_str) {
3160 struct got_reflist_head refs;
3161 TAILQ_INIT(&refs);
3162 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3163 NULL);
3164 if (error)
3165 goto done;
3167 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3168 repo, worktree);
3169 if (error != NULL)
3170 goto done;
3171 if (keyword_idstr != NULL) {
3172 free(commit_id_str);
3173 commit_id_str = keyword_idstr;
3176 error = got_repo_match_object_id(&commit_id, NULL,
3177 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3178 got_ref_list_free(&refs);
3179 if (error)
3180 goto done;
3181 error = check_linear_ancestry(commit_id,
3182 got_worktree_get_base_commit_id(worktree), 0, repo);
3183 if (error != NULL) {
3184 if (error->code == GOT_ERR_ANCESTRY) {
3185 error = checkout_ancestry_error(
3186 head_ref, commit_id_str);
3188 goto done;
3190 error = check_same_branch(commit_id, head_ref, repo);
3191 if (error) {
3192 if (error->code == GOT_ERR_ANCESTRY) {
3193 error = checkout_ancestry_error(
3194 head_ref, commit_id_str);
3196 goto done;
3198 error = got_worktree_set_base_commit_id(worktree, repo,
3199 commit_id);
3200 if (error)
3201 goto done;
3202 /* Expand potentially abbreviated commit ID string. */
3203 free(commit_id_str);
3204 error = got_object_id_str(&commit_id_str, commit_id);
3205 if (error)
3206 goto done;
3207 } else {
3208 commit_id = got_object_id_dup(
3209 got_worktree_get_base_commit_id(worktree));
3210 if (commit_id == NULL) {
3211 error = got_error_from_errno("got_object_id_dup");
3212 goto done;
3214 error = got_object_id_str(&commit_id_str, commit_id);
3215 if (error)
3216 goto done;
3219 error = got_pathlist_append(&paths, "", NULL);
3220 if (error)
3221 goto done;
3222 cpa.worktree_path = worktree_path;
3223 cpa.had_base_commit_ref_error = 0;
3224 cpa.verbosity = verbosity;
3225 error = got_worktree_checkout_files(worktree, &paths, repo,
3226 checkout_progress, &cpa, check_cancelled, NULL);
3227 if (error != NULL)
3228 goto done;
3230 if (got_ref_is_symbolic(head_ref)) {
3231 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3232 if (error)
3233 goto done;
3234 refname = got_ref_get_name(ref);
3235 } else
3236 refname = got_ref_get_name(head_ref);
3237 printf("Checked out %s: %s\n", refname, commit_id_str);
3238 printf("Now shut up and hack\n");
3239 if (cpa.had_base_commit_ref_error)
3240 show_worktree_base_ref_warning();
3241 done:
3242 if (pack_fds) {
3243 const struct got_error *pack_err =
3244 got_repo_pack_fds_close(pack_fds);
3245 if (error == NULL)
3246 error = pack_err;
3248 if (head_ref)
3249 got_ref_close(head_ref);
3250 if (ref)
3251 got_ref_close(ref);
3252 if (repo) {
3253 close_err = got_repo_close(repo);
3254 if (error == NULL)
3255 error = close_err;
3257 if (worktree != NULL) {
3258 close_err = got_worktree_close(worktree);
3259 if (error == NULL)
3260 error = close_err;
3262 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3263 free(commit_id_str);
3264 free(commit_id);
3265 free(repo_path);
3266 free(worktree_path);
3267 free(cwd);
3268 return error;
3271 struct got_update_progress_arg {
3272 int did_something;
3273 int conflicts;
3274 int obstructed;
3275 int not_updated;
3276 int missing;
3277 int not_deleted;
3278 int unversioned;
3279 int verbosity;
3282 static void
3283 print_update_progress_stats(struct got_update_progress_arg *upa)
3285 if (!upa->did_something)
3286 return;
3288 if (upa->conflicts > 0)
3289 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3290 if (upa->obstructed > 0)
3291 printf("File paths obstructed by a non-regular file: %d\n",
3292 upa->obstructed);
3293 if (upa->not_updated > 0)
3294 printf("Files not updated because of existing merge "
3295 "conflicts: %d\n", upa->not_updated);
3299 * The meaning of some status codes differs between merge-style operations and
3300 * update operations. For example, the ! status code means "file was missing"
3301 * if changes were merged into the work tree, and "missing file was restored"
3302 * if the work tree was updated. This function should be used by any operation
3303 * which merges changes into the work tree without updating the work tree.
3305 static void
3306 print_merge_progress_stats(struct got_update_progress_arg *upa)
3308 if (!upa->did_something)
3309 return;
3311 if (upa->conflicts > 0)
3312 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3313 if (upa->obstructed > 0)
3314 printf("File paths obstructed by a non-regular file: %d\n",
3315 upa->obstructed);
3316 if (upa->missing > 0)
3317 printf("Files which had incoming changes but could not be "
3318 "found in the work tree: %d\n", upa->missing);
3319 if (upa->not_deleted > 0)
3320 printf("Files not deleted due to differences in deleted "
3321 "content: %d\n", upa->not_deleted);
3322 if (upa->unversioned > 0)
3323 printf("Files not merged because an unversioned file was "
3324 "found in the work tree: %d\n", upa->unversioned);
3327 __dead static void
3328 usage_update(void)
3330 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3331 "[path ...]\n", getprogname());
3332 exit(1);
3335 static const struct got_error *
3336 update_progress(void *arg, unsigned char status, const char *path)
3338 struct got_update_progress_arg *upa = arg;
3340 if (status == GOT_STATUS_EXISTS ||
3341 status == GOT_STATUS_BASE_REF_ERR)
3342 return NULL;
3344 upa->did_something = 1;
3346 /* Base commit bump happens silently. */
3347 if (status == GOT_STATUS_BUMP_BASE)
3348 return NULL;
3350 if (status == GOT_STATUS_CONFLICT)
3351 upa->conflicts++;
3352 if (status == GOT_STATUS_OBSTRUCTED)
3353 upa->obstructed++;
3354 if (status == GOT_STATUS_CANNOT_UPDATE)
3355 upa->not_updated++;
3356 if (status == GOT_STATUS_MISSING)
3357 upa->missing++;
3358 if (status == GOT_STATUS_CANNOT_DELETE)
3359 upa->not_deleted++;
3360 if (status == GOT_STATUS_UNVERSIONED)
3361 upa->unversioned++;
3363 while (path[0] == '/')
3364 path++;
3365 if (upa->verbosity >= 0)
3366 printf("%c %s\n", status, path);
3368 return NULL;
3371 static const struct got_error *
3372 switch_head_ref(struct got_reference *head_ref,
3373 struct got_object_id *commit_id, struct got_worktree *worktree,
3374 struct got_repository *repo)
3376 const struct got_error *err = NULL;
3377 char *base_id_str;
3378 int ref_has_moved = 0;
3380 /* Trivial case: switching between two different references. */
3381 if (strcmp(got_ref_get_name(head_ref),
3382 got_worktree_get_head_ref_name(worktree)) != 0) {
3383 printf("Switching work tree from %s to %s\n",
3384 got_worktree_get_head_ref_name(worktree),
3385 got_ref_get_name(head_ref));
3386 return got_worktree_set_head_ref(worktree, head_ref);
3389 err = check_linear_ancestry(commit_id,
3390 got_worktree_get_base_commit_id(worktree), 0, repo);
3391 if (err) {
3392 if (err->code != GOT_ERR_ANCESTRY)
3393 return err;
3394 ref_has_moved = 1;
3396 if (!ref_has_moved)
3397 return NULL;
3399 /* Switching to a rebased branch with the same reference name. */
3400 err = got_object_id_str(&base_id_str,
3401 got_worktree_get_base_commit_id(worktree));
3402 if (err)
3403 return err;
3404 printf("Reference %s now points at a different branch\n",
3405 got_worktree_get_head_ref_name(worktree));
3406 printf("Switching work tree from %s to %s\n", base_id_str,
3407 got_worktree_get_head_ref_name(worktree));
3408 return NULL;
3411 static const struct got_error *
3412 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3414 const struct got_error *err;
3415 int in_progress;
3417 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3418 if (err)
3419 return err;
3420 if (in_progress)
3421 return got_error(GOT_ERR_REBASING);
3423 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3424 if (err)
3425 return err;
3426 if (in_progress)
3427 return got_error(GOT_ERR_HISTEDIT_BUSY);
3429 return NULL;
3432 static const struct got_error *
3433 check_merge_in_progress(struct got_worktree *worktree,
3434 struct got_repository *repo)
3436 const struct got_error *err;
3437 int in_progress;
3439 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3440 if (err)
3441 return err;
3442 if (in_progress)
3443 return got_error(GOT_ERR_MERGE_BUSY);
3445 return NULL;
3448 static const struct got_error *
3449 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3450 char *argv[], struct got_worktree *worktree)
3452 const struct got_error *err = NULL;
3453 char *path;
3454 struct got_pathlist_entry *new;
3455 int i;
3457 if (argc == 0) {
3458 path = strdup("");
3459 if (path == NULL)
3460 return got_error_from_errno("strdup");
3461 return got_pathlist_append(paths, path, NULL);
3464 for (i = 0; i < argc; i++) {
3465 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3466 if (err)
3467 break;
3468 err = got_pathlist_insert(&new, paths, path, NULL);
3469 if (err || new == NULL /* duplicate */) {
3470 free(path);
3471 if (err)
3472 break;
3476 return err;
3479 static const struct got_error *
3480 wrap_not_worktree_error(const struct got_error *orig_err,
3481 const char *cmdname, const char *path)
3483 const struct got_error *err;
3484 struct got_repository *repo;
3485 static char msg[512];
3486 int *pack_fds = NULL;
3488 err = got_repo_pack_fds_open(&pack_fds);
3489 if (err)
3490 return err;
3492 err = got_repo_open(&repo, path, NULL, pack_fds);
3493 if (err)
3494 return orig_err;
3496 snprintf(msg, sizeof(msg),
3497 "'got %s' needs a work tree in addition to a git repository\n"
3498 "Work trees can be checked out from this Git repository with "
3499 "'got checkout'.\n"
3500 "The got(1) manual page contains more information.", cmdname);
3501 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3502 if (repo) {
3503 const struct got_error *close_err = got_repo_close(repo);
3504 if (err == NULL)
3505 err = close_err;
3507 if (pack_fds) {
3508 const struct got_error *pack_err =
3509 got_repo_pack_fds_close(pack_fds);
3510 if (err == NULL)
3511 err = pack_err;
3513 return err;
3516 static const struct got_error *
3517 cmd_update(int argc, char *argv[])
3519 const struct got_error *close_err, *error = NULL;
3520 struct got_repository *repo = NULL;
3521 struct got_worktree *worktree = NULL;
3522 char *worktree_path = NULL;
3523 struct got_object_id *commit_id = NULL;
3524 char *commit_id_str = NULL;
3525 const char *branch_name = NULL;
3526 struct got_reference *head_ref = NULL;
3527 struct got_pathlist_head paths;
3528 struct got_pathlist_entry *pe;
3529 int ch, verbosity = 0;
3530 struct got_update_progress_arg upa;
3531 int *pack_fds = NULL;
3533 TAILQ_INIT(&paths);
3535 #ifndef PROFILE
3536 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3537 "unveil", NULL) == -1)
3538 err(1, "pledge");
3539 #endif
3541 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3542 switch (ch) {
3543 case 'b':
3544 branch_name = optarg;
3545 break;
3546 case 'c':
3547 commit_id_str = strdup(optarg);
3548 if (commit_id_str == NULL)
3549 return got_error_from_errno("strdup");
3550 break;
3551 case 'q':
3552 verbosity = -1;
3553 break;
3554 default:
3555 usage_update();
3556 /* NOTREACHED */
3560 argc -= optind;
3561 argv += optind;
3563 worktree_path = getcwd(NULL, 0);
3564 if (worktree_path == NULL) {
3565 error = got_error_from_errno("getcwd");
3566 goto done;
3569 error = got_repo_pack_fds_open(&pack_fds);
3570 if (error != NULL)
3571 goto done;
3573 error = got_worktree_open(&worktree, worktree_path,
3574 GOT_WORKTREE_GOT_DIR);
3575 if (error) {
3576 if (error->code == GOT_ERR_NOT_WORKTREE)
3577 error = wrap_not_worktree_error(error, "update",
3578 worktree_path);
3579 goto done;
3582 error = check_rebase_or_histedit_in_progress(worktree);
3583 if (error)
3584 goto done;
3586 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3587 NULL, pack_fds);
3588 if (error != NULL)
3589 goto done;
3591 error = apply_unveil(got_repo_get_path(repo), 0,
3592 got_worktree_get_root_path(worktree));
3593 if (error)
3594 goto done;
3596 error = check_merge_in_progress(worktree, repo);
3597 if (error)
3598 goto done;
3600 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3601 if (error)
3602 goto done;
3604 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3605 got_worktree_get_head_ref_name(worktree), 0);
3606 if (error != NULL)
3607 goto done;
3608 if (commit_id_str == NULL) {
3609 error = got_ref_resolve(&commit_id, repo, head_ref);
3610 if (error != NULL)
3611 goto done;
3612 error = got_object_id_str(&commit_id_str, commit_id);
3613 if (error != NULL)
3614 goto done;
3615 } else {
3616 struct got_reflist_head refs;
3617 char *keyword_idstr = NULL;
3619 TAILQ_INIT(&refs);
3621 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3622 NULL);
3623 if (error)
3624 goto done;
3626 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3627 repo, worktree);
3628 if (error != NULL)
3629 goto done;
3630 if (keyword_idstr != NULL) {
3631 free(commit_id_str);
3632 commit_id_str = keyword_idstr;
3635 error = got_repo_match_object_id(&commit_id, NULL,
3636 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3637 got_ref_list_free(&refs);
3638 free(commit_id_str);
3639 commit_id_str = NULL;
3640 if (error)
3641 goto done;
3642 error = got_object_id_str(&commit_id_str, commit_id);
3643 if (error)
3644 goto done;
3647 if (branch_name) {
3648 struct got_object_id *head_commit_id;
3649 TAILQ_FOREACH(pe, &paths, entry) {
3650 if (pe->path_len == 0)
3651 continue;
3652 error = got_error_msg(GOT_ERR_BAD_PATH,
3653 "switching between branches requires that "
3654 "the entire work tree gets updated");
3655 goto done;
3657 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3658 if (error)
3659 goto done;
3660 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3661 repo);
3662 free(head_commit_id);
3663 if (error != NULL)
3664 goto done;
3665 error = check_same_branch(commit_id, head_ref, repo);
3666 if (error)
3667 goto done;
3668 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3669 if (error)
3670 goto done;
3671 } else {
3672 error = check_linear_ancestry(commit_id,
3673 got_worktree_get_base_commit_id(worktree), 0, repo);
3674 if (error != NULL) {
3675 if (error->code == GOT_ERR_ANCESTRY)
3676 error = got_error(GOT_ERR_BRANCH_MOVED);
3677 goto done;
3679 error = check_same_branch(commit_id, head_ref, repo);
3680 if (error)
3681 goto done;
3684 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3685 commit_id) != 0) {
3686 error = got_worktree_set_base_commit_id(worktree, repo,
3687 commit_id);
3688 if (error)
3689 goto done;
3692 memset(&upa, 0, sizeof(upa));
3693 upa.verbosity = verbosity;
3694 error = got_worktree_checkout_files(worktree, &paths, repo,
3695 update_progress, &upa, check_cancelled, NULL);
3696 if (error != NULL)
3697 goto done;
3699 if (upa.did_something) {
3700 printf("Updated to %s: %s\n",
3701 got_worktree_get_head_ref_name(worktree), commit_id_str);
3702 } else
3703 printf("Already up-to-date\n");
3705 print_update_progress_stats(&upa);
3706 done:
3707 if (pack_fds) {
3708 const struct got_error *pack_err =
3709 got_repo_pack_fds_close(pack_fds);
3710 if (error == NULL)
3711 error = pack_err;
3713 if (repo) {
3714 close_err = got_repo_close(repo);
3715 if (error == NULL)
3716 error = close_err;
3718 if (worktree != NULL) {
3719 close_err = got_worktree_close(worktree);
3720 if (error == NULL)
3721 error = close_err;
3723 if (head_ref != NULL)
3724 got_ref_close(head_ref);
3725 free(worktree_path);
3726 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3727 free(commit_id);
3728 free(commit_id_str);
3729 return error;
3732 static const struct got_error *
3733 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3734 const char *path, int diff_context, int ignore_whitespace,
3735 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3736 struct got_repository *repo, FILE *outfile)
3738 const struct got_error *err = NULL;
3739 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3740 FILE *f1 = NULL, *f2 = NULL;
3741 int fd1 = -1, fd2 = -1;
3743 fd1 = got_opentempfd();
3744 if (fd1 == -1)
3745 return got_error_from_errno("got_opentempfd");
3746 fd2 = got_opentempfd();
3747 if (fd2 == -1) {
3748 err = got_error_from_errno("got_opentempfd");
3749 goto done;
3752 if (blob_id1) {
3753 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3754 fd1);
3755 if (err)
3756 goto done;
3759 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3760 if (err)
3761 goto done;
3763 f1 = got_opentemp();
3764 if (f1 == NULL) {
3765 err = got_error_from_errno("got_opentemp");
3766 goto done;
3768 f2 = got_opentemp();
3769 if (f2 == NULL) {
3770 err = got_error_from_errno("got_opentemp");
3771 goto done;
3774 while (path[0] == '/')
3775 path++;
3776 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3777 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3778 force_text_diff, dsa, outfile);
3779 done:
3780 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3781 err = got_error_from_errno("close");
3782 if (blob1)
3783 got_object_blob_close(blob1);
3784 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3785 err = got_error_from_errno("close");
3786 if (blob2)
3787 got_object_blob_close(blob2);
3788 if (f1 && fclose(f1) == EOF && err == NULL)
3789 err = got_error_from_errno("fclose");
3790 if (f2 && fclose(f2) == EOF && err == NULL)
3791 err = got_error_from_errno("fclose");
3792 return err;
3795 static const struct got_error *
3796 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3797 const char *path, int diff_context, int ignore_whitespace,
3798 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3799 struct got_repository *repo, FILE *outfile)
3801 const struct got_error *err = NULL;
3802 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3803 struct got_diff_blob_output_unidiff_arg arg;
3804 FILE *f1 = NULL, *f2 = NULL;
3805 int fd1 = -1, fd2 = -1;
3807 if (tree_id1) {
3808 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3809 if (err)
3810 goto done;
3811 fd1 = got_opentempfd();
3812 if (fd1 == -1) {
3813 err = got_error_from_errno("got_opentempfd");
3814 goto done;
3818 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3819 if (err)
3820 goto done;
3822 f1 = got_opentemp();
3823 if (f1 == NULL) {
3824 err = got_error_from_errno("got_opentemp");
3825 goto done;
3828 f2 = got_opentemp();
3829 if (f2 == NULL) {
3830 err = got_error_from_errno("got_opentemp");
3831 goto done;
3833 fd2 = got_opentempfd();
3834 if (fd2 == -1) {
3835 err = got_error_from_errno("got_opentempfd");
3836 goto done;
3838 arg.diff_context = diff_context;
3839 arg.ignore_whitespace = ignore_whitespace;
3840 arg.force_text_diff = force_text_diff;
3841 arg.diffstat = dsa;
3842 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3843 arg.outfile = outfile;
3844 arg.lines = NULL;
3845 arg.nlines = 0;
3846 while (path[0] == '/')
3847 path++;
3848 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3849 got_diff_blob_output_unidiff, &arg, 1);
3850 done:
3851 if (tree1)
3852 got_object_tree_close(tree1);
3853 if (tree2)
3854 got_object_tree_close(tree2);
3855 if (f1 && fclose(f1) == EOF && err == NULL)
3856 err = got_error_from_errno("fclose");
3857 if (f2 && fclose(f2) == EOF && err == NULL)
3858 err = got_error_from_errno("fclose");
3859 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3860 err = got_error_from_errno("close");
3861 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3862 err = got_error_from_errno("close");
3863 return err;
3866 static const struct got_error *
3867 get_changed_paths(struct got_pathlist_head *paths,
3868 struct got_commit_object *commit, struct got_repository *repo,
3869 struct got_diffstat_cb_arg *dsa)
3871 const struct got_error *err = NULL;
3872 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3873 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3874 struct got_object_qid *qid;
3875 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3876 FILE *f1 = NULL, *f2 = NULL;
3877 int fd1 = -1, fd2 = -1;
3879 if (dsa) {
3880 cb = got_diff_tree_compute_diffstat;
3882 f1 = got_opentemp();
3883 if (f1 == NULL) {
3884 err = got_error_from_errno("got_opentemp");
3885 goto done;
3887 f2 = got_opentemp();
3888 if (f2 == NULL) {
3889 err = got_error_from_errno("got_opentemp");
3890 goto done;
3892 fd1 = got_opentempfd();
3893 if (fd1 == -1) {
3894 err = got_error_from_errno("got_opentempfd");
3895 goto done;
3897 fd2 = got_opentempfd();
3898 if (fd2 == -1) {
3899 err = got_error_from_errno("got_opentempfd");
3900 goto done;
3904 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3905 if (qid != NULL) {
3906 struct got_commit_object *pcommit;
3907 err = got_object_open_as_commit(&pcommit, repo,
3908 &qid->id);
3909 if (err)
3910 return err;
3912 tree_id1 = got_object_id_dup(
3913 got_object_commit_get_tree_id(pcommit));
3914 if (tree_id1 == NULL) {
3915 got_object_commit_close(pcommit);
3916 return got_error_from_errno("got_object_id_dup");
3918 got_object_commit_close(pcommit);
3922 if (tree_id1) {
3923 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3924 if (err)
3925 goto done;
3928 tree_id2 = got_object_commit_get_tree_id(commit);
3929 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3930 if (err)
3931 goto done;
3933 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3934 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3935 done:
3936 if (tree1)
3937 got_object_tree_close(tree1);
3938 if (tree2)
3939 got_object_tree_close(tree2);
3940 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3941 err = got_error_from_errno("close");
3942 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3943 err = got_error_from_errno("close");
3944 if (f1 && fclose(f1) == EOF && err == NULL)
3945 err = got_error_from_errno("fclose");
3946 if (f2 && fclose(f2) == EOF && err == NULL)
3947 err = got_error_from_errno("fclose");
3948 free(tree_id1);
3949 return err;
3952 static const struct got_error *
3953 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3954 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3955 struct got_repository *repo, FILE *outfile)
3957 const struct got_error *err = NULL;
3958 struct got_commit_object *pcommit = NULL;
3959 char *id_str1 = NULL, *id_str2 = NULL;
3960 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3961 struct got_object_qid *qid;
3963 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3964 if (qid != NULL) {
3965 err = got_object_open_as_commit(&pcommit, repo,
3966 &qid->id);
3967 if (err)
3968 return err;
3969 err = got_object_id_str(&id_str1, &qid->id);
3970 if (err)
3971 goto done;
3974 err = got_object_id_str(&id_str2, id);
3975 if (err)
3976 goto done;
3978 if (path && path[0] != '\0') {
3979 int obj_type;
3980 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3981 if (err)
3982 goto done;
3983 if (pcommit) {
3984 err = got_object_id_by_path(&obj_id1, repo,
3985 pcommit, path);
3986 if (err) {
3987 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3988 free(obj_id2);
3989 goto done;
3993 err = got_object_get_type(&obj_type, repo, obj_id2);
3994 if (err) {
3995 free(obj_id2);
3996 goto done;
3998 fprintf(outfile,
3999 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4000 fprintf(outfile, "commit - %s\n",
4001 id_str1 ? id_str1 : "/dev/null");
4002 fprintf(outfile, "commit + %s\n", id_str2);
4003 switch (obj_type) {
4004 case GOT_OBJ_TYPE_BLOB:
4005 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4006 0, 0, dsa, repo, outfile);
4007 break;
4008 case GOT_OBJ_TYPE_TREE:
4009 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4010 0, 0, dsa, repo, outfile);
4011 break;
4012 default:
4013 err = got_error(GOT_ERR_OBJ_TYPE);
4014 break;
4016 free(obj_id1);
4017 free(obj_id2);
4018 } else {
4019 obj_id2 = got_object_commit_get_tree_id(commit);
4020 if (pcommit)
4021 obj_id1 = got_object_commit_get_tree_id(pcommit);
4022 fprintf(outfile,
4023 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4024 fprintf(outfile, "commit - %s\n",
4025 id_str1 ? id_str1 : "/dev/null");
4026 fprintf(outfile, "commit + %s\n", id_str2);
4027 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4028 dsa, repo, outfile);
4030 done:
4031 free(id_str1);
4032 free(id_str2);
4033 if (pcommit)
4034 got_object_commit_close(pcommit);
4035 return err;
4038 static char *
4039 get_datestr(time_t *time, char *datebuf)
4041 struct tm mytm, *tm;
4042 char *p, *s;
4044 tm = gmtime_r(time, &mytm);
4045 if (tm == NULL)
4046 return NULL;
4047 s = asctime_r(tm, datebuf);
4048 if (s == NULL)
4049 return NULL;
4050 p = strchr(s, '\n');
4051 if (p)
4052 *p = '\0';
4053 return s;
4056 static const struct got_error *
4057 match_commit(int *have_match, struct got_object_id *id,
4058 struct got_commit_object *commit, regex_t *regex)
4060 const struct got_error *err = NULL;
4061 regmatch_t regmatch;
4062 char *id_str = NULL, *logmsg = NULL;
4064 *have_match = 0;
4066 err = got_object_id_str(&id_str, id);
4067 if (err)
4068 return err;
4070 err = got_object_commit_get_logmsg(&logmsg, commit);
4071 if (err)
4072 goto done;
4074 if (regexec(regex, got_object_commit_get_author(commit), 1,
4075 &regmatch, 0) == 0 ||
4076 regexec(regex, got_object_commit_get_committer(commit), 1,
4077 &regmatch, 0) == 0 ||
4078 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4079 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4080 *have_match = 1;
4081 done:
4082 free(id_str);
4083 free(logmsg);
4084 return err;
4087 static void
4088 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4089 regex_t *regex)
4091 regmatch_t regmatch;
4092 struct got_pathlist_entry *pe;
4094 *have_match = 0;
4096 TAILQ_FOREACH(pe, changed_paths, entry) {
4097 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4098 *have_match = 1;
4099 break;
4104 static const struct got_error *
4105 match_patch(int *have_match, struct got_commit_object *commit,
4106 struct got_object_id *id, const char *path, int diff_context,
4107 struct got_repository *repo, regex_t *regex, FILE *f)
4109 const struct got_error *err = NULL;
4110 char *line = NULL;
4111 size_t linesize = 0;
4112 regmatch_t regmatch;
4114 *have_match = 0;
4116 err = got_opentemp_truncate(f);
4117 if (err)
4118 return err;
4120 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4121 if (err)
4122 goto done;
4124 if (fseeko(f, 0L, SEEK_SET) == -1) {
4125 err = got_error_from_errno("fseeko");
4126 goto done;
4129 while (getline(&line, &linesize, f) != -1) {
4130 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4131 *have_match = 1;
4132 break;
4135 done:
4136 free(line);
4137 return err;
4140 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4142 static const struct got_error*
4143 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4144 struct got_object_id *id, struct got_repository *repo,
4145 int local_only)
4147 static const struct got_error *err = NULL;
4148 struct got_reflist_entry *re;
4149 char *s;
4150 const char *name;
4152 *refs_str = NULL;
4154 TAILQ_FOREACH(re, refs, entry) {
4155 struct got_tag_object *tag = NULL;
4156 struct got_object_id *ref_id;
4157 int cmp;
4159 name = got_ref_get_name(re->ref);
4160 if (strcmp(name, GOT_REF_HEAD) == 0)
4161 continue;
4162 if (strncmp(name, "refs/", 5) == 0)
4163 name += 5;
4164 if (strncmp(name, "got/", 4) == 0)
4165 continue;
4166 if (strncmp(name, "heads/", 6) == 0)
4167 name += 6;
4168 if (strncmp(name, "remotes/", 8) == 0) {
4169 if (local_only)
4170 continue;
4171 name += 8;
4172 s = strstr(name, "/" GOT_REF_HEAD);
4173 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4174 continue;
4176 err = got_ref_resolve(&ref_id, repo, re->ref);
4177 if (err)
4178 break;
4179 if (strncmp(name, "tags/", 5) == 0) {
4180 err = got_object_open_as_tag(&tag, repo, ref_id);
4181 if (err) {
4182 if (err->code != GOT_ERR_OBJ_TYPE) {
4183 free(ref_id);
4184 break;
4186 /* Ref points at something other than a tag. */
4187 err = NULL;
4188 tag = NULL;
4191 cmp = got_object_id_cmp(tag ?
4192 got_object_tag_get_object_id(tag) : ref_id, id);
4193 free(ref_id);
4194 if (tag)
4195 got_object_tag_close(tag);
4196 if (cmp != 0)
4197 continue;
4198 s = *refs_str;
4199 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4200 s ? ", " : "", name) == -1) {
4201 err = got_error_from_errno("asprintf");
4202 free(s);
4203 *refs_str = NULL;
4204 break;
4206 free(s);
4209 return err;
4212 static const struct got_error *
4213 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4214 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4216 const struct got_error *err = NULL;
4217 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4218 char *comma, *s, *nl;
4219 struct got_reflist_head *refs;
4220 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4221 struct tm tm;
4222 time_t committer_time;
4224 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4225 if (refs) {
4226 err = build_refs_str(&ref_str, refs, id, repo, 1);
4227 if (err)
4228 return err;
4230 /* Display the first matching ref only. */
4231 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4232 *comma = '\0';
4235 if (ref_str == NULL) {
4236 err = got_object_id_str(&id_str, id);
4237 if (err)
4238 return err;
4241 committer_time = got_object_commit_get_committer_time(commit);
4242 if (gmtime_r(&committer_time, &tm) == NULL) {
4243 err = got_error_from_errno("gmtime_r");
4244 goto done;
4246 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4247 err = got_error(GOT_ERR_NO_SPACE);
4248 goto done;
4251 err = got_object_commit_get_logmsg(&logmsg0, commit);
4252 if (err)
4253 goto done;
4255 s = logmsg0;
4256 while (isspace((unsigned char)s[0]))
4257 s++;
4259 nl = strchr(s, '\n');
4260 if (nl) {
4261 *nl = '\0';
4264 if (ref_str)
4265 printf("%s%-7s %s\n", datebuf, ref_str, s);
4266 else
4267 printf("%s%.7s %s\n", datebuf, id_str, s);
4269 if (fflush(stdout) != 0 && err == NULL)
4270 err = got_error_from_errno("fflush");
4271 done:
4272 free(id_str);
4273 free(ref_str);
4274 free(logmsg0);
4275 return err;
4278 static const struct got_error *
4279 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4281 struct got_pathlist_entry *pe;
4283 if (header != NULL)
4284 printf("%s\n", header);
4286 TAILQ_FOREACH(pe, dsa->paths, entry) {
4287 struct got_diff_changed_path *cp = pe->data;
4288 int pad = dsa->max_path_len - pe->path_len + 1;
4290 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4291 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4293 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4294 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4295 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4297 if (fflush(stdout) != 0)
4298 return got_error_from_errno("fflush");
4300 return NULL;
4303 static const struct got_error *
4304 printfile(FILE *f)
4306 char buf[8192];
4307 size_t r;
4309 if (fseeko(f, 0L, SEEK_SET) == -1)
4310 return got_error_from_errno("fseek");
4312 for (;;) {
4313 r = fread(buf, 1, sizeof(buf), f);
4314 if (r == 0) {
4315 if (ferror(f))
4316 return got_error_from_errno("fread");
4317 if (feof(f))
4318 break;
4320 if (fwrite(buf, 1, r, stdout) != r)
4321 return got_ferror(stdout, GOT_ERR_IO);
4324 return NULL;
4327 static const struct got_error *
4328 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4329 struct got_repository *repo, const char *path,
4330 struct got_pathlist_head *changed_paths,
4331 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4332 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4333 const char *prefix)
4335 const struct got_error *err = NULL;
4336 FILE *f = NULL;
4337 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4338 char datebuf[26];
4339 time_t committer_time;
4340 const char *author, *committer;
4341 char *refs_str = NULL;
4343 err = got_object_id_str(&id_str, id);
4344 if (err)
4345 return err;
4347 if (custom_refs_str == NULL) {
4348 struct got_reflist_head *refs;
4349 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4350 if (refs) {
4351 err = build_refs_str(&refs_str, refs, id, repo, 0);
4352 if (err)
4353 goto done;
4357 printf(GOT_COMMIT_SEP_STR);
4358 if (custom_refs_str)
4359 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4360 custom_refs_str);
4361 else
4362 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4363 refs_str ? " (" : "", refs_str ? refs_str : "",
4364 refs_str ? ")" : "");
4365 free(id_str);
4366 id_str = NULL;
4367 free(refs_str);
4368 refs_str = NULL;
4369 printf("from: %s\n", got_object_commit_get_author(commit));
4370 author = got_object_commit_get_author(commit);
4371 committer = got_object_commit_get_committer(commit);
4372 if (strcmp(author, committer) != 0)
4373 printf("via: %s\n", committer);
4374 committer_time = got_object_commit_get_committer_time(commit);
4375 datestr = get_datestr(&committer_time, datebuf);
4376 if (datestr)
4377 printf("date: %s UTC\n", datestr);
4378 if (got_object_commit_get_nparents(commit) > 1) {
4379 const struct got_object_id_queue *parent_ids;
4380 struct got_object_qid *qid;
4381 int n = 1;
4382 parent_ids = got_object_commit_get_parent_ids(commit);
4383 STAILQ_FOREACH(qid, parent_ids, entry) {
4384 err = got_object_id_str(&id_str, &qid->id);
4385 if (err)
4386 goto done;
4387 printf("parent %d: %s\n", n++, id_str);
4388 free(id_str);
4389 id_str = NULL;
4393 err = got_object_commit_get_logmsg(&logmsg0, commit);
4394 if (err)
4395 goto done;
4397 logmsg = logmsg0;
4398 do {
4399 line = strsep(&logmsg, "\n");
4400 if (line)
4401 printf(" %s\n", line);
4402 } while (line);
4403 free(logmsg0);
4405 if (changed_paths && diffstat == NULL) {
4406 struct got_pathlist_entry *pe;
4408 TAILQ_FOREACH(pe, changed_paths, entry) {
4409 struct got_diff_changed_path *cp = pe->data;
4411 printf(" %c %s\n", cp->status, pe->path);
4413 printf("\n");
4415 if (show_patch) {
4416 if (diffstat) {
4417 f = got_opentemp();
4418 if (f == NULL) {
4419 err = got_error_from_errno("got_opentemp");
4420 goto done;
4424 err = print_patch(commit, id, path, diff_context, diffstat,
4425 repo, diffstat == NULL ? stdout : f);
4426 if (err)
4427 goto done;
4429 if (diffstat) {
4430 err = print_diffstat(diffstat, NULL);
4431 if (err)
4432 goto done;
4433 if (show_patch) {
4434 err = printfile(f);
4435 if (err)
4436 goto done;
4439 if (show_patch)
4440 printf("\n");
4442 if (fflush(stdout) != 0 && err == NULL)
4443 err = got_error_from_errno("fflush");
4444 done:
4445 if (f && fclose(f) == EOF && err == NULL)
4446 err = got_error_from_errno("fclose");
4447 free(id_str);
4448 free(refs_str);
4449 return err;
4452 static const struct got_error *
4453 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4454 struct got_repository *repo, const char *path, int show_changed_paths,
4455 int show_diffstat, int show_patch, const char *search_pattern,
4456 int diff_context, int limit, int log_branches, int reverse_display_order,
4457 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4458 FILE *tmpfile)
4460 const struct got_error *err;
4461 struct got_commit_graph *graph;
4462 regex_t regex;
4463 int have_match;
4464 struct got_object_id_queue reversed_commits;
4465 struct got_object_qid *qid;
4466 struct got_commit_object *commit;
4467 struct got_pathlist_head changed_paths;
4469 STAILQ_INIT(&reversed_commits);
4470 TAILQ_INIT(&changed_paths);
4472 if (search_pattern && regcomp(&regex, search_pattern,
4473 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4474 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4476 err = got_commit_graph_open(&graph, path, !log_branches);
4477 if (err)
4478 return err;
4479 if (log_branches && toposort) {
4480 err = got_commit_graph_toposort(graph, root_id, repo,
4481 check_cancelled, NULL);
4482 } else {
4483 err = got_commit_graph_bfsort(graph, root_id, repo,
4484 check_cancelled, NULL);
4486 if (err)
4487 goto done;
4488 for (;;) {
4489 struct got_object_id id;
4490 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4491 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4493 if (sigint_received || sigpipe_received)
4494 break;
4496 err = got_commit_graph_iter_next(&id, graph, repo,
4497 check_cancelled, NULL);
4498 if (err) {
4499 if (err->code == GOT_ERR_ITER_COMPLETED)
4500 err = NULL;
4501 break;
4504 err = got_object_open_as_commit(&commit, repo, &id);
4505 if (err)
4506 break;
4508 if (((show_changed_paths && !show_diffstat) ||
4509 (show_diffstat && !show_patch))
4510 && !reverse_display_order) {
4511 err = get_changed_paths(&changed_paths, commit, repo,
4512 show_diffstat ? &dsa : NULL);
4513 if (err)
4514 break;
4517 if (search_pattern) {
4518 err = match_commit(&have_match, &id, commit, &regex);
4519 if (err) {
4520 got_object_commit_close(commit);
4521 break;
4523 if (have_match == 0 && show_changed_paths)
4524 match_changed_paths(&have_match,
4525 &changed_paths, &regex);
4526 if (have_match == 0 && show_patch) {
4527 err = match_patch(&have_match, commit, &id,
4528 path, diff_context, repo, &regex, tmpfile);
4529 if (err)
4530 break;
4532 if (have_match == 0) {
4533 got_object_commit_close(commit);
4534 got_pathlist_free(&changed_paths,
4535 GOT_PATHLIST_FREE_ALL);
4536 continue;
4540 if (reverse_display_order) {
4541 err = got_object_qid_alloc(&qid, &id);
4542 if (err)
4543 break;
4544 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4545 got_object_commit_close(commit);
4546 } else {
4547 if (one_line)
4548 err = print_commit_oneline(commit, &id,
4549 repo, refs_idmap);
4550 else
4551 err = print_commit(commit, &id, repo, path,
4552 (show_changed_paths || show_diffstat) ?
4553 &changed_paths : NULL,
4554 show_diffstat ? &dsa : NULL, show_patch,
4555 diff_context, refs_idmap, NULL, NULL);
4556 got_object_commit_close(commit);
4557 if (err)
4558 break;
4560 if ((limit && --limit == 0) ||
4561 (end_id && got_object_id_cmp(&id, end_id) == 0))
4562 break;
4564 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4566 if (reverse_display_order) {
4567 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4568 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4569 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4571 err = got_object_open_as_commit(&commit, repo,
4572 &qid->id);
4573 if (err)
4574 break;
4575 if ((show_changed_paths && !show_diffstat) ||
4576 (show_diffstat && !show_patch)) {
4577 err = get_changed_paths(&changed_paths, commit,
4578 repo, show_diffstat ? &dsa : NULL);
4579 if (err)
4580 break;
4582 if (one_line)
4583 err = print_commit_oneline(commit, &qid->id,
4584 repo, refs_idmap);
4585 else
4586 err = print_commit(commit, &qid->id, repo, path,
4587 (show_changed_paths || show_diffstat) ?
4588 &changed_paths : NULL,
4589 show_diffstat ? &dsa : NULL, show_patch,
4590 diff_context, refs_idmap, NULL, NULL);
4591 got_object_commit_close(commit);
4592 if (err)
4593 break;
4594 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4597 done:
4598 while (!STAILQ_EMPTY(&reversed_commits)) {
4599 qid = STAILQ_FIRST(&reversed_commits);
4600 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4601 got_object_qid_free(qid);
4603 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4604 if (search_pattern)
4605 regfree(&regex);
4606 got_commit_graph_close(graph);
4607 return err;
4610 __dead static void
4611 usage_log(void)
4613 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4614 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4615 "[path]\n", getprogname());
4616 exit(1);
4619 static int
4620 get_default_log_limit(void)
4622 const char *got_default_log_limit;
4623 long long n;
4624 const char *errstr;
4626 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4627 if (got_default_log_limit == NULL)
4628 return 0;
4629 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4630 if (errstr != NULL)
4631 return 0;
4632 return n;
4635 static const struct got_error *
4636 cmd_log(int argc, char *argv[])
4638 const struct got_error *error;
4639 struct got_repository *repo = NULL;
4640 struct got_worktree *worktree = NULL;
4641 struct got_object_id *start_id = NULL, *end_id = NULL;
4642 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4643 char *keyword_idstr = NULL;
4644 const char *start_commit = NULL, *end_commit = NULL;
4645 const char *search_pattern = NULL;
4646 int diff_context = -1, ch;
4647 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4648 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4649 int toposort = 0;
4650 const char *errstr;
4651 struct got_reflist_head refs;
4652 struct got_reflist_object_id_map *refs_idmap = NULL;
4653 FILE *tmpfile = NULL;
4654 int *pack_fds = NULL;
4656 TAILQ_INIT(&refs);
4658 #ifndef PROFILE
4659 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4660 NULL)
4661 == -1)
4662 err(1, "pledge");
4663 #endif
4665 limit = get_default_log_limit();
4667 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4668 switch (ch) {
4669 case 'b':
4670 log_branches = 1;
4671 break;
4672 case 'C':
4673 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4674 &errstr);
4675 if (errstr != NULL)
4676 errx(1, "number of context lines is %s: %s",
4677 errstr, optarg);
4678 break;
4679 case 'c':
4680 start_commit = optarg;
4681 break;
4682 case 'd':
4683 show_diffstat = 1;
4684 break;
4685 case 'l':
4686 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4687 if (errstr != NULL)
4688 errx(1, "number of commits is %s: %s",
4689 errstr, optarg);
4690 break;
4691 case 'P':
4692 show_changed_paths = 1;
4693 break;
4694 case 'p':
4695 show_patch = 1;
4696 break;
4697 case 'R':
4698 reverse_display_order = 1;
4699 break;
4700 case 'r':
4701 repo_path = realpath(optarg, NULL);
4702 if (repo_path == NULL)
4703 return got_error_from_errno2("realpath",
4704 optarg);
4705 got_path_strip_trailing_slashes(repo_path);
4706 break;
4707 case 'S':
4708 search_pattern = optarg;
4709 break;
4710 case 's':
4711 one_line = 1;
4712 break;
4713 case 't':
4714 toposort = 1;
4715 break;
4716 case 'x':
4717 end_commit = optarg;
4718 break;
4719 default:
4720 usage_log();
4721 /* NOTREACHED */
4725 argc -= optind;
4726 argv += optind;
4728 if (diff_context == -1)
4729 diff_context = 3;
4730 else if (!show_patch)
4731 errx(1, "-C requires -p");
4733 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4734 errx(1, "cannot use -s with -d, -p or -P");
4736 cwd = getcwd(NULL, 0);
4737 if (cwd == NULL) {
4738 error = got_error_from_errno("getcwd");
4739 goto done;
4742 error = got_repo_pack_fds_open(&pack_fds);
4743 if (error != NULL)
4744 goto done;
4746 if (repo_path == NULL) {
4747 error = got_worktree_open(&worktree, cwd,
4748 GOT_WORKTREE_GOT_DIR);
4749 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4750 goto done;
4751 error = NULL;
4754 if (argc == 1) {
4755 if (worktree) {
4756 error = got_worktree_resolve_path(&path, worktree,
4757 argv[0]);
4758 if (error)
4759 goto done;
4760 } else {
4761 path = strdup(argv[0]);
4762 if (path == NULL) {
4763 error = got_error_from_errno("strdup");
4764 goto done;
4767 } else if (argc != 0)
4768 usage_log();
4770 if (repo_path == NULL) {
4771 repo_path = worktree ?
4772 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4774 if (repo_path == NULL) {
4775 error = got_error_from_errno("strdup");
4776 goto done;
4779 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4780 if (error != NULL)
4781 goto done;
4783 error = apply_unveil(got_repo_get_path(repo), 1,
4784 worktree ? got_worktree_get_root_path(worktree) : NULL);
4785 if (error)
4786 goto done;
4788 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4789 if (error)
4790 goto done;
4792 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4793 if (error)
4794 goto done;
4796 if (start_commit == NULL) {
4797 struct got_reference *head_ref;
4798 struct got_commit_object *commit = NULL;
4799 error = got_ref_open(&head_ref, repo,
4800 worktree ? got_worktree_get_head_ref_name(worktree)
4801 : GOT_REF_HEAD, 0);
4802 if (error != NULL)
4803 goto done;
4804 error = got_ref_resolve(&start_id, repo, head_ref);
4805 got_ref_close(head_ref);
4806 if (error != NULL)
4807 goto done;
4808 error = got_object_open_as_commit(&commit, repo,
4809 start_id);
4810 if (error != NULL)
4811 goto done;
4812 got_object_commit_close(commit);
4813 } else {
4814 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4815 repo, worktree);
4816 if (error != NULL)
4817 goto done;
4818 if (keyword_idstr != NULL)
4819 start_commit = keyword_idstr;
4821 error = got_repo_match_object_id(&start_id, NULL,
4822 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4823 if (error != NULL)
4824 goto done;
4826 if (end_commit != NULL) {
4827 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4828 repo, worktree);
4829 if (error != NULL)
4830 goto done;
4831 if (keyword_idstr != NULL)
4832 end_commit = keyword_idstr;
4834 error = got_repo_match_object_id(&end_id, NULL,
4835 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4836 if (error != NULL)
4837 goto done;
4840 if (worktree) {
4842 * If a path was specified on the command line it was resolved
4843 * to a path in the work tree above. Prepend the work tree's
4844 * path prefix to obtain the corresponding in-repository path.
4846 if (path) {
4847 const char *prefix;
4848 prefix = got_worktree_get_path_prefix(worktree);
4849 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4850 (path[0] != '\0') ? "/" : "", path) == -1) {
4851 error = got_error_from_errno("asprintf");
4852 goto done;
4855 } else
4856 error = got_repo_map_path(&in_repo_path, repo,
4857 path ? path : "");
4858 if (error != NULL)
4859 goto done;
4860 if (in_repo_path) {
4861 free(path);
4862 path = in_repo_path;
4865 if (worktree) {
4866 /* Release work tree lock. */
4867 got_worktree_close(worktree);
4868 worktree = NULL;
4871 if (search_pattern && show_patch) {
4872 tmpfile = got_opentemp();
4873 if (tmpfile == NULL) {
4874 error = got_error_from_errno("got_opentemp");
4875 goto done;
4879 error = print_commits(start_id, end_id, repo, path ? path : "",
4880 show_changed_paths, show_diffstat, show_patch, search_pattern,
4881 diff_context, limit, log_branches, reverse_display_order,
4882 refs_idmap, one_line, toposort, tmpfile);
4883 done:
4884 free(path);
4885 free(repo_path);
4886 free(cwd);
4887 free(start_id);
4888 free(end_id);
4889 free(keyword_idstr);
4890 if (worktree)
4891 got_worktree_close(worktree);
4892 if (repo) {
4893 const struct got_error *close_err = got_repo_close(repo);
4894 if (error == NULL)
4895 error = close_err;
4897 if (pack_fds) {
4898 const struct got_error *pack_err =
4899 got_repo_pack_fds_close(pack_fds);
4900 if (error == NULL)
4901 error = pack_err;
4903 if (refs_idmap)
4904 got_reflist_object_id_map_free(refs_idmap);
4905 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4906 error = got_error_from_errno("fclose");
4907 got_ref_list_free(&refs);
4908 return error;
4911 __dead static void
4912 usage_diff(void)
4914 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4915 "[-r repository-path] [object1 object2 | path ...]\n",
4916 getprogname());
4917 exit(1);
4920 struct print_diff_arg {
4921 struct got_repository *repo;
4922 struct got_worktree *worktree;
4923 struct got_diffstat_cb_arg *diffstat;
4924 int diff_context;
4925 const char *id_str;
4926 int header_shown;
4927 int diff_staged;
4928 enum got_diff_algorithm diff_algo;
4929 int ignore_whitespace;
4930 int force_text_diff;
4931 FILE *f1;
4932 FILE *f2;
4933 FILE *outfile;
4937 * Create a file which contains the target path of a symlink so we can feed
4938 * it as content to the diff engine.
4940 static const struct got_error *
4941 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4942 const char *abspath)
4944 const struct got_error *err = NULL;
4945 char target_path[PATH_MAX];
4946 ssize_t target_len, outlen;
4948 *fd = -1;
4950 if (dirfd != -1) {
4951 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4952 if (target_len == -1)
4953 return got_error_from_errno2("readlinkat", abspath);
4954 } else {
4955 target_len = readlink(abspath, target_path, PATH_MAX);
4956 if (target_len == -1)
4957 return got_error_from_errno2("readlink", abspath);
4960 *fd = got_opentempfd();
4961 if (*fd == -1)
4962 return got_error_from_errno("got_opentempfd");
4964 outlen = write(*fd, target_path, target_len);
4965 if (outlen == -1) {
4966 err = got_error_from_errno("got_opentempfd");
4967 goto done;
4970 if (lseek(*fd, 0, SEEK_SET) == -1) {
4971 err = got_error_from_errno2("lseek", abspath);
4972 goto done;
4974 done:
4975 if (err) {
4976 close(*fd);
4977 *fd = -1;
4979 return err;
4982 static const struct got_error *
4983 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4984 const char *path, struct got_object_id *blob_id,
4985 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4986 int dirfd, const char *de_name)
4988 struct print_diff_arg *a = arg;
4989 const struct got_error *err = NULL;
4990 struct got_blob_object *blob1 = NULL;
4991 int fd = -1, fd1 = -1, fd2 = -1;
4992 FILE *f2 = NULL;
4993 char *abspath = NULL, *label1 = NULL;
4994 struct stat sb;
4995 off_t size1 = 0;
4996 int f2_exists = 0;
4998 memset(&sb, 0, sizeof(sb));
5000 if (a->diff_staged) {
5001 if (staged_status != GOT_STATUS_MODIFY &&
5002 staged_status != GOT_STATUS_ADD &&
5003 staged_status != GOT_STATUS_DELETE)
5004 return NULL;
5005 } else {
5006 if (staged_status == GOT_STATUS_DELETE)
5007 return NULL;
5008 if (status == GOT_STATUS_NONEXISTENT)
5009 return got_error_set_errno(ENOENT, path);
5010 if (status != GOT_STATUS_MODIFY &&
5011 status != GOT_STATUS_ADD &&
5012 status != GOT_STATUS_DELETE &&
5013 status != GOT_STATUS_CONFLICT)
5014 return NULL;
5017 err = got_opentemp_truncate(a->f1);
5018 if (err)
5019 return got_error_from_errno("got_opentemp_truncate");
5020 err = got_opentemp_truncate(a->f2);
5021 if (err)
5022 return got_error_from_errno("got_opentemp_truncate");
5024 if (!a->header_shown) {
5025 if (fprintf(a->outfile, "diff %s%s\n",
5026 a->diff_staged ? "-s " : "",
5027 got_worktree_get_root_path(a->worktree)) < 0) {
5028 err = got_error_from_errno("fprintf");
5029 goto done;
5031 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5032 err = got_error_from_errno("fprintf");
5033 goto done;
5035 if (fprintf(a->outfile, "path + %s%s\n",
5036 got_worktree_get_root_path(a->worktree),
5037 a->diff_staged ? " (staged changes)" : "") < 0) {
5038 err = got_error_from_errno("fprintf");
5039 goto done;
5041 a->header_shown = 1;
5044 if (a->diff_staged) {
5045 const char *label1 = NULL, *label2 = NULL;
5046 switch (staged_status) {
5047 case GOT_STATUS_MODIFY:
5048 label1 = path;
5049 label2 = path;
5050 break;
5051 case GOT_STATUS_ADD:
5052 label2 = path;
5053 break;
5054 case GOT_STATUS_DELETE:
5055 label1 = path;
5056 break;
5057 default:
5058 return got_error(GOT_ERR_FILE_STATUS);
5060 fd1 = got_opentempfd();
5061 if (fd1 == -1) {
5062 err = got_error_from_errno("got_opentempfd");
5063 goto done;
5065 fd2 = got_opentempfd();
5066 if (fd2 == -1) {
5067 err = got_error_from_errno("got_opentempfd");
5068 goto done;
5070 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5071 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5072 a->diff_algo, a->diff_context, a->ignore_whitespace,
5073 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5074 goto done;
5077 fd1 = got_opentempfd();
5078 if (fd1 == -1) {
5079 err = got_error_from_errno("got_opentempfd");
5080 goto done;
5083 if (staged_status == GOT_STATUS_ADD ||
5084 staged_status == GOT_STATUS_MODIFY) {
5085 char *id_str;
5086 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5087 8192, fd1);
5088 if (err)
5089 goto done;
5090 err = got_object_id_str(&id_str, staged_blob_id);
5091 if (err)
5092 goto done;
5093 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5094 err = got_error_from_errno("asprintf");
5095 free(id_str);
5096 goto done;
5098 free(id_str);
5099 } else if (status != GOT_STATUS_ADD) {
5100 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5101 fd1);
5102 if (err)
5103 goto done;
5106 if (status != GOT_STATUS_DELETE) {
5107 if (asprintf(&abspath, "%s/%s",
5108 got_worktree_get_root_path(a->worktree), path) == -1) {
5109 err = got_error_from_errno("asprintf");
5110 goto done;
5113 if (dirfd != -1) {
5114 fd = openat(dirfd, de_name,
5115 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5116 if (fd == -1) {
5117 if (!got_err_open_nofollow_on_symlink()) {
5118 err = got_error_from_errno2("openat",
5119 abspath);
5120 goto done;
5122 err = get_symlink_target_file(&fd, dirfd,
5123 de_name, abspath);
5124 if (err)
5125 goto done;
5127 } else {
5128 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5129 if (fd == -1) {
5130 if (!got_err_open_nofollow_on_symlink()) {
5131 err = got_error_from_errno2("open",
5132 abspath);
5133 goto done;
5135 err = get_symlink_target_file(&fd, dirfd,
5136 de_name, abspath);
5137 if (err)
5138 goto done;
5141 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5142 err = got_error_from_errno2("fstatat", abspath);
5143 goto done;
5145 f2 = fdopen(fd, "r");
5146 if (f2 == NULL) {
5147 err = got_error_from_errno2("fdopen", abspath);
5148 goto done;
5150 fd = -1;
5151 f2_exists = 1;
5154 if (blob1) {
5155 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5156 a->f1, blob1);
5157 if (err)
5158 goto done;
5161 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5162 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5163 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5164 done:
5165 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5166 err = got_error_from_errno("close");
5167 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5168 err = got_error_from_errno("close");
5169 if (blob1)
5170 got_object_blob_close(blob1);
5171 if (fd != -1 && close(fd) == -1 && err == NULL)
5172 err = got_error_from_errno("close");
5173 if (f2 && fclose(f2) == EOF && err == NULL)
5174 err = got_error_from_errno("fclose");
5175 free(abspath);
5176 return err;
5179 static const struct got_error *
5180 cmd_diff(int argc, char *argv[])
5182 const struct got_error *error;
5183 struct got_repository *repo = NULL;
5184 struct got_worktree *worktree = NULL;
5185 char *cwd = NULL, *repo_path = NULL;
5186 const char *commit_args[2] = { NULL, NULL };
5187 int ncommit_args = 0;
5188 struct got_object_id *ids[2] = { NULL, NULL };
5189 char *labels[2] = { NULL, NULL };
5190 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5191 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5192 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5193 const char *errstr;
5194 struct got_reflist_head refs;
5195 struct got_pathlist_head diffstat_paths, paths;
5196 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5197 int fd1 = -1, fd2 = -1;
5198 int *pack_fds = NULL;
5199 struct got_diffstat_cb_arg dsa;
5201 memset(&dsa, 0, sizeof(dsa));
5203 TAILQ_INIT(&refs);
5204 TAILQ_INIT(&paths);
5205 TAILQ_INIT(&diffstat_paths);
5207 #ifndef PROFILE
5208 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5209 NULL) == -1)
5210 err(1, "pledge");
5211 #endif
5213 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5214 switch (ch) {
5215 case 'a':
5216 force_text_diff = 1;
5217 break;
5218 case 'C':
5219 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5220 &errstr);
5221 if (errstr != NULL)
5222 errx(1, "number of context lines is %s: %s",
5223 errstr, optarg);
5224 break;
5225 case 'c':
5226 if (ncommit_args >= 2)
5227 errx(1, "too many -c options used");
5228 commit_args[ncommit_args++] = optarg;
5229 break;
5230 case 'd':
5231 show_diffstat = 1;
5232 break;
5233 case 'P':
5234 force_path = 1;
5235 break;
5236 case 'r':
5237 repo_path = realpath(optarg, NULL);
5238 if (repo_path == NULL)
5239 return got_error_from_errno2("realpath",
5240 optarg);
5241 got_path_strip_trailing_slashes(repo_path);
5242 rflag = 1;
5243 break;
5244 case 's':
5245 diff_staged = 1;
5246 break;
5247 case 'w':
5248 ignore_whitespace = 1;
5249 break;
5250 default:
5251 usage_diff();
5252 /* NOTREACHED */
5256 argc -= optind;
5257 argv += optind;
5259 cwd = getcwd(NULL, 0);
5260 if (cwd == NULL) {
5261 error = got_error_from_errno("getcwd");
5262 goto done;
5265 error = got_repo_pack_fds_open(&pack_fds);
5266 if (error != NULL)
5267 goto done;
5269 if (repo_path == NULL) {
5270 error = got_worktree_open(&worktree, cwd,
5271 GOT_WORKTREE_GOT_DIR);
5272 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5273 goto done;
5274 else
5275 error = NULL;
5276 if (worktree) {
5277 repo_path =
5278 strdup(got_worktree_get_repo_path(worktree));
5279 if (repo_path == NULL) {
5280 error = got_error_from_errno("strdup");
5281 goto done;
5283 } else {
5284 repo_path = strdup(cwd);
5285 if (repo_path == NULL) {
5286 error = got_error_from_errno("strdup");
5287 goto done;
5292 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5293 free(repo_path);
5294 if (error != NULL)
5295 goto done;
5297 if (show_diffstat) {
5298 dsa.paths = &diffstat_paths;
5299 dsa.force_text = force_text_diff;
5300 dsa.ignore_ws = ignore_whitespace;
5301 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5304 if (rflag || worktree == NULL || ncommit_args > 0) {
5305 if (force_path) {
5306 error = got_error_msg(GOT_ERR_NOT_IMPL,
5307 "-P option can only be used when diffing "
5308 "a work tree");
5309 goto done;
5311 if (diff_staged) {
5312 error = got_error_msg(GOT_ERR_NOT_IMPL,
5313 "-s option can only be used when diffing "
5314 "a work tree");
5315 goto done;
5319 error = apply_unveil(got_repo_get_path(repo), 1,
5320 worktree ? got_worktree_get_root_path(worktree) : NULL);
5321 if (error)
5322 goto done;
5324 if ((!force_path && argc == 2) || ncommit_args > 0) {
5325 int obj_type = (ncommit_args > 0 ?
5326 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5327 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5328 NULL);
5329 if (error)
5330 goto done;
5331 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5332 const char *arg;
5333 char *keyword_idstr = NULL;
5335 if (ncommit_args > 0)
5336 arg = commit_args[i];
5337 else
5338 arg = argv[i];
5340 error = got_keyword_to_idstr(&keyword_idstr, arg,
5341 repo, worktree);
5342 if (error != NULL)
5343 goto done;
5344 if (keyword_idstr != NULL)
5345 arg = keyword_idstr;
5347 error = got_repo_match_object_id(&ids[i], &labels[i],
5348 arg, obj_type, &refs, repo);
5349 free(keyword_idstr);
5350 if (error) {
5351 if (error->code != GOT_ERR_NOT_REF &&
5352 error->code != GOT_ERR_NO_OBJ)
5353 goto done;
5354 if (ncommit_args > 0)
5355 goto done;
5356 error = NULL;
5357 break;
5362 f1 = got_opentemp();
5363 if (f1 == NULL) {
5364 error = got_error_from_errno("got_opentemp");
5365 goto done;
5368 f2 = got_opentemp();
5369 if (f2 == NULL) {
5370 error = got_error_from_errno("got_opentemp");
5371 goto done;
5374 outfile = got_opentemp();
5375 if (outfile == NULL) {
5376 error = got_error_from_errno("got_opentemp");
5377 goto done;
5380 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5381 struct print_diff_arg arg;
5382 char *id_str;
5384 if (worktree == NULL) {
5385 if (argc == 2 && ids[0] == NULL) {
5386 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5387 goto done;
5388 } else if (argc == 2 && ids[1] == NULL) {
5389 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5390 goto done;
5391 } else if (argc > 0) {
5392 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5393 "%s", "specified paths cannot be resolved");
5394 goto done;
5395 } else {
5396 error = got_error(GOT_ERR_NOT_WORKTREE);
5397 goto done;
5401 error = get_worktree_paths_from_argv(&paths, argc, argv,
5402 worktree);
5403 if (error)
5404 goto done;
5406 error = got_object_id_str(&id_str,
5407 got_worktree_get_base_commit_id(worktree));
5408 if (error)
5409 goto done;
5410 arg.repo = repo;
5411 arg.worktree = worktree;
5412 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5413 arg.diff_context = diff_context;
5414 arg.id_str = id_str;
5415 arg.header_shown = 0;
5416 arg.diff_staged = diff_staged;
5417 arg.ignore_whitespace = ignore_whitespace;
5418 arg.force_text_diff = force_text_diff;
5419 arg.diffstat = show_diffstat ? &dsa : NULL;
5420 arg.f1 = f1;
5421 arg.f2 = f2;
5422 arg.outfile = outfile;
5424 error = got_worktree_status(worktree, &paths, repo, 0,
5425 print_diff, &arg, check_cancelled, NULL);
5426 free(id_str);
5427 if (error)
5428 goto done;
5430 if (show_diffstat && dsa.nfiles > 0) {
5431 char *header;
5433 if (asprintf(&header, "diffstat %s%s",
5434 diff_staged ? "-s " : "",
5435 got_worktree_get_root_path(worktree)) == -1) {
5436 error = got_error_from_errno("asprintf");
5437 goto done;
5440 error = print_diffstat(&dsa, header);
5441 free(header);
5442 if (error)
5443 goto done;
5446 error = printfile(outfile);
5447 goto done;
5450 if (ncommit_args == 1) {
5451 struct got_commit_object *commit;
5452 error = got_object_open_as_commit(&commit, repo, ids[0]);
5453 if (error)
5454 goto done;
5456 labels[1] = labels[0];
5457 ids[1] = ids[0];
5458 if (got_object_commit_get_nparents(commit) > 0) {
5459 const struct got_object_id_queue *pids;
5460 struct got_object_qid *pid;
5461 pids = got_object_commit_get_parent_ids(commit);
5462 pid = STAILQ_FIRST(pids);
5463 ids[0] = got_object_id_dup(&pid->id);
5464 if (ids[0] == NULL) {
5465 error = got_error_from_errno(
5466 "got_object_id_dup");
5467 got_object_commit_close(commit);
5468 goto done;
5470 error = got_object_id_str(&labels[0], ids[0]);
5471 if (error) {
5472 got_object_commit_close(commit);
5473 goto done;
5475 } else {
5476 ids[0] = NULL;
5477 labels[0] = strdup("/dev/null");
5478 if (labels[0] == NULL) {
5479 error = got_error_from_errno("strdup");
5480 got_object_commit_close(commit);
5481 goto done;
5485 got_object_commit_close(commit);
5488 if (ncommit_args == 0 && argc > 2) {
5489 error = got_error_msg(GOT_ERR_BAD_PATH,
5490 "path arguments cannot be used when diffing two objects");
5491 goto done;
5494 if (ids[0]) {
5495 error = got_object_get_type(&type1, repo, ids[0]);
5496 if (error)
5497 goto done;
5500 error = got_object_get_type(&type2, repo, ids[1]);
5501 if (error)
5502 goto done;
5503 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5504 error = got_error(GOT_ERR_OBJ_TYPE);
5505 goto done;
5507 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5508 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5509 "path arguments cannot be used when diffing blobs");
5510 goto done;
5513 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5514 char *in_repo_path;
5515 struct got_pathlist_entry *new;
5516 if (worktree) {
5517 const char *prefix;
5518 char *p;
5519 error = got_worktree_resolve_path(&p, worktree,
5520 argv[i]);
5521 if (error)
5522 goto done;
5523 prefix = got_worktree_get_path_prefix(worktree);
5524 while (prefix[0] == '/')
5525 prefix++;
5526 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5527 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5528 p) == -1) {
5529 error = got_error_from_errno("asprintf");
5530 free(p);
5531 goto done;
5533 free(p);
5534 } else {
5535 char *mapped_path, *s;
5536 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5537 if (error)
5538 goto done;
5539 s = mapped_path;
5540 while (s[0] == '/')
5541 s++;
5542 in_repo_path = strdup(s);
5543 if (in_repo_path == NULL) {
5544 error = got_error_from_errno("asprintf");
5545 free(mapped_path);
5546 goto done;
5548 free(mapped_path);
5551 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5552 if (error || new == NULL /* duplicate */)
5553 free(in_repo_path);
5554 if (error)
5555 goto done;
5558 if (worktree) {
5559 /* Release work tree lock. */
5560 got_worktree_close(worktree);
5561 worktree = NULL;
5564 fd1 = got_opentempfd();
5565 if (fd1 == -1) {
5566 error = got_error_from_errno("got_opentempfd");
5567 goto done;
5570 fd2 = got_opentempfd();
5571 if (fd2 == -1) {
5572 error = got_error_from_errno("got_opentempfd");
5573 goto done;
5576 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5577 case GOT_OBJ_TYPE_BLOB:
5578 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5579 fd1, fd2, ids[0], ids[1], NULL, NULL,
5580 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5581 ignore_whitespace, force_text_diff,
5582 show_diffstat ? &dsa : NULL, repo, outfile);
5583 break;
5584 case GOT_OBJ_TYPE_TREE:
5585 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5586 ids[0], ids[1], &paths, "", "",
5587 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5588 ignore_whitespace, force_text_diff,
5589 show_diffstat ? &dsa : NULL, repo, outfile);
5590 break;
5591 case GOT_OBJ_TYPE_COMMIT:
5592 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5593 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5594 fd1, fd2, ids[0], ids[1], &paths,
5595 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5596 ignore_whitespace, force_text_diff,
5597 show_diffstat ? &dsa : NULL, repo, outfile);
5598 break;
5599 default:
5600 error = got_error(GOT_ERR_OBJ_TYPE);
5602 if (error)
5603 goto done;
5605 if (show_diffstat && dsa.nfiles > 0) {
5606 char *header = NULL;
5608 if (asprintf(&header, "diffstat %s %s",
5609 labels[0], labels[1]) == -1) {
5610 error = got_error_from_errno("asprintf");
5611 goto done;
5614 error = print_diffstat(&dsa, header);
5615 free(header);
5616 if (error)
5617 goto done;
5620 error = printfile(outfile);
5622 done:
5623 free(labels[0]);
5624 free(labels[1]);
5625 free(ids[0]);
5626 free(ids[1]);
5627 if (worktree)
5628 got_worktree_close(worktree);
5629 if (repo) {
5630 const struct got_error *close_err = got_repo_close(repo);
5631 if (error == NULL)
5632 error = close_err;
5634 if (pack_fds) {
5635 const struct got_error *pack_err =
5636 got_repo_pack_fds_close(pack_fds);
5637 if (error == NULL)
5638 error = pack_err;
5640 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5641 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5642 got_ref_list_free(&refs);
5643 if (outfile && fclose(outfile) == EOF && error == NULL)
5644 error = got_error_from_errno("fclose");
5645 if (f1 && fclose(f1) == EOF && error == NULL)
5646 error = got_error_from_errno("fclose");
5647 if (f2 && fclose(f2) == EOF && error == NULL)
5648 error = got_error_from_errno("fclose");
5649 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5650 error = got_error_from_errno("close");
5651 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5652 error = got_error_from_errno("close");
5653 return error;
5656 __dead static void
5657 usage_blame(void)
5659 fprintf(stderr,
5660 "usage: %s blame [-c commit] [-r repository-path] path\n",
5661 getprogname());
5662 exit(1);
5665 struct blame_line {
5666 int annotated;
5667 char *id_str;
5668 char *committer;
5669 char datebuf[11]; /* YYYY-MM-DD + NUL */
5672 struct blame_cb_args {
5673 struct blame_line *lines;
5674 int nlines;
5675 int nlines_prec;
5676 int lineno_cur;
5677 off_t *line_offsets;
5678 FILE *f;
5679 struct got_repository *repo;
5682 static const struct got_error *
5683 blame_cb(void *arg, int nlines, int lineno,
5684 struct got_commit_object *commit, struct got_object_id *id)
5686 const struct got_error *err = NULL;
5687 struct blame_cb_args *a = arg;
5688 struct blame_line *bline;
5689 char *line = NULL;
5690 size_t linesize = 0;
5691 off_t offset;
5692 struct tm tm;
5693 time_t committer_time;
5695 if (nlines != a->nlines ||
5696 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5697 return got_error(GOT_ERR_RANGE);
5699 if (sigint_received)
5700 return got_error(GOT_ERR_ITER_COMPLETED);
5702 if (lineno == -1)
5703 return NULL; /* no change in this commit */
5705 /* Annotate this line. */
5706 bline = &a->lines[lineno - 1];
5707 if (bline->annotated)
5708 return NULL;
5709 err = got_object_id_str(&bline->id_str, id);
5710 if (err)
5711 return err;
5713 bline->committer = strdup(got_object_commit_get_committer(commit));
5714 if (bline->committer == NULL) {
5715 err = got_error_from_errno("strdup");
5716 goto done;
5719 committer_time = got_object_commit_get_committer_time(commit);
5720 if (gmtime_r(&committer_time, &tm) == NULL)
5721 return got_error_from_errno("gmtime_r");
5722 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5723 &tm) == 0) {
5724 err = got_error(GOT_ERR_NO_SPACE);
5725 goto done;
5727 bline->annotated = 1;
5729 /* Print lines annotated so far. */
5730 bline = &a->lines[a->lineno_cur - 1];
5731 if (!bline->annotated)
5732 goto done;
5734 offset = a->line_offsets[a->lineno_cur - 1];
5735 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5736 err = got_error_from_errno("fseeko");
5737 goto done;
5740 while (a->lineno_cur <= a->nlines && bline->annotated) {
5741 char *smallerthan, *at, *nl, *committer;
5742 size_t len;
5744 if (getline(&line, &linesize, a->f) == -1) {
5745 if (ferror(a->f))
5746 err = got_error_from_errno("getline");
5747 break;
5750 committer = bline->committer;
5751 smallerthan = strchr(committer, '<');
5752 if (smallerthan && smallerthan[1] != '\0')
5753 committer = smallerthan + 1;
5754 at = strchr(committer, '@');
5755 if (at)
5756 *at = '\0';
5757 len = strlen(committer);
5758 if (len >= 9)
5759 committer[8] = '\0';
5761 nl = strchr(line, '\n');
5762 if (nl)
5763 *nl = '\0';
5764 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5765 bline->id_str, bline->datebuf, committer, line);
5767 a->lineno_cur++;
5768 bline = &a->lines[a->lineno_cur - 1];
5770 done:
5771 free(line);
5772 return err;
5775 static const struct got_error *
5776 cmd_blame(int argc, char *argv[])
5778 const struct got_error *error;
5779 struct got_repository *repo = NULL;
5780 struct got_worktree *worktree = NULL;
5781 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5782 char *link_target = NULL;
5783 struct got_object_id *obj_id = NULL;
5784 struct got_object_id *commit_id = NULL;
5785 struct got_commit_object *commit = NULL;
5786 struct got_blob_object *blob = NULL;
5787 char *commit_id_str = NULL, *keyword_idstr = NULL;
5788 struct blame_cb_args bca;
5789 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5790 off_t filesize;
5791 int *pack_fds = NULL;
5792 FILE *f1 = NULL, *f2 = NULL;
5794 fd1 = got_opentempfd();
5795 if (fd1 == -1)
5796 return got_error_from_errno("got_opentempfd");
5798 memset(&bca, 0, sizeof(bca));
5800 #ifndef PROFILE
5801 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5802 NULL) == -1)
5803 err(1, "pledge");
5804 #endif
5806 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5807 switch (ch) {
5808 case 'c':
5809 commit_id_str = optarg;
5810 break;
5811 case 'r':
5812 repo_path = realpath(optarg, NULL);
5813 if (repo_path == NULL)
5814 return got_error_from_errno2("realpath",
5815 optarg);
5816 got_path_strip_trailing_slashes(repo_path);
5817 break;
5818 default:
5819 usage_blame();
5820 /* NOTREACHED */
5824 argc -= optind;
5825 argv += optind;
5827 if (argc == 1)
5828 path = argv[0];
5829 else
5830 usage_blame();
5832 cwd = getcwd(NULL, 0);
5833 if (cwd == NULL) {
5834 error = got_error_from_errno("getcwd");
5835 goto done;
5838 error = got_repo_pack_fds_open(&pack_fds);
5839 if (error != NULL)
5840 goto done;
5842 if (repo_path == NULL) {
5843 error = got_worktree_open(&worktree, cwd,
5844 GOT_WORKTREE_GOT_DIR);
5845 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5846 goto done;
5847 else
5848 error = NULL;
5849 if (worktree) {
5850 repo_path =
5851 strdup(got_worktree_get_repo_path(worktree));
5852 if (repo_path == NULL) {
5853 error = got_error_from_errno("strdup");
5854 if (error)
5855 goto done;
5857 } else {
5858 repo_path = strdup(cwd);
5859 if (repo_path == NULL) {
5860 error = got_error_from_errno("strdup");
5861 goto done;
5866 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5867 if (error != NULL)
5868 goto done;
5870 if (worktree) {
5871 const char *prefix = got_worktree_get_path_prefix(worktree);
5872 char *p;
5874 error = got_worktree_resolve_path(&p, worktree, path);
5875 if (error)
5876 goto done;
5877 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5878 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5879 p) == -1) {
5880 error = got_error_from_errno("asprintf");
5881 free(p);
5882 goto done;
5884 free(p);
5885 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5886 } else {
5887 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5888 if (error)
5889 goto done;
5890 error = got_repo_map_path(&in_repo_path, repo, path);
5892 if (error)
5893 goto done;
5895 if (commit_id_str == NULL) {
5896 struct got_reference *head_ref;
5897 error = got_ref_open(&head_ref, repo, worktree ?
5898 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5899 if (error != NULL)
5900 goto done;
5901 error = got_ref_resolve(&commit_id, repo, head_ref);
5902 got_ref_close(head_ref);
5903 if (error != NULL)
5904 goto done;
5905 } else {
5906 struct got_reflist_head refs;
5908 TAILQ_INIT(&refs);
5909 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5910 NULL);
5911 if (error)
5912 goto done;
5914 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5915 repo, worktree);
5916 if (error != NULL)
5917 goto done;
5918 if (keyword_idstr != NULL)
5919 commit_id_str = keyword_idstr;
5921 error = got_repo_match_object_id(&commit_id, NULL,
5922 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5923 got_ref_list_free(&refs);
5924 if (error)
5925 goto done;
5928 if (worktree) {
5929 /* Release work tree lock. */
5930 got_worktree_close(worktree);
5931 worktree = NULL;
5934 error = got_object_open_as_commit(&commit, repo, commit_id);
5935 if (error)
5936 goto done;
5938 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5939 commit, repo);
5940 if (error)
5941 goto done;
5943 error = got_object_id_by_path(&obj_id, repo, commit,
5944 link_target ? link_target : in_repo_path);
5945 if (error)
5946 goto done;
5948 error = got_object_get_type(&obj_type, repo, obj_id);
5949 if (error)
5950 goto done;
5952 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5953 error = got_error_path(link_target ? link_target : in_repo_path,
5954 GOT_ERR_OBJ_TYPE);
5955 goto done;
5958 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5959 if (error)
5960 goto done;
5961 bca.f = got_opentemp();
5962 if (bca.f == NULL) {
5963 error = got_error_from_errno("got_opentemp");
5964 goto done;
5966 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5967 &bca.line_offsets, bca.f, blob);
5968 if (error || bca.nlines == 0)
5969 goto done;
5971 /* Don't include \n at EOF in the blame line count. */
5972 if (bca.line_offsets[bca.nlines - 1] == filesize)
5973 bca.nlines--;
5975 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5976 if (bca.lines == NULL) {
5977 error = got_error_from_errno("calloc");
5978 goto done;
5980 bca.lineno_cur = 1;
5981 bca.nlines_prec = 0;
5982 i = bca.nlines;
5983 while (i > 0) {
5984 i /= 10;
5985 bca.nlines_prec++;
5987 bca.repo = repo;
5989 fd2 = got_opentempfd();
5990 if (fd2 == -1) {
5991 error = got_error_from_errno("got_opentempfd");
5992 goto done;
5994 fd3 = got_opentempfd();
5995 if (fd3 == -1) {
5996 error = got_error_from_errno("got_opentempfd");
5997 goto done;
5999 f1 = got_opentemp();
6000 if (f1 == NULL) {
6001 error = got_error_from_errno("got_opentemp");
6002 goto done;
6004 f2 = got_opentemp();
6005 if (f2 == NULL) {
6006 error = got_error_from_errno("got_opentemp");
6007 goto done;
6009 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6010 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6011 check_cancelled, NULL, fd2, fd3, f1, f2);
6012 done:
6013 free(keyword_idstr);
6014 free(in_repo_path);
6015 free(link_target);
6016 free(repo_path);
6017 free(cwd);
6018 free(commit_id);
6019 free(obj_id);
6020 if (commit)
6021 got_object_commit_close(commit);
6023 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6024 error = got_error_from_errno("close");
6025 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6026 error = got_error_from_errno("close");
6027 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6028 error = got_error_from_errno("close");
6029 if (f1 && fclose(f1) == EOF && error == NULL)
6030 error = got_error_from_errno("fclose");
6031 if (f2 && fclose(f2) == EOF && error == NULL)
6032 error = got_error_from_errno("fclose");
6034 if (blob)
6035 got_object_blob_close(blob);
6036 if (worktree)
6037 got_worktree_close(worktree);
6038 if (repo) {
6039 const struct got_error *close_err = got_repo_close(repo);
6040 if (error == NULL)
6041 error = close_err;
6043 if (pack_fds) {
6044 const struct got_error *pack_err =
6045 got_repo_pack_fds_close(pack_fds);
6046 if (error == NULL)
6047 error = pack_err;
6049 if (bca.lines) {
6050 for (i = 0; i < bca.nlines; i++) {
6051 struct blame_line *bline = &bca.lines[i];
6052 free(bline->id_str);
6053 free(bline->committer);
6055 free(bca.lines);
6057 free(bca.line_offsets);
6058 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6059 error = got_error_from_errno("fclose");
6060 return error;
6063 __dead static void
6064 usage_tree(void)
6066 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6067 "[path]\n", getprogname());
6068 exit(1);
6071 static const struct got_error *
6072 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6073 const char *root_path, struct got_repository *repo)
6075 const struct got_error *err = NULL;
6076 int is_root_path = (strcmp(path, root_path) == 0);
6077 const char *modestr = "";
6078 mode_t mode = got_tree_entry_get_mode(te);
6079 char *link_target = NULL;
6081 path += strlen(root_path);
6082 while (path[0] == '/')
6083 path++;
6085 if (got_object_tree_entry_is_submodule(te))
6086 modestr = "$";
6087 else if (S_ISLNK(mode)) {
6088 int i;
6090 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6091 if (err)
6092 return err;
6093 for (i = 0; link_target[i] != '\0'; i++) {
6094 if (!isprint((unsigned char)link_target[i]))
6095 link_target[i] = '?';
6098 modestr = "@";
6100 else if (S_ISDIR(mode))
6101 modestr = "/";
6102 else if (mode & S_IXUSR)
6103 modestr = "*";
6105 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6106 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6107 link_target ? " -> ": "", link_target ? link_target : "");
6109 free(link_target);
6110 return NULL;
6113 static const struct got_error *
6114 print_tree(const char *path, struct got_commit_object *commit,
6115 int show_ids, int recurse, const char *root_path,
6116 struct got_repository *repo)
6118 const struct got_error *err = NULL;
6119 struct got_object_id *tree_id = NULL;
6120 struct got_tree_object *tree = NULL;
6121 int nentries, i;
6123 err = got_object_id_by_path(&tree_id, repo, commit, path);
6124 if (err)
6125 goto done;
6127 err = got_object_open_as_tree(&tree, repo, tree_id);
6128 if (err)
6129 goto done;
6130 nentries = got_object_tree_get_nentries(tree);
6131 for (i = 0; i < nentries; i++) {
6132 struct got_tree_entry *te;
6133 char *id = NULL;
6135 if (sigint_received || sigpipe_received)
6136 break;
6138 te = got_object_tree_get_entry(tree, i);
6139 if (show_ids) {
6140 char *id_str;
6141 err = got_object_id_str(&id_str,
6142 got_tree_entry_get_id(te));
6143 if (err)
6144 goto done;
6145 if (asprintf(&id, "%s ", id_str) == -1) {
6146 err = got_error_from_errno("asprintf");
6147 free(id_str);
6148 goto done;
6150 free(id_str);
6152 err = print_entry(te, id, path, root_path, repo);
6153 free(id);
6154 if (err)
6155 goto done;
6157 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6158 char *child_path;
6159 if (asprintf(&child_path, "%s%s%s", path,
6160 path[0] == '/' && path[1] == '\0' ? "" : "/",
6161 got_tree_entry_get_name(te)) == -1) {
6162 err = got_error_from_errno("asprintf");
6163 goto done;
6165 err = print_tree(child_path, commit, show_ids, 1,
6166 root_path, repo);
6167 free(child_path);
6168 if (err)
6169 goto done;
6172 done:
6173 if (tree)
6174 got_object_tree_close(tree);
6175 free(tree_id);
6176 return err;
6179 static const struct got_error *
6180 cmd_tree(int argc, char *argv[])
6182 const struct got_error *error;
6183 struct got_repository *repo = NULL;
6184 struct got_worktree *worktree = NULL;
6185 const char *path, *refname = NULL;
6186 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6187 struct got_object_id *commit_id = NULL;
6188 struct got_commit_object *commit = NULL;
6189 char *commit_id_str = NULL, *keyword_idstr = NULL;
6190 int show_ids = 0, recurse = 0;
6191 int ch;
6192 int *pack_fds = NULL;
6194 #ifndef PROFILE
6195 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6196 NULL) == -1)
6197 err(1, "pledge");
6198 #endif
6200 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6201 switch (ch) {
6202 case 'c':
6203 commit_id_str = optarg;
6204 break;
6205 case 'i':
6206 show_ids = 1;
6207 break;
6208 case 'R':
6209 recurse = 1;
6210 break;
6211 case 'r':
6212 repo_path = realpath(optarg, NULL);
6213 if (repo_path == NULL)
6214 return got_error_from_errno2("realpath",
6215 optarg);
6216 got_path_strip_trailing_slashes(repo_path);
6217 break;
6218 default:
6219 usage_tree();
6220 /* NOTREACHED */
6224 argc -= optind;
6225 argv += optind;
6227 if (argc == 1)
6228 path = argv[0];
6229 else if (argc > 1)
6230 usage_tree();
6231 else
6232 path = NULL;
6234 cwd = getcwd(NULL, 0);
6235 if (cwd == NULL) {
6236 error = got_error_from_errno("getcwd");
6237 goto done;
6240 error = got_repo_pack_fds_open(&pack_fds);
6241 if (error != NULL)
6242 goto done;
6244 if (repo_path == NULL) {
6245 error = got_worktree_open(&worktree, cwd,
6246 GOT_WORKTREE_GOT_DIR);
6247 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6248 goto done;
6249 else
6250 error = NULL;
6251 if (worktree) {
6252 repo_path =
6253 strdup(got_worktree_get_repo_path(worktree));
6254 if (repo_path == NULL)
6255 error = got_error_from_errno("strdup");
6256 if (error)
6257 goto done;
6258 } else {
6259 repo_path = strdup(cwd);
6260 if (repo_path == NULL) {
6261 error = got_error_from_errno("strdup");
6262 goto done;
6267 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6268 if (error != NULL)
6269 goto done;
6271 if (worktree) {
6272 const char *prefix = got_worktree_get_path_prefix(worktree);
6273 char *p;
6275 if (path == NULL || got_path_is_root_dir(path))
6276 path = "";
6277 error = got_worktree_resolve_path(&p, worktree, path);
6278 if (error)
6279 goto done;
6280 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6281 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6282 p) == -1) {
6283 error = got_error_from_errno("asprintf");
6284 free(p);
6285 goto done;
6287 free(p);
6288 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6289 if (error)
6290 goto done;
6291 } else {
6292 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6293 if (error)
6294 goto done;
6295 if (path == NULL)
6296 path = "/";
6297 error = got_repo_map_path(&in_repo_path, repo, path);
6298 if (error != NULL)
6299 goto done;
6302 if (commit_id_str == NULL) {
6303 struct got_reference *head_ref;
6304 if (worktree)
6305 refname = got_worktree_get_head_ref_name(worktree);
6306 else
6307 refname = GOT_REF_HEAD;
6308 error = got_ref_open(&head_ref, repo, refname, 0);
6309 if (error != NULL)
6310 goto done;
6311 error = got_ref_resolve(&commit_id, repo, head_ref);
6312 got_ref_close(head_ref);
6313 if (error != NULL)
6314 goto done;
6315 } else {
6316 struct got_reflist_head refs;
6318 TAILQ_INIT(&refs);
6319 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6320 NULL);
6321 if (error)
6322 goto done;
6324 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6325 repo, worktree);
6326 if (error != NULL)
6327 goto done;
6328 if (keyword_idstr != NULL)
6329 commit_id_str = keyword_idstr;
6331 error = got_repo_match_object_id(&commit_id, NULL,
6332 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6333 got_ref_list_free(&refs);
6334 if (error)
6335 goto done;
6338 if (worktree) {
6339 /* Release work tree lock. */
6340 got_worktree_close(worktree);
6341 worktree = NULL;
6344 error = got_object_open_as_commit(&commit, repo, commit_id);
6345 if (error)
6346 goto done;
6348 error = print_tree(in_repo_path, commit, show_ids, recurse,
6349 in_repo_path, repo);
6350 done:
6351 free(keyword_idstr);
6352 free(in_repo_path);
6353 free(repo_path);
6354 free(cwd);
6355 free(commit_id);
6356 if (commit)
6357 got_object_commit_close(commit);
6358 if (worktree)
6359 got_worktree_close(worktree);
6360 if (repo) {
6361 const struct got_error *close_err = got_repo_close(repo);
6362 if (error == NULL)
6363 error = close_err;
6365 if (pack_fds) {
6366 const struct got_error *pack_err =
6367 got_repo_pack_fds_close(pack_fds);
6368 if (error == NULL)
6369 error = pack_err;
6371 return error;
6374 __dead static void
6375 usage_status(void)
6377 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6378 "[-s status-codes] [path ...]\n", getprogname());
6379 exit(1);
6382 struct got_status_arg {
6383 char *status_codes;
6384 int suppress;
6387 static const struct got_error *
6388 print_status(void *arg, unsigned char status, unsigned char staged_status,
6389 const char *path, struct got_object_id *blob_id,
6390 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6391 int dirfd, const char *de_name)
6393 struct got_status_arg *st = arg;
6395 if (status == staged_status && (status == GOT_STATUS_DELETE))
6396 status = GOT_STATUS_NO_CHANGE;
6397 if (st != NULL && st->status_codes) {
6398 size_t ncodes = strlen(st->status_codes);
6399 int i, j = 0;
6401 for (i = 0; i < ncodes ; i++) {
6402 if (st->suppress) {
6403 if (status == st->status_codes[i] ||
6404 staged_status == st->status_codes[i]) {
6405 j++;
6406 continue;
6408 } else {
6409 if (status == st->status_codes[i] ||
6410 staged_status == st->status_codes[i])
6411 break;
6415 if (st->suppress && j == 0)
6416 goto print;
6418 if (i == ncodes)
6419 return NULL;
6421 print:
6422 printf("%c%c %s\n", status, staged_status, path);
6423 return NULL;
6426 static const struct got_error *
6427 cmd_status(int argc, char *argv[])
6429 const struct got_error *close_err, *error = NULL;
6430 struct got_repository *repo = NULL;
6431 struct got_worktree *worktree = NULL;
6432 struct got_status_arg st;
6433 char *cwd = NULL;
6434 struct got_pathlist_head paths;
6435 int ch, i, no_ignores = 0;
6436 int *pack_fds = NULL;
6438 TAILQ_INIT(&paths);
6440 memset(&st, 0, sizeof(st));
6441 st.status_codes = NULL;
6442 st.suppress = 0;
6444 #ifndef PROFILE
6445 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6446 NULL) == -1)
6447 err(1, "pledge");
6448 #endif
6450 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6451 switch (ch) {
6452 case 'I':
6453 no_ignores = 1;
6454 break;
6455 case 'S':
6456 if (st.status_codes != NULL && st.suppress == 0)
6457 option_conflict('S', 's');
6458 st.suppress = 1;
6459 /* fallthrough */
6460 case 's':
6461 for (i = 0; optarg[i] != '\0'; i++) {
6462 switch (optarg[i]) {
6463 case GOT_STATUS_MODIFY:
6464 case GOT_STATUS_ADD:
6465 case GOT_STATUS_DELETE:
6466 case GOT_STATUS_CONFLICT:
6467 case GOT_STATUS_MISSING:
6468 case GOT_STATUS_OBSTRUCTED:
6469 case GOT_STATUS_UNVERSIONED:
6470 case GOT_STATUS_MODE_CHANGE:
6471 case GOT_STATUS_NONEXISTENT:
6472 break;
6473 default:
6474 errx(1, "invalid status code '%c'",
6475 optarg[i]);
6478 if (ch == 's' && st.suppress)
6479 option_conflict('s', 'S');
6480 st.status_codes = optarg;
6481 break;
6482 default:
6483 usage_status();
6484 /* NOTREACHED */
6488 argc -= optind;
6489 argv += optind;
6491 cwd = getcwd(NULL, 0);
6492 if (cwd == NULL) {
6493 error = got_error_from_errno("getcwd");
6494 goto done;
6497 error = got_repo_pack_fds_open(&pack_fds);
6498 if (error != NULL)
6499 goto done;
6501 error = got_worktree_open(&worktree, cwd,
6502 GOT_WORKTREE_GOT_DIR);
6503 if (error) {
6504 if (error->code == GOT_ERR_NOT_WORKTREE)
6505 error = wrap_not_worktree_error(error, "status", cwd);
6506 goto done;
6509 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6510 NULL, pack_fds);
6511 if (error != NULL)
6512 goto done;
6514 error = apply_unveil(got_repo_get_path(repo), 1,
6515 got_worktree_get_root_path(worktree));
6516 if (error)
6517 goto done;
6519 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6520 if (error)
6521 goto done;
6523 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6524 print_status, &st, check_cancelled, NULL);
6525 done:
6526 if (pack_fds) {
6527 const struct got_error *pack_err =
6528 got_repo_pack_fds_close(pack_fds);
6529 if (error == NULL)
6530 error = pack_err;
6532 if (repo) {
6533 close_err = got_repo_close(repo);
6534 if (error == NULL)
6535 error = close_err;
6537 if (worktree != NULL) {
6538 close_err = got_worktree_close(worktree);
6539 if (error == NULL)
6540 error = close_err;
6543 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6544 free(cwd);
6545 return error;
6548 __dead static void
6549 usage_ref(void)
6551 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6552 "[-s reference] [name]\n", getprogname());
6553 exit(1);
6556 static const struct got_error *
6557 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6559 static const struct got_error *err = NULL;
6560 struct got_reflist_head refs;
6561 struct got_reflist_entry *re;
6563 TAILQ_INIT(&refs);
6564 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6565 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6566 repo);
6567 if (err)
6568 return err;
6570 TAILQ_FOREACH(re, &refs, entry) {
6571 char *refstr;
6572 refstr = got_ref_to_str(re->ref);
6573 if (refstr == NULL) {
6574 err = got_error_from_errno("got_ref_to_str");
6575 break;
6577 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6578 free(refstr);
6581 got_ref_list_free(&refs);
6582 return err;
6585 static const struct got_error *
6586 delete_ref_by_name(struct got_repository *repo, const char *refname)
6588 const struct got_error *err;
6589 struct got_reference *ref;
6591 err = got_ref_open(&ref, repo, refname, 0);
6592 if (err)
6593 return err;
6595 err = delete_ref(repo, ref);
6596 got_ref_close(ref);
6597 return err;
6600 static const struct got_error *
6601 add_ref(struct got_repository *repo, const char *refname, const char *target)
6603 const struct got_error *err = NULL;
6604 struct got_object_id *id = NULL;
6605 struct got_reference *ref = NULL;
6606 struct got_reflist_head refs;
6609 * Don't let the user create a reference name with a leading '-'.
6610 * While technically a valid reference name, this case is usually
6611 * an unintended typo.
6613 if (refname[0] == '-')
6614 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6616 TAILQ_INIT(&refs);
6617 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6618 if (err)
6619 goto done;
6620 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6621 &refs, repo);
6622 got_ref_list_free(&refs);
6623 if (err)
6624 goto done;
6626 err = got_ref_alloc(&ref, refname, id);
6627 if (err)
6628 goto done;
6630 err = got_ref_write(ref, repo);
6631 done:
6632 if (ref)
6633 got_ref_close(ref);
6634 free(id);
6635 return err;
6638 static const struct got_error *
6639 add_symref(struct got_repository *repo, const char *refname, const char *target)
6641 const struct got_error *err = NULL;
6642 struct got_reference *ref = NULL;
6643 struct got_reference *target_ref = NULL;
6646 * Don't let the user create a reference name with a leading '-'.
6647 * While technically a valid reference name, this case is usually
6648 * an unintended typo.
6650 if (refname[0] == '-')
6651 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6653 err = got_ref_open(&target_ref, repo, target, 0);
6654 if (err)
6655 return err;
6657 err = got_ref_alloc_symref(&ref, refname, target_ref);
6658 if (err)
6659 goto done;
6661 err = got_ref_write(ref, repo);
6662 done:
6663 if (target_ref)
6664 got_ref_close(target_ref);
6665 if (ref)
6666 got_ref_close(ref);
6667 return err;
6670 static const struct got_error *
6671 cmd_ref(int argc, char *argv[])
6673 const struct got_error *error = NULL;
6674 struct got_repository *repo = NULL;
6675 struct got_worktree *worktree = NULL;
6676 char *cwd = NULL, *repo_path = NULL;
6677 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6678 const char *obj_arg = NULL, *symref_target= NULL;
6679 char *refname = NULL, *keyword_idstr = NULL;
6680 int *pack_fds = NULL;
6682 #ifndef PROFILE
6683 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6684 "sendfd unveil", NULL) == -1)
6685 err(1, "pledge");
6686 #endif
6688 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6689 switch (ch) {
6690 case 'c':
6691 obj_arg = optarg;
6692 break;
6693 case 'd':
6694 do_delete = 1;
6695 break;
6696 case 'l':
6697 do_list = 1;
6698 break;
6699 case 'r':
6700 repo_path = realpath(optarg, NULL);
6701 if (repo_path == NULL)
6702 return got_error_from_errno2("realpath",
6703 optarg);
6704 got_path_strip_trailing_slashes(repo_path);
6705 break;
6706 case 's':
6707 symref_target = optarg;
6708 break;
6709 case 't':
6710 sort_by_time = 1;
6711 break;
6712 default:
6713 usage_ref();
6714 /* NOTREACHED */
6718 if (obj_arg && do_list)
6719 option_conflict('c', 'l');
6720 if (obj_arg && do_delete)
6721 option_conflict('c', 'd');
6722 if (obj_arg && symref_target)
6723 option_conflict('c', 's');
6724 if (symref_target && do_delete)
6725 option_conflict('s', 'd');
6726 if (symref_target && do_list)
6727 option_conflict('s', 'l');
6728 if (do_delete && do_list)
6729 option_conflict('d', 'l');
6730 if (sort_by_time && !do_list)
6731 errx(1, "-t option requires -l option");
6733 argc -= optind;
6734 argv += optind;
6736 if (do_list) {
6737 if (argc != 0 && argc != 1)
6738 usage_ref();
6739 if (argc == 1) {
6740 refname = strdup(argv[0]);
6741 if (refname == NULL) {
6742 error = got_error_from_errno("strdup");
6743 goto done;
6746 } else {
6747 if (argc != 1)
6748 usage_ref();
6749 refname = strdup(argv[0]);
6750 if (refname == NULL) {
6751 error = got_error_from_errno("strdup");
6752 goto done;
6756 if (refname)
6757 got_path_strip_trailing_slashes(refname);
6759 cwd = getcwd(NULL, 0);
6760 if (cwd == NULL) {
6761 error = got_error_from_errno("getcwd");
6762 goto done;
6765 error = got_repo_pack_fds_open(&pack_fds);
6766 if (error != NULL)
6767 goto done;
6769 if (repo_path == NULL) {
6770 error = got_worktree_open(&worktree, cwd,
6771 GOT_WORKTREE_GOT_DIR);
6772 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6773 goto done;
6774 else
6775 error = NULL;
6776 if (worktree) {
6777 repo_path =
6778 strdup(got_worktree_get_repo_path(worktree));
6779 if (repo_path == NULL)
6780 error = got_error_from_errno("strdup");
6781 if (error)
6782 goto done;
6783 } else {
6784 repo_path = strdup(cwd);
6785 if (repo_path == NULL) {
6786 error = got_error_from_errno("strdup");
6787 goto done;
6792 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6793 if (error != NULL)
6794 goto done;
6796 #ifndef PROFILE
6797 if (do_list) {
6798 /* Remove "cpath" promise. */
6799 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6800 NULL) == -1)
6801 err(1, "pledge");
6803 #endif
6805 error = apply_unveil(got_repo_get_path(repo), do_list,
6806 worktree ? got_worktree_get_root_path(worktree) : NULL);
6807 if (error)
6808 goto done;
6810 if (do_list)
6811 error = list_refs(repo, refname, sort_by_time);
6812 else if (do_delete)
6813 error = delete_ref_by_name(repo, refname);
6814 else if (symref_target)
6815 error = add_symref(repo, refname, symref_target);
6816 else {
6817 if (obj_arg == NULL)
6818 usage_ref();
6820 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6821 repo, worktree);
6822 if (error != NULL)
6823 goto done;
6824 if (keyword_idstr != NULL)
6825 obj_arg = keyword_idstr;
6827 error = add_ref(repo, refname, obj_arg);
6829 done:
6830 free(refname);
6831 if (repo) {
6832 const struct got_error *close_err = got_repo_close(repo);
6833 if (error == NULL)
6834 error = close_err;
6836 if (worktree)
6837 got_worktree_close(worktree);
6838 if (pack_fds) {
6839 const struct got_error *pack_err =
6840 got_repo_pack_fds_close(pack_fds);
6841 if (error == NULL)
6842 error = pack_err;
6844 free(cwd);
6845 free(repo_path);
6846 free(keyword_idstr);
6847 return error;
6850 __dead static void
6851 usage_branch(void)
6853 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6854 "[-r repository-path] [name]\n", getprogname());
6855 exit(1);
6858 static const struct got_error *
6859 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6860 struct got_reference *ref)
6862 const struct got_error *err = NULL;
6863 const char *refname;
6864 char *refstr;
6865 char marker = ' ';
6867 refname = got_ref_get_name(ref);
6868 if (worktree && strcmp(refname,
6869 got_worktree_get_head_ref_name(worktree)) == 0) {
6870 err = got_worktree_get_state(&marker, repo, worktree,
6871 check_cancelled, NULL);
6872 if (err != NULL)
6873 return err;
6876 if (strncmp(refname, "refs/heads/", 11) == 0)
6877 refname += 11;
6878 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6879 refname += 18;
6880 if (strncmp(refname, "refs/remotes/", 13) == 0)
6881 refname += 13;
6883 refstr = got_ref_to_str(ref);
6884 if (refstr == NULL)
6885 return got_error_from_errno("got_ref_to_str");
6887 printf("%c %s: %s\n", marker, refname, refstr);
6888 free(refstr);
6889 return NULL;
6892 static const struct got_error *
6893 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6895 const char *refname;
6897 if (worktree == NULL)
6898 return got_error(GOT_ERR_NOT_WORKTREE);
6900 refname = got_worktree_get_head_ref_name(worktree);
6902 if (strncmp(refname, "refs/heads/", 11) == 0)
6903 refname += 11;
6904 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6905 refname += 18;
6907 printf("%s\n", refname);
6909 return NULL;
6912 static const struct got_error *
6913 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6914 int sort_by_time)
6916 static const struct got_error *err = NULL;
6917 struct got_reflist_head refs;
6918 struct got_reflist_entry *re;
6919 struct got_reference *temp_ref = NULL;
6920 int rebase_in_progress, histedit_in_progress;
6922 TAILQ_INIT(&refs);
6924 if (worktree) {
6925 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6926 worktree);
6927 if (err)
6928 return err;
6930 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6931 worktree);
6932 if (err)
6933 return err;
6935 if (rebase_in_progress || histedit_in_progress) {
6936 err = got_ref_open(&temp_ref, repo,
6937 got_worktree_get_head_ref_name(worktree), 0);
6938 if (err)
6939 return err;
6940 list_branch(repo, worktree, temp_ref);
6941 got_ref_close(temp_ref);
6945 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6946 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6947 repo);
6948 if (err)
6949 return err;
6951 TAILQ_FOREACH(re, &refs, entry)
6952 list_branch(repo, worktree, re->ref);
6954 got_ref_list_free(&refs);
6956 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6957 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6958 repo);
6959 if (err)
6960 return err;
6962 TAILQ_FOREACH(re, &refs, entry)
6963 list_branch(repo, worktree, re->ref);
6965 got_ref_list_free(&refs);
6967 return NULL;
6970 static const struct got_error *
6971 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6972 const char *branch_name)
6974 const struct got_error *err = NULL;
6975 struct got_reference *ref = NULL;
6976 char *refname, *remote_refname = NULL;
6978 if (strncmp(branch_name, "refs/", 5) == 0)
6979 branch_name += 5;
6980 if (strncmp(branch_name, "heads/", 6) == 0)
6981 branch_name += 6;
6982 else if (strncmp(branch_name, "remotes/", 8) == 0)
6983 branch_name += 8;
6985 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6986 return got_error_from_errno("asprintf");
6988 if (asprintf(&remote_refname, "refs/remotes/%s",
6989 branch_name) == -1) {
6990 err = got_error_from_errno("asprintf");
6991 goto done;
6994 err = got_ref_open(&ref, repo, refname, 0);
6995 if (err) {
6996 const struct got_error *err2;
6997 if (err->code != GOT_ERR_NOT_REF)
6998 goto done;
7000 * Keep 'err' intact such that if neither branch exists
7001 * we report "refs/heads" rather than "refs/remotes" in
7002 * our error message.
7004 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7005 if (err2)
7006 goto done;
7007 err = NULL;
7010 if (worktree &&
7011 strcmp(got_worktree_get_head_ref_name(worktree),
7012 got_ref_get_name(ref)) == 0) {
7013 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7014 "will not delete this work tree's current branch");
7015 goto done;
7018 err = delete_ref(repo, ref);
7019 done:
7020 if (ref)
7021 got_ref_close(ref);
7022 free(refname);
7023 free(remote_refname);
7024 return err;
7027 static const struct got_error *
7028 add_branch(struct got_repository *repo, const char *branch_name,
7029 struct got_object_id *base_commit_id)
7031 const struct got_error *err = NULL;
7032 struct got_reference *ref = NULL;
7033 char *refname = NULL;
7036 * Don't let the user create a branch name with a leading '-'.
7037 * While technically a valid reference name, this case is usually
7038 * an unintended typo.
7040 if (branch_name[0] == '-')
7041 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7043 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7044 branch_name += 11;
7046 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7047 err = got_error_from_errno("asprintf");
7048 goto done;
7051 err = got_ref_open(&ref, repo, refname, 0);
7052 if (err == NULL) {
7053 err = got_error(GOT_ERR_BRANCH_EXISTS);
7054 goto done;
7055 } else if (err->code != GOT_ERR_NOT_REF)
7056 goto done;
7058 err = got_ref_alloc(&ref, refname, base_commit_id);
7059 if (err)
7060 goto done;
7062 err = got_ref_write(ref, repo);
7063 done:
7064 if (ref)
7065 got_ref_close(ref);
7066 free(refname);
7067 return err;
7070 static const struct got_error *
7071 cmd_branch(int argc, char *argv[])
7073 const struct got_error *error = NULL;
7074 struct got_repository *repo = NULL;
7075 struct got_worktree *worktree = NULL;
7076 char *cwd = NULL, *repo_path = NULL;
7077 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7078 const char *delref = NULL, *commit_id_arg = NULL;
7079 struct got_reference *ref = NULL;
7080 struct got_pathlist_head paths;
7081 struct got_object_id *commit_id = NULL;
7082 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7083 int *pack_fds = NULL;
7085 TAILQ_INIT(&paths);
7087 #ifndef PROFILE
7088 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7089 "sendfd unveil", NULL) == -1)
7090 err(1, "pledge");
7091 #endif
7093 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7094 switch (ch) {
7095 case 'c':
7096 commit_id_arg = optarg;
7097 break;
7098 case 'd':
7099 delref = optarg;
7100 break;
7101 case 'l':
7102 do_list = 1;
7103 break;
7104 case 'n':
7105 do_update = 0;
7106 break;
7107 case 'r':
7108 repo_path = realpath(optarg, NULL);
7109 if (repo_path == NULL)
7110 return got_error_from_errno2("realpath",
7111 optarg);
7112 got_path_strip_trailing_slashes(repo_path);
7113 break;
7114 case 't':
7115 sort_by_time = 1;
7116 break;
7117 default:
7118 usage_branch();
7119 /* NOTREACHED */
7123 if (do_list && delref)
7124 option_conflict('l', 'd');
7125 if (sort_by_time && !do_list)
7126 errx(1, "-t option requires -l option");
7128 argc -= optind;
7129 argv += optind;
7131 if (!do_list && !delref && argc == 0)
7132 do_show = 1;
7134 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7135 errx(1, "-c option can only be used when creating a branch");
7137 if (do_list || delref) {
7138 if (argc > 0)
7139 usage_branch();
7140 } else if (!do_show && argc != 1)
7141 usage_branch();
7143 cwd = getcwd(NULL, 0);
7144 if (cwd == NULL) {
7145 error = got_error_from_errno("getcwd");
7146 goto done;
7149 error = got_repo_pack_fds_open(&pack_fds);
7150 if (error != NULL)
7151 goto done;
7153 if (repo_path == NULL) {
7154 error = got_worktree_open(&worktree, cwd,
7155 GOT_WORKTREE_GOT_DIR);
7156 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7157 goto done;
7158 else
7159 error = NULL;
7160 if (worktree) {
7161 repo_path =
7162 strdup(got_worktree_get_repo_path(worktree));
7163 if (repo_path == NULL)
7164 error = got_error_from_errno("strdup");
7165 if (error)
7166 goto done;
7167 } else {
7168 repo_path = strdup(cwd);
7169 if (repo_path == NULL) {
7170 error = got_error_from_errno("strdup");
7171 goto done;
7176 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7177 if (error != NULL)
7178 goto done;
7180 #ifndef PROFILE
7181 if (do_list || do_show) {
7182 /* Remove "cpath" promise. */
7183 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7184 NULL) == -1)
7185 err(1, "pledge");
7187 #endif
7189 error = apply_unveil(got_repo_get_path(repo), do_list,
7190 worktree ? got_worktree_get_root_path(worktree) : NULL);
7191 if (error)
7192 goto done;
7194 if (do_show)
7195 error = show_current_branch(repo, worktree);
7196 else if (do_list)
7197 error = list_branches(repo, worktree, sort_by_time);
7198 else if (delref)
7199 error = delete_branch(repo, worktree, delref);
7200 else {
7201 struct got_reflist_head refs;
7202 TAILQ_INIT(&refs);
7203 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7204 NULL);
7205 if (error)
7206 goto done;
7207 if (commit_id_arg == NULL)
7208 commit_id_arg = worktree ?
7209 got_worktree_get_head_ref_name(worktree) :
7210 GOT_REF_HEAD;
7211 else {
7212 error = got_keyword_to_idstr(&keyword_idstr,
7213 commit_id_arg, repo, worktree);
7214 if (error != NULL)
7215 goto done;
7216 if (keyword_idstr != NULL)
7217 commit_id_arg = keyword_idstr;
7219 error = got_repo_match_object_id(&commit_id, NULL,
7220 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7221 got_ref_list_free(&refs);
7222 if (error)
7223 goto done;
7224 error = add_branch(repo, argv[0], commit_id);
7225 if (error)
7226 goto done;
7227 if (worktree && do_update) {
7228 struct got_update_progress_arg upa;
7229 char *branch_refname = NULL;
7231 error = got_object_id_str(&commit_id_str, commit_id);
7232 if (error)
7233 goto done;
7234 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7235 worktree);
7236 if (error)
7237 goto done;
7238 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7239 == -1) {
7240 error = got_error_from_errno("asprintf");
7241 goto done;
7243 error = got_ref_open(&ref, repo, branch_refname, 0);
7244 free(branch_refname);
7245 if (error)
7246 goto done;
7247 error = switch_head_ref(ref, commit_id, worktree,
7248 repo);
7249 if (error)
7250 goto done;
7251 error = got_worktree_set_base_commit_id(worktree, repo,
7252 commit_id);
7253 if (error)
7254 goto done;
7255 memset(&upa, 0, sizeof(upa));
7256 error = got_worktree_checkout_files(worktree, &paths,
7257 repo, update_progress, &upa, check_cancelled,
7258 NULL);
7259 if (error)
7260 goto done;
7261 if (upa.did_something) {
7262 printf("Updated to %s: %s\n",
7263 got_worktree_get_head_ref_name(worktree),
7264 commit_id_str);
7266 print_update_progress_stats(&upa);
7269 done:
7270 free(keyword_idstr);
7271 if (ref)
7272 got_ref_close(ref);
7273 if (repo) {
7274 const struct got_error *close_err = got_repo_close(repo);
7275 if (error == NULL)
7276 error = close_err;
7278 if (worktree)
7279 got_worktree_close(worktree);
7280 if (pack_fds) {
7281 const struct got_error *pack_err =
7282 got_repo_pack_fds_close(pack_fds);
7283 if (error == NULL)
7284 error = pack_err;
7286 free(cwd);
7287 free(repo_path);
7288 free(commit_id);
7289 free(commit_id_str);
7290 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7291 return error;
7295 __dead static void
7296 usage_tag(void)
7298 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7299 "[-r repository-path] [-s signer-id] name\n", getprogname());
7300 exit(1);
7303 #if 0
7304 static const struct got_error *
7305 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7307 const struct got_error *err = NULL;
7308 struct got_reflist_entry *re, *se, *new;
7309 struct got_object_id *re_id, *se_id;
7310 struct got_tag_object *re_tag, *se_tag;
7311 time_t re_time, se_time;
7313 STAILQ_FOREACH(re, tags, entry) {
7314 se = STAILQ_FIRST(sorted);
7315 if (se == NULL) {
7316 err = got_reflist_entry_dup(&new, re);
7317 if (err)
7318 return err;
7319 STAILQ_INSERT_HEAD(sorted, new, entry);
7320 continue;
7321 } else {
7322 err = got_ref_resolve(&re_id, repo, re->ref);
7323 if (err)
7324 break;
7325 err = got_object_open_as_tag(&re_tag, repo, re_id);
7326 free(re_id);
7327 if (err)
7328 break;
7329 re_time = got_object_tag_get_tagger_time(re_tag);
7330 got_object_tag_close(re_tag);
7333 while (se) {
7334 err = got_ref_resolve(&se_id, repo, re->ref);
7335 if (err)
7336 break;
7337 err = got_object_open_as_tag(&se_tag, repo, se_id);
7338 free(se_id);
7339 if (err)
7340 break;
7341 se_time = got_object_tag_get_tagger_time(se_tag);
7342 got_object_tag_close(se_tag);
7344 if (se_time > re_time) {
7345 err = got_reflist_entry_dup(&new, re);
7346 if (err)
7347 return err;
7348 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7349 break;
7351 se = STAILQ_NEXT(se, entry);
7352 continue;
7355 done:
7356 return err;
7358 #endif
7360 static const struct got_error *
7361 get_tag_refname(char **refname, const char *tag_name)
7363 const struct got_error *err;
7365 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7366 *refname = strdup(tag_name);
7367 if (*refname == NULL)
7368 return got_error_from_errno("strdup");
7369 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7370 err = got_error_from_errno("asprintf");
7371 *refname = NULL;
7372 return err;
7375 return NULL;
7378 static const struct got_error *
7379 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7380 const char *allowed_signers, const char *revoked_signers, int verbosity)
7382 static const struct got_error *err = NULL;
7383 struct got_reflist_head refs;
7384 struct got_reflist_entry *re;
7385 char *wanted_refname = NULL;
7386 int bad_sigs = 0;
7388 TAILQ_INIT(&refs);
7390 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7391 if (err)
7392 return err;
7394 if (tag_name) {
7395 struct got_reference *ref;
7396 err = get_tag_refname(&wanted_refname, tag_name);
7397 if (err)
7398 goto done;
7399 /* Wanted tag reference should exist. */
7400 err = got_ref_open(&ref, repo, wanted_refname, 0);
7401 if (err)
7402 goto done;
7403 got_ref_close(ref);
7406 TAILQ_FOREACH(re, &refs, entry) {
7407 const char *refname;
7408 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7409 char datebuf[26];
7410 const char *tagger, *ssh_sig = NULL;
7411 char *sig_msg = NULL;
7412 time_t tagger_time;
7413 struct got_object_id *id;
7414 struct got_tag_object *tag;
7415 struct got_commit_object *commit = NULL;
7417 refname = got_ref_get_name(re->ref);
7418 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7419 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7420 continue;
7421 refname += 10;
7422 refstr = got_ref_to_str(re->ref);
7423 if (refstr == NULL) {
7424 err = got_error_from_errno("got_ref_to_str");
7425 break;
7428 err = got_ref_resolve(&id, repo, re->ref);
7429 if (err)
7430 break;
7431 err = got_object_open_as_tag(&tag, repo, id);
7432 if (err) {
7433 if (err->code != GOT_ERR_OBJ_TYPE) {
7434 free(id);
7435 break;
7437 /* "lightweight" tag */
7438 err = got_object_open_as_commit(&commit, repo, id);
7439 if (err) {
7440 free(id);
7441 break;
7443 tagger = got_object_commit_get_committer(commit);
7444 tagger_time =
7445 got_object_commit_get_committer_time(commit);
7446 err = got_object_id_str(&id_str, id);
7447 free(id);
7448 if (err)
7449 break;
7450 } else {
7451 free(id);
7452 tagger = got_object_tag_get_tagger(tag);
7453 tagger_time = got_object_tag_get_tagger_time(tag);
7454 err = got_object_id_str(&id_str,
7455 got_object_tag_get_object_id(tag));
7456 if (err)
7457 break;
7460 if (tag && verify_tags) {
7461 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7462 got_object_tag_get_message(tag));
7463 if (ssh_sig && allowed_signers == NULL) {
7464 err = got_error_msg(
7465 GOT_ERR_VERIFY_TAG_SIGNATURE,
7466 "SSH signature verification requires "
7467 "setting allowed_signers in "
7468 "got.conf(5)");
7469 break;
7473 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7474 free(refstr);
7475 printf("from: %s\n", tagger);
7476 datestr = get_datestr(&tagger_time, datebuf);
7477 if (datestr)
7478 printf("date: %s UTC\n", datestr);
7479 if (commit)
7480 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7481 else {
7482 switch (got_object_tag_get_object_type(tag)) {
7483 case GOT_OBJ_TYPE_BLOB:
7484 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7485 id_str);
7486 break;
7487 case GOT_OBJ_TYPE_TREE:
7488 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7489 id_str);
7490 break;
7491 case GOT_OBJ_TYPE_COMMIT:
7492 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7493 id_str);
7494 break;
7495 case GOT_OBJ_TYPE_TAG:
7496 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7497 id_str);
7498 break;
7499 default:
7500 break;
7503 free(id_str);
7505 if (ssh_sig) {
7506 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7507 allowed_signers, revoked_signers, verbosity);
7508 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7509 bad_sigs = 1;
7510 else if (err)
7511 break;
7512 printf("signature: %s", sig_msg);
7513 free(sig_msg);
7514 sig_msg = NULL;
7517 if (commit) {
7518 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7519 if (err)
7520 break;
7521 got_object_commit_close(commit);
7522 } else {
7523 tagmsg0 = strdup(got_object_tag_get_message(tag));
7524 got_object_tag_close(tag);
7525 if (tagmsg0 == NULL) {
7526 err = got_error_from_errno("strdup");
7527 break;
7531 tagmsg = tagmsg0;
7532 do {
7533 line = strsep(&tagmsg, "\n");
7534 if (line)
7535 printf(" %s\n", line);
7536 } while (line);
7537 free(tagmsg0);
7539 done:
7540 got_ref_list_free(&refs);
7541 free(wanted_refname);
7543 if (err == NULL && bad_sigs)
7544 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7545 return err;
7548 static const struct got_error *
7549 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7550 const char *tag_name, const char *repo_path)
7552 const struct got_error *err = NULL;
7553 char *template = NULL, *initial_content = NULL;
7554 char *editor = NULL;
7555 int initial_content_len;
7556 int fd = -1;
7558 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7559 err = got_error_from_errno("asprintf");
7560 goto done;
7563 initial_content_len = asprintf(&initial_content,
7564 "\n# tagging commit %s as %s\n",
7565 commit_id_str, tag_name);
7566 if (initial_content_len == -1) {
7567 err = got_error_from_errno("asprintf");
7568 goto done;
7571 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7572 if (err)
7573 goto done;
7575 if (write(fd, initial_content, initial_content_len) == -1) {
7576 err = got_error_from_errno2("write", *tagmsg_path);
7577 goto done;
7579 if (close(fd) == -1) {
7580 err = got_error_from_errno2("close", *tagmsg_path);
7581 goto done;
7583 fd = -1;
7585 err = get_editor(&editor);
7586 if (err)
7587 goto done;
7588 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7589 initial_content_len, 1);
7590 done:
7591 free(initial_content);
7592 free(template);
7593 free(editor);
7595 if (fd != -1 && close(fd) == -1 && err == NULL)
7596 err = got_error_from_errno2("close", *tagmsg_path);
7598 if (err) {
7599 free(*tagmsg);
7600 *tagmsg = NULL;
7602 return err;
7605 static const struct got_error *
7606 add_tag(struct got_repository *repo, const char *tagger,
7607 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7608 const char *signer_id, int verbosity)
7610 const struct got_error *err = NULL;
7611 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7612 char *label = NULL, *commit_id_str = NULL;
7613 struct got_reference *ref = NULL;
7614 char *refname = NULL, *tagmsg = NULL;
7615 char *tagmsg_path = NULL, *tag_id_str = NULL;
7616 int preserve_tagmsg = 0;
7617 struct got_reflist_head refs;
7619 TAILQ_INIT(&refs);
7622 * Don't let the user create a tag name with a leading '-'.
7623 * While technically a valid reference name, this case is usually
7624 * an unintended typo.
7626 if (tag_name[0] == '-')
7627 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7629 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7630 if (err)
7631 goto done;
7633 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7634 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7635 if (err)
7636 goto done;
7638 err = got_object_id_str(&commit_id_str, commit_id);
7639 if (err)
7640 goto done;
7642 err = get_tag_refname(&refname, tag_name);
7643 if (err)
7644 goto done;
7645 if (strncmp("refs/tags/", tag_name, 10) == 0)
7646 tag_name += 10;
7648 err = got_ref_open(&ref, repo, refname, 0);
7649 if (err == NULL) {
7650 err = got_error(GOT_ERR_TAG_EXISTS);
7651 goto done;
7652 } else if (err->code != GOT_ERR_NOT_REF)
7653 goto done;
7655 if (tagmsg_arg == NULL) {
7656 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7657 tag_name, got_repo_get_path(repo));
7658 if (err) {
7659 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7660 tagmsg_path != NULL)
7661 preserve_tagmsg = 1;
7662 goto done;
7664 /* Editor is done; we can now apply unveil(2) */
7665 err = got_sigs_apply_unveil();
7666 if (err)
7667 goto done;
7668 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7669 if (err)
7670 goto done;
7673 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7674 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7675 verbosity);
7676 if (err) {
7677 if (tagmsg_path)
7678 preserve_tagmsg = 1;
7679 goto done;
7682 err = got_ref_alloc(&ref, refname, tag_id);
7683 if (err) {
7684 if (tagmsg_path)
7685 preserve_tagmsg = 1;
7686 goto done;
7689 err = got_ref_write(ref, repo);
7690 if (err) {
7691 if (tagmsg_path)
7692 preserve_tagmsg = 1;
7693 goto done;
7696 err = got_object_id_str(&tag_id_str, tag_id);
7697 if (err) {
7698 if (tagmsg_path)
7699 preserve_tagmsg = 1;
7700 goto done;
7702 printf("Created tag %s\n", tag_id_str);
7703 done:
7704 if (preserve_tagmsg) {
7705 fprintf(stderr, "%s: tag message preserved in %s\n",
7706 getprogname(), tagmsg_path);
7707 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7708 err = got_error_from_errno2("unlink", tagmsg_path);
7709 free(tag_id_str);
7710 if (ref)
7711 got_ref_close(ref);
7712 free(commit_id);
7713 free(commit_id_str);
7714 free(refname);
7715 free(tagmsg);
7716 free(tagmsg_path);
7717 got_ref_list_free(&refs);
7718 return err;
7721 static const struct got_error *
7722 cmd_tag(int argc, char *argv[])
7724 const struct got_error *error = NULL;
7725 struct got_repository *repo = NULL;
7726 struct got_worktree *worktree = NULL;
7727 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7728 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7729 char *allowed_signers = NULL, *revoked_signers = NULL;
7730 const char *signer_id = NULL;
7731 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7732 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7733 int *pack_fds = NULL;
7735 #ifndef PROFILE
7736 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7737 "sendfd unveil", NULL) == -1)
7738 err(1, "pledge");
7739 #endif
7741 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7742 switch (ch) {
7743 case 'c':
7744 commit_id_arg = optarg;
7745 break;
7746 case 'l':
7747 do_list = 1;
7748 break;
7749 case 'm':
7750 tagmsg = optarg;
7751 break;
7752 case 'r':
7753 repo_path = realpath(optarg, NULL);
7754 if (repo_path == NULL) {
7755 error = got_error_from_errno2("realpath",
7756 optarg);
7757 goto done;
7759 got_path_strip_trailing_slashes(repo_path);
7760 break;
7761 case 's':
7762 signer_id = optarg;
7763 break;
7764 case 'V':
7765 verify_tags = 1;
7766 break;
7767 case 'v':
7768 if (verbosity < 0)
7769 verbosity = 0;
7770 else if (verbosity < 3)
7771 verbosity++;
7772 break;
7773 default:
7774 usage_tag();
7775 /* NOTREACHED */
7779 argc -= optind;
7780 argv += optind;
7782 if (do_list || verify_tags) {
7783 if (commit_id_arg != NULL)
7784 errx(1,
7785 "-c option can only be used when creating a tag");
7786 if (tagmsg) {
7787 if (do_list)
7788 option_conflict('l', 'm');
7789 else
7790 option_conflict('V', 'm');
7792 if (signer_id) {
7793 if (do_list)
7794 option_conflict('l', 's');
7795 else
7796 option_conflict('V', 's');
7798 if (argc > 1)
7799 usage_tag();
7800 } else if (argc != 1)
7801 usage_tag();
7803 if (argc == 1)
7804 tag_name = argv[0];
7806 cwd = getcwd(NULL, 0);
7807 if (cwd == NULL) {
7808 error = got_error_from_errno("getcwd");
7809 goto done;
7812 error = got_repo_pack_fds_open(&pack_fds);
7813 if (error != NULL)
7814 goto done;
7816 if (repo_path == NULL) {
7817 error = got_worktree_open(&worktree, cwd,
7818 GOT_WORKTREE_GOT_DIR);
7819 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7820 goto done;
7821 else
7822 error = NULL;
7823 if (worktree) {
7824 repo_path =
7825 strdup(got_worktree_get_repo_path(worktree));
7826 if (repo_path == NULL)
7827 error = got_error_from_errno("strdup");
7828 if (error)
7829 goto done;
7830 } else {
7831 repo_path = strdup(cwd);
7832 if (repo_path == NULL) {
7833 error = got_error_from_errno("strdup");
7834 goto done;
7839 if (do_list || verify_tags) {
7840 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7841 if (error != NULL)
7842 goto done;
7843 error = get_allowed_signers(&allowed_signers, repo, worktree);
7844 if (error)
7845 goto done;
7846 error = get_revoked_signers(&revoked_signers, repo, worktree);
7847 if (error)
7848 goto done;
7849 if (worktree) {
7850 /* Release work tree lock. */
7851 got_worktree_close(worktree);
7852 worktree = NULL;
7856 * Remove "cpath" promise unless needed for signature tmpfile
7857 * creation.
7859 if (verify_tags)
7860 got_sigs_apply_unveil();
7861 else {
7862 #ifndef PROFILE
7863 if (pledge("stdio rpath wpath flock proc exec sendfd "
7864 "unveil", NULL) == -1)
7865 err(1, "pledge");
7866 #endif
7868 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7869 if (error)
7870 goto done;
7871 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7872 revoked_signers, verbosity);
7873 } else {
7874 error = get_gitconfig_path(&gitconfig_path);
7875 if (error)
7876 goto done;
7877 error = got_repo_open(&repo, repo_path, gitconfig_path,
7878 pack_fds);
7879 if (error != NULL)
7880 goto done;
7882 error = get_author(&tagger, repo, worktree);
7883 if (error)
7884 goto done;
7885 if (signer_id == NULL)
7886 signer_id = get_signer_id(repo, worktree);
7888 if (tagmsg) {
7889 if (signer_id) {
7890 error = got_sigs_apply_unveil();
7891 if (error)
7892 goto done;
7894 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7895 if (error)
7896 goto done;
7899 if (commit_id_arg == NULL) {
7900 struct got_reference *head_ref;
7901 struct got_object_id *commit_id;
7902 error = got_ref_open(&head_ref, repo,
7903 worktree ? got_worktree_get_head_ref_name(worktree)
7904 : GOT_REF_HEAD, 0);
7905 if (error)
7906 goto done;
7907 error = got_ref_resolve(&commit_id, repo, head_ref);
7908 got_ref_close(head_ref);
7909 if (error)
7910 goto done;
7911 error = got_object_id_str(&commit_id_str, commit_id);
7912 free(commit_id);
7913 if (error)
7914 goto done;
7915 } else {
7916 error = got_keyword_to_idstr(&keyword_idstr,
7917 commit_id_arg, repo, worktree);
7918 if (error != NULL)
7919 goto done;
7920 commit_id_str = keyword_idstr;
7923 if (worktree) {
7924 /* Release work tree lock. */
7925 got_worktree_close(worktree);
7926 worktree = NULL;
7929 error = add_tag(repo, tagger, tag_name,
7930 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7931 signer_id, verbosity);
7933 done:
7934 if (repo) {
7935 const struct got_error *close_err = got_repo_close(repo);
7936 if (error == NULL)
7937 error = close_err;
7939 if (worktree)
7940 got_worktree_close(worktree);
7941 if (pack_fds) {
7942 const struct got_error *pack_err =
7943 got_repo_pack_fds_close(pack_fds);
7944 if (error == NULL)
7945 error = pack_err;
7947 free(cwd);
7948 free(repo_path);
7949 free(gitconfig_path);
7950 free(commit_id_str);
7951 free(tagger);
7952 free(allowed_signers);
7953 free(revoked_signers);
7954 return error;
7957 __dead static void
7958 usage_add(void)
7960 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7961 exit(1);
7964 static const struct got_error *
7965 add_progress(void *arg, unsigned char status, const char *path)
7967 while (path[0] == '/')
7968 path++;
7969 printf("%c %s\n", status, path);
7970 return NULL;
7973 static const struct got_error *
7974 cmd_add(int argc, char *argv[])
7976 const struct got_error *error = NULL;
7977 struct got_repository *repo = NULL;
7978 struct got_worktree *worktree = NULL;
7979 char *cwd = NULL;
7980 struct got_pathlist_head paths;
7981 struct got_pathlist_entry *pe;
7982 int ch, can_recurse = 0, no_ignores = 0;
7983 int *pack_fds = NULL;
7985 TAILQ_INIT(&paths);
7987 #ifndef PROFILE
7988 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7989 NULL) == -1)
7990 err(1, "pledge");
7991 #endif
7993 while ((ch = getopt(argc, argv, "IR")) != -1) {
7994 switch (ch) {
7995 case 'I':
7996 no_ignores = 1;
7997 break;
7998 case 'R':
7999 can_recurse = 1;
8000 break;
8001 default:
8002 usage_add();
8003 /* NOTREACHED */
8007 argc -= optind;
8008 argv += optind;
8010 if (argc < 1)
8011 usage_add();
8013 cwd = getcwd(NULL, 0);
8014 if (cwd == NULL) {
8015 error = got_error_from_errno("getcwd");
8016 goto done;
8019 error = got_repo_pack_fds_open(&pack_fds);
8020 if (error != NULL)
8021 goto done;
8023 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8024 if (error) {
8025 if (error->code == GOT_ERR_NOT_WORKTREE)
8026 error = wrap_not_worktree_error(error, "add", cwd);
8027 goto done;
8030 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8031 NULL, pack_fds);
8032 if (error != NULL)
8033 goto done;
8035 error = apply_unveil(got_repo_get_path(repo), 1,
8036 got_worktree_get_root_path(worktree));
8037 if (error)
8038 goto done;
8040 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8041 if (error)
8042 goto done;
8044 if (!can_recurse) {
8045 char *ondisk_path;
8046 struct stat sb;
8047 TAILQ_FOREACH(pe, &paths, entry) {
8048 if (asprintf(&ondisk_path, "%s/%s",
8049 got_worktree_get_root_path(worktree),
8050 pe->path) == -1) {
8051 error = got_error_from_errno("asprintf");
8052 goto done;
8054 if (lstat(ondisk_path, &sb) == -1) {
8055 if (errno == ENOENT) {
8056 free(ondisk_path);
8057 continue;
8059 error = got_error_from_errno2("lstat",
8060 ondisk_path);
8061 free(ondisk_path);
8062 goto done;
8064 free(ondisk_path);
8065 if (S_ISDIR(sb.st_mode)) {
8066 error = got_error_msg(GOT_ERR_BAD_PATH,
8067 "adding directories requires -R option");
8068 goto done;
8073 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8074 NULL, repo, no_ignores);
8075 done:
8076 if (repo) {
8077 const struct got_error *close_err = got_repo_close(repo);
8078 if (error == NULL)
8079 error = close_err;
8081 if (worktree)
8082 got_worktree_close(worktree);
8083 if (pack_fds) {
8084 const struct got_error *pack_err =
8085 got_repo_pack_fds_close(pack_fds);
8086 if (error == NULL)
8087 error = pack_err;
8089 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8090 free(cwd);
8091 return error;
8094 __dead static void
8095 usage_remove(void)
8097 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8098 getprogname());
8099 exit(1);
8102 static const struct got_error *
8103 print_remove_status(void *arg, unsigned char status,
8104 unsigned char staged_status, const char *path)
8106 while (path[0] == '/')
8107 path++;
8108 if (status == GOT_STATUS_NONEXISTENT)
8109 return NULL;
8110 if (status == staged_status && (status == GOT_STATUS_DELETE))
8111 status = GOT_STATUS_NO_CHANGE;
8112 printf("%c%c %s\n", status, staged_status, path);
8113 return NULL;
8116 static const struct got_error *
8117 cmd_remove(int argc, char *argv[])
8119 const struct got_error *error = NULL;
8120 struct got_worktree *worktree = NULL;
8121 struct got_repository *repo = NULL;
8122 const char *status_codes = NULL;
8123 char *cwd = NULL;
8124 struct got_pathlist_head paths;
8125 struct got_pathlist_entry *pe;
8126 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8127 int ignore_missing_paths = 0;
8128 int *pack_fds = NULL;
8130 TAILQ_INIT(&paths);
8132 #ifndef PROFILE
8133 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8134 NULL) == -1)
8135 err(1, "pledge");
8136 #endif
8138 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8139 switch (ch) {
8140 case 'f':
8141 delete_local_mods = 1;
8142 ignore_missing_paths = 1;
8143 break;
8144 case 'k':
8145 keep_on_disk = 1;
8146 break;
8147 case 'R':
8148 can_recurse = 1;
8149 break;
8150 case 's':
8151 for (i = 0; optarg[i] != '\0'; i++) {
8152 switch (optarg[i]) {
8153 case GOT_STATUS_MODIFY:
8154 delete_local_mods = 1;
8155 break;
8156 case GOT_STATUS_MISSING:
8157 ignore_missing_paths = 1;
8158 break;
8159 default:
8160 errx(1, "invalid status code '%c'",
8161 optarg[i]);
8164 status_codes = optarg;
8165 break;
8166 default:
8167 usage_remove();
8168 /* NOTREACHED */
8172 argc -= optind;
8173 argv += optind;
8175 if (argc < 1)
8176 usage_remove();
8178 cwd = getcwd(NULL, 0);
8179 if (cwd == NULL) {
8180 error = got_error_from_errno("getcwd");
8181 goto done;
8184 error = got_repo_pack_fds_open(&pack_fds);
8185 if (error != NULL)
8186 goto done;
8188 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8189 if (error) {
8190 if (error->code == GOT_ERR_NOT_WORKTREE)
8191 error = wrap_not_worktree_error(error, "remove", cwd);
8192 goto done;
8195 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8196 NULL, pack_fds);
8197 if (error)
8198 goto done;
8200 error = apply_unveil(got_repo_get_path(repo), 1,
8201 got_worktree_get_root_path(worktree));
8202 if (error)
8203 goto done;
8205 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8206 if (error)
8207 goto done;
8209 if (!can_recurse) {
8210 char *ondisk_path;
8211 struct stat sb;
8212 TAILQ_FOREACH(pe, &paths, entry) {
8213 if (asprintf(&ondisk_path, "%s/%s",
8214 got_worktree_get_root_path(worktree),
8215 pe->path) == -1) {
8216 error = got_error_from_errno("asprintf");
8217 goto done;
8219 if (lstat(ondisk_path, &sb) == -1) {
8220 if (errno == ENOENT) {
8221 free(ondisk_path);
8222 continue;
8224 error = got_error_from_errno2("lstat",
8225 ondisk_path);
8226 free(ondisk_path);
8227 goto done;
8229 free(ondisk_path);
8230 if (S_ISDIR(sb.st_mode)) {
8231 error = got_error_msg(GOT_ERR_BAD_PATH,
8232 "removing directories requires -R option");
8233 goto done;
8238 error = got_worktree_schedule_delete(worktree, &paths,
8239 delete_local_mods, status_codes, print_remove_status, NULL,
8240 repo, keep_on_disk, ignore_missing_paths);
8241 done:
8242 if (repo) {
8243 const struct got_error *close_err = got_repo_close(repo);
8244 if (error == NULL)
8245 error = close_err;
8247 if (worktree)
8248 got_worktree_close(worktree);
8249 if (pack_fds) {
8250 const struct got_error *pack_err =
8251 got_repo_pack_fds_close(pack_fds);
8252 if (error == NULL)
8253 error = pack_err;
8255 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8256 free(cwd);
8257 return error;
8260 __dead static void
8261 usage_patch(void)
8263 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8264 "[patchfile]\n", getprogname());
8265 exit(1);
8268 static const struct got_error *
8269 patch_from_stdin(int *patchfd)
8271 const struct got_error *err = NULL;
8272 ssize_t r;
8273 char buf[BUFSIZ];
8274 sig_t sighup, sigint, sigquit;
8276 *patchfd = got_opentempfd();
8277 if (*patchfd == -1)
8278 return got_error_from_errno("got_opentempfd");
8280 sighup = signal(SIGHUP, SIG_DFL);
8281 sigint = signal(SIGINT, SIG_DFL);
8282 sigquit = signal(SIGQUIT, SIG_DFL);
8284 for (;;) {
8285 r = read(0, buf, sizeof(buf));
8286 if (r == -1) {
8287 err = got_error_from_errno("read");
8288 break;
8290 if (r == 0)
8291 break;
8292 if (write(*patchfd, buf, r) == -1) {
8293 err = got_error_from_errno("write");
8294 break;
8298 signal(SIGHUP, sighup);
8299 signal(SIGINT, sigint);
8300 signal(SIGQUIT, sigquit);
8302 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8303 err = got_error_from_errno("lseek");
8305 if (err != NULL) {
8306 close(*patchfd);
8307 *patchfd = -1;
8310 return err;
8313 struct got_patch_progress_arg {
8314 int did_something;
8315 int conflicts;
8316 int rejects;
8319 static const struct got_error *
8320 patch_progress(void *arg, const char *old, const char *new,
8321 unsigned char status, const struct got_error *error, int old_from,
8322 int old_lines, int new_from, int new_lines, int offset,
8323 int ws_mangled, const struct got_error *hunk_err)
8325 const char *path = new == NULL ? old : new;
8326 struct got_patch_progress_arg *a = arg;
8328 while (*path == '/')
8329 path++;
8331 if (status != GOT_STATUS_NO_CHANGE &&
8332 status != 0 /* per-hunk progress */) {
8333 printf("%c %s\n", status, path);
8334 a->did_something = 1;
8337 if (hunk_err == NULL) {
8338 if (status == GOT_STATUS_CANNOT_UPDATE)
8339 a->rejects++;
8340 else if (status == GOT_STATUS_CONFLICT)
8341 a->conflicts++;
8344 if (error != NULL)
8345 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8347 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8348 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8349 old_lines, new_from, new_lines);
8350 if (hunk_err != NULL)
8351 printf("%s\n", hunk_err->msg);
8352 else if (offset != 0)
8353 printf("applied with offset %d\n", offset);
8354 else
8355 printf("hunk contains mangled whitespace\n");
8358 return NULL;
8361 static void
8362 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8364 if (!ppa->did_something)
8365 return;
8367 if (ppa->conflicts > 0)
8368 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8370 if (ppa->rejects > 0) {
8371 printf("Files where patch failed to apply: %d\n",
8372 ppa->rejects);
8376 static const struct got_error *
8377 cmd_patch(int argc, char *argv[])
8379 const struct got_error *error = NULL, *close_error = NULL;
8380 struct got_worktree *worktree = NULL;
8381 struct got_repository *repo = NULL;
8382 struct got_reflist_head refs;
8383 struct got_object_id *commit_id = NULL;
8384 const char *commit_id_str = NULL;
8385 struct stat sb;
8386 const char *errstr;
8387 char *cwd = NULL, *keyword_idstr = NULL;
8388 int ch, nop = 0, strip = -1, reverse = 0;
8389 int patchfd;
8390 int *pack_fds = NULL;
8391 struct got_patch_progress_arg ppa;
8393 TAILQ_INIT(&refs);
8395 #ifndef PROFILE
8396 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8397 "unveil", NULL) == -1)
8398 err(1, "pledge");
8399 #endif
8401 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8402 switch (ch) {
8403 case 'c':
8404 commit_id_str = optarg;
8405 break;
8406 case 'n':
8407 nop = 1;
8408 break;
8409 case 'p':
8410 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8411 if (errstr != NULL)
8412 errx(1, "pathname strip count is %s: %s",
8413 errstr, optarg);
8414 break;
8415 case 'R':
8416 reverse = 1;
8417 break;
8418 default:
8419 usage_patch();
8420 /* NOTREACHED */
8424 argc -= optind;
8425 argv += optind;
8427 if (argc == 0) {
8428 error = patch_from_stdin(&patchfd);
8429 if (error)
8430 return error;
8431 } else if (argc == 1) {
8432 patchfd = open(argv[0], O_RDONLY);
8433 if (patchfd == -1) {
8434 error = got_error_from_errno2("open", argv[0]);
8435 return error;
8437 if (fstat(patchfd, &sb) == -1) {
8438 error = got_error_from_errno2("fstat", argv[0]);
8439 goto done;
8441 if (!S_ISREG(sb.st_mode)) {
8442 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8443 goto done;
8445 } else
8446 usage_patch();
8448 if ((cwd = getcwd(NULL, 0)) == NULL) {
8449 error = got_error_from_errno("getcwd");
8450 goto done;
8453 error = got_repo_pack_fds_open(&pack_fds);
8454 if (error != NULL)
8455 goto done;
8457 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8458 if (error != NULL)
8459 goto done;
8461 const char *repo_path = got_worktree_get_repo_path(worktree);
8462 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8463 if (error != NULL)
8464 goto done;
8466 error = apply_unveil(got_repo_get_path(repo), 0,
8467 got_worktree_get_root_path(worktree));
8468 if (error != NULL)
8469 goto done;
8471 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8472 if (error)
8473 goto done;
8475 if (commit_id_str != NULL) {
8476 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8477 repo, worktree);
8478 if (error != NULL)
8479 goto done;
8481 error = got_repo_match_object_id(&commit_id, NULL,
8482 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8483 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8484 if (error)
8485 goto done;
8488 memset(&ppa, 0, sizeof(ppa));
8489 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8490 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8491 print_patch_progress_stats(&ppa);
8492 done:
8493 got_ref_list_free(&refs);
8494 free(keyword_idstr);
8495 free(commit_id);
8496 if (repo) {
8497 close_error = got_repo_close(repo);
8498 if (error == NULL)
8499 error = close_error;
8501 if (worktree != NULL) {
8502 close_error = got_worktree_close(worktree);
8503 if (error == NULL)
8504 error = close_error;
8506 if (pack_fds) {
8507 const struct got_error *pack_err =
8508 got_repo_pack_fds_close(pack_fds);
8509 if (error == NULL)
8510 error = pack_err;
8512 free(cwd);
8513 return error;
8516 __dead static void
8517 usage_revert(void)
8519 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8520 getprogname());
8521 exit(1);
8524 static const struct got_error *
8525 revert_progress(void *arg, unsigned char status, const char *path)
8527 if (status == GOT_STATUS_UNVERSIONED)
8528 return NULL;
8530 while (path[0] == '/')
8531 path++;
8532 printf("%c %s\n", status, path);
8533 return NULL;
8536 struct choose_patch_arg {
8537 FILE *patch_script_file;
8538 const char *action;
8541 static const struct got_error *
8542 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8543 int nchanges, const char *action)
8545 const struct got_error *err;
8546 char *line = NULL;
8547 size_t linesize = 0;
8548 ssize_t linelen;
8550 switch (status) {
8551 case GOT_STATUS_ADD:
8552 printf("A %s\n%s this addition? [y/n] ", path, action);
8553 break;
8554 case GOT_STATUS_DELETE:
8555 printf("D %s\n%s this deletion? [y/n] ", path, action);
8556 break;
8557 case GOT_STATUS_MODIFY:
8558 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8559 return got_error_from_errno("fseek");
8560 printf(GOT_COMMIT_SEP_STR);
8561 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8562 printf("%s", line);
8563 if (linelen == -1 && ferror(patch_file)) {
8564 err = got_error_from_errno("getline");
8565 free(line);
8566 return err;
8568 free(line);
8569 printf(GOT_COMMIT_SEP_STR);
8570 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8571 path, n, nchanges, action);
8572 break;
8573 default:
8574 return got_error_path(path, GOT_ERR_FILE_STATUS);
8577 fflush(stdout);
8578 return NULL;
8581 static const struct got_error *
8582 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8583 FILE *patch_file, int n, int nchanges)
8585 const struct got_error *err = NULL;
8586 char *line = NULL;
8587 size_t linesize = 0;
8588 ssize_t linelen;
8589 int resp = ' ';
8590 struct choose_patch_arg *a = arg;
8592 *choice = GOT_PATCH_CHOICE_NONE;
8594 if (a->patch_script_file) {
8595 char *nl;
8596 err = show_change(status, path, patch_file, n, nchanges,
8597 a->action);
8598 if (err)
8599 return err;
8600 linelen = getline(&line, &linesize, a->patch_script_file);
8601 if (linelen == -1) {
8602 if (ferror(a->patch_script_file))
8603 return got_error_from_errno("getline");
8604 return NULL;
8606 nl = strchr(line, '\n');
8607 if (nl)
8608 *nl = '\0';
8609 if (strcmp(line, "y") == 0) {
8610 *choice = GOT_PATCH_CHOICE_YES;
8611 printf("y\n");
8612 } else if (strcmp(line, "n") == 0) {
8613 *choice = GOT_PATCH_CHOICE_NO;
8614 printf("n\n");
8615 } else if (strcmp(line, "q") == 0 &&
8616 status == GOT_STATUS_MODIFY) {
8617 *choice = GOT_PATCH_CHOICE_QUIT;
8618 printf("q\n");
8619 } else
8620 printf("invalid response '%s'\n", line);
8621 free(line);
8622 return NULL;
8625 while (resp != 'y' && resp != 'n' && resp != 'q') {
8626 err = show_change(status, path, patch_file, n, nchanges,
8627 a->action);
8628 if (err)
8629 return err;
8630 resp = getchar();
8631 if (resp == '\n')
8632 resp = getchar();
8633 if (status == GOT_STATUS_MODIFY) {
8634 if (resp != 'y' && resp != 'n' && resp != 'q') {
8635 printf("invalid response '%c'\n", resp);
8636 resp = ' ';
8638 } else if (resp != 'y' && resp != 'n') {
8639 printf("invalid response '%c'\n", resp);
8640 resp = ' ';
8644 if (resp == 'y')
8645 *choice = GOT_PATCH_CHOICE_YES;
8646 else if (resp == 'n')
8647 *choice = GOT_PATCH_CHOICE_NO;
8648 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8649 *choice = GOT_PATCH_CHOICE_QUIT;
8651 return NULL;
8654 struct wt_commitable_path_arg {
8655 struct got_pathlist_head *commit_paths;
8656 int *has_changes;
8660 * Shortcut work tree status callback to determine if the set of paths scanned
8661 * has at least one versioned path that is being modified and, if not NULL, is
8662 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8663 * soon as a path is passed with a status that satisfies this criteria.
8665 static const struct got_error *
8666 worktree_has_commitable_path(void *arg, unsigned char status,
8667 unsigned char staged_status, const char *path,
8668 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8669 struct got_object_id *commit_id, int dirfd, const char *de_name)
8671 struct wt_commitable_path_arg *a = arg;
8673 if (status == staged_status && (status == GOT_STATUS_DELETE))
8674 status = GOT_STATUS_NO_CHANGE;
8676 if (!(status == GOT_STATUS_NO_CHANGE ||
8677 status == GOT_STATUS_UNVERSIONED) ||
8678 staged_status != GOT_STATUS_NO_CHANGE) {
8679 if (a->commit_paths != NULL) {
8680 struct got_pathlist_entry *pe;
8682 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8683 if (strncmp(path, pe->path,
8684 pe->path_len) == 0) {
8685 *a->has_changes = 1;
8686 break;
8689 } else
8690 *a->has_changes = 1;
8692 if (*a->has_changes)
8693 return got_error(GOT_ERR_FILE_MODIFIED);
8696 return NULL;
8700 * Check that the changeset of the commit identified by id is
8701 * comprised of at least one modified path that is being committed.
8703 static const struct got_error *
8704 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8705 struct got_object_id *id, struct got_worktree *worktree,
8706 struct got_repository *repo)
8708 const struct got_error *err;
8709 struct got_pathlist_head paths;
8710 struct got_commit_object *commit = NULL, *pcommit = NULL;
8711 struct got_tree_object *tree = NULL, *ptree = NULL;
8712 struct got_object_qid *pid;
8714 TAILQ_INIT(&paths);
8716 err = got_object_open_as_commit(&commit, repo, id);
8717 if (err)
8718 goto done;
8720 err = got_object_open_as_tree(&tree, repo,
8721 got_object_commit_get_tree_id(commit));
8722 if (err)
8723 goto done;
8725 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8726 if (pid != NULL) {
8727 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8728 if (err)
8729 goto done;
8731 err = got_object_open_as_tree(&ptree, repo,
8732 got_object_commit_get_tree_id(pcommit));
8733 if (err)
8734 goto done;
8737 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8738 got_diff_tree_collect_changed_paths, &paths, 0);
8739 if (err)
8740 goto done;
8742 err = got_worktree_status(worktree, &paths, repo, 0,
8743 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8744 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8746 * At least one changed path in the referenced commit is
8747 * modified in the work tree, that's all we need to know!
8749 err = NULL;
8752 done:
8753 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8754 if (commit)
8755 got_object_commit_close(commit);
8756 if (pcommit)
8757 got_object_commit_close(pcommit);
8758 if (tree)
8759 got_object_tree_close(tree);
8760 if (ptree)
8761 got_object_tree_close(ptree);
8762 return err;
8766 * Remove any "logmsg" reference comprised entirely of paths that have
8767 * been reverted in this work tree. If any path in the logmsg ref changeset
8768 * remains in a changed state in the worktree, do not remove the reference.
8770 static const struct got_error *
8771 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8773 const struct got_error *err;
8774 struct got_reflist_head refs;
8775 struct got_reflist_entry *re;
8776 struct got_commit_object *commit = NULL;
8777 struct got_object_id *commit_id = NULL;
8778 struct wt_commitable_path_arg wcpa;
8779 char *uuidstr = NULL;
8781 TAILQ_INIT(&refs);
8783 err = got_worktree_get_uuid(&uuidstr, worktree);
8784 if (err)
8785 goto done;
8787 err = got_ref_list(&refs, repo, "refs/got/worktree",
8788 got_ref_cmp_by_name, repo);
8789 if (err)
8790 goto done;
8792 TAILQ_FOREACH(re, &refs, entry) {
8793 const char *refname;
8794 int has_changes = 0;
8796 refname = got_ref_get_name(re->ref);
8798 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8799 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8800 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8801 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8802 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8803 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8804 else
8805 continue;
8807 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8808 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8809 else
8810 continue;
8812 err = got_repo_match_object_id(&commit_id, NULL, refname,
8813 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8814 if (err)
8815 goto done;
8817 err = got_object_open_as_commit(&commit, repo, commit_id);
8818 if (err)
8819 goto done;
8821 wcpa.commit_paths = NULL;
8822 wcpa.has_changes = &has_changes;
8824 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8825 worktree, repo);
8826 if (err)
8827 goto done;
8829 if (!has_changes) {
8830 err = got_ref_delete(re->ref, repo);
8831 if (err)
8832 goto done;
8835 got_object_commit_close(commit);
8836 commit = NULL;
8837 free(commit_id);
8838 commit_id = NULL;
8841 done:
8842 free(uuidstr);
8843 free(commit_id);
8844 got_ref_list_free(&refs);
8845 if (commit)
8846 got_object_commit_close(commit);
8847 return err;
8850 static const struct got_error *
8851 cmd_revert(int argc, char *argv[])
8853 const struct got_error *error = NULL;
8854 struct got_worktree *worktree = NULL;
8855 struct got_repository *repo = NULL;
8856 char *cwd = NULL, *path = NULL;
8857 struct got_pathlist_head paths;
8858 struct got_pathlist_entry *pe;
8859 int ch, can_recurse = 0, pflag = 0;
8860 FILE *patch_script_file = NULL;
8861 const char *patch_script_path = NULL;
8862 struct choose_patch_arg cpa;
8863 int *pack_fds = NULL;
8865 TAILQ_INIT(&paths);
8867 #ifndef PROFILE
8868 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8869 "unveil", NULL) == -1)
8870 err(1, "pledge");
8871 #endif
8873 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8874 switch (ch) {
8875 case 'F':
8876 patch_script_path = optarg;
8877 break;
8878 case 'p':
8879 pflag = 1;
8880 break;
8881 case 'R':
8882 can_recurse = 1;
8883 break;
8884 default:
8885 usage_revert();
8886 /* NOTREACHED */
8890 argc -= optind;
8891 argv += optind;
8893 if (argc < 1)
8894 usage_revert();
8895 if (patch_script_path && !pflag)
8896 errx(1, "-F option can only be used together with -p option");
8898 cwd = getcwd(NULL, 0);
8899 if (cwd == NULL) {
8900 error = got_error_from_errno("getcwd");
8901 goto done;
8904 error = got_repo_pack_fds_open(&pack_fds);
8905 if (error != NULL)
8906 goto done;
8908 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8909 if (error) {
8910 if (error->code == GOT_ERR_NOT_WORKTREE)
8911 error = wrap_not_worktree_error(error, "revert", cwd);
8912 goto done;
8915 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8916 NULL, pack_fds);
8917 if (error != NULL)
8918 goto done;
8920 if (patch_script_path) {
8921 patch_script_file = fopen(patch_script_path, "re");
8922 if (patch_script_file == NULL) {
8923 error = got_error_from_errno2("fopen",
8924 patch_script_path);
8925 goto done;
8930 * XXX "c" perm needed on repo dir to delete merge references.
8932 error = apply_unveil(got_repo_get_path(repo), 0,
8933 got_worktree_get_root_path(worktree));
8934 if (error)
8935 goto done;
8937 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8938 if (error)
8939 goto done;
8941 if (!can_recurse) {
8942 char *ondisk_path;
8943 struct stat sb;
8944 TAILQ_FOREACH(pe, &paths, entry) {
8945 if (asprintf(&ondisk_path, "%s/%s",
8946 got_worktree_get_root_path(worktree),
8947 pe->path) == -1) {
8948 error = got_error_from_errno("asprintf");
8949 goto done;
8951 if (lstat(ondisk_path, &sb) == -1) {
8952 if (errno == ENOENT) {
8953 free(ondisk_path);
8954 continue;
8956 error = got_error_from_errno2("lstat",
8957 ondisk_path);
8958 free(ondisk_path);
8959 goto done;
8961 free(ondisk_path);
8962 if (S_ISDIR(sb.st_mode)) {
8963 error = got_error_msg(GOT_ERR_BAD_PATH,
8964 "reverting directories requires -R option");
8965 goto done;
8970 cpa.patch_script_file = patch_script_file;
8971 cpa.action = "revert";
8972 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8973 pflag ? choose_patch : NULL, &cpa, repo);
8975 error = rm_logmsg_ref(worktree, repo);
8976 done:
8977 if (patch_script_file && fclose(patch_script_file) == EOF &&
8978 error == NULL)
8979 error = got_error_from_errno2("fclose", patch_script_path);
8980 if (repo) {
8981 const struct got_error *close_err = got_repo_close(repo);
8982 if (error == NULL)
8983 error = close_err;
8985 if (worktree)
8986 got_worktree_close(worktree);
8987 if (pack_fds) {
8988 const struct got_error *pack_err =
8989 got_repo_pack_fds_close(pack_fds);
8990 if (error == NULL)
8991 error = pack_err;
8993 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8994 free(path);
8995 free(cwd);
8996 return error;
8999 __dead static void
9000 usage_commit(void)
9002 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9003 "[-m message] [path ...]\n", getprogname());
9004 exit(1);
9007 struct collect_commit_logmsg_arg {
9008 const char *cmdline_log;
9009 const char *prepared_log;
9010 const char *merged_log;
9011 int non_interactive;
9012 const char *editor;
9013 const char *worktree_path;
9014 const char *branch_name;
9015 const char *repo_path;
9016 char *logmsg_path;
9020 static const struct got_error *
9021 read_prepared_logmsg(char **logmsg, const char *path)
9023 const struct got_error *err = NULL;
9024 FILE *f = NULL;
9025 struct stat sb;
9026 size_t r;
9028 *logmsg = NULL;
9029 memset(&sb, 0, sizeof(sb));
9031 f = fopen(path, "re");
9032 if (f == NULL)
9033 return got_error_from_errno2("fopen", path);
9035 if (fstat(fileno(f), &sb) == -1) {
9036 err = got_error_from_errno2("fstat", path);
9037 goto done;
9039 if (sb.st_size == 0) {
9040 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9041 goto done;
9044 *logmsg = malloc(sb.st_size + 1);
9045 if (*logmsg == NULL) {
9046 err = got_error_from_errno("malloc");
9047 goto done;
9050 r = fread(*logmsg, 1, sb.st_size, f);
9051 if (r != sb.st_size) {
9052 if (ferror(f))
9053 err = got_error_from_errno2("fread", path);
9054 else
9055 err = got_error(GOT_ERR_IO);
9056 goto done;
9058 (*logmsg)[sb.st_size] = '\0';
9059 done:
9060 if (fclose(f) == EOF && err == NULL)
9061 err = got_error_from_errno2("fclose", path);
9062 if (err) {
9063 free(*logmsg);
9064 *logmsg = NULL;
9066 return err;
9069 static const struct got_error *
9070 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9071 const char *diff_path, char **logmsg, void *arg)
9073 char *initial_content = NULL;
9074 struct got_pathlist_entry *pe;
9075 const struct got_error *err = NULL;
9076 char *template = NULL;
9077 char *prepared_msg = NULL, *merged_msg = NULL;
9078 struct collect_commit_logmsg_arg *a = arg;
9079 int initial_content_len;
9080 int fd = -1;
9081 size_t len;
9083 /* if a message was specified on the command line, just use it */
9084 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9085 len = strlen(a->cmdline_log) + 1;
9086 *logmsg = malloc(len + 1);
9087 if (*logmsg == NULL)
9088 return got_error_from_errno("malloc");
9089 strlcpy(*logmsg, a->cmdline_log, len);
9090 return NULL;
9091 } else if (a->prepared_log != NULL && a->non_interactive)
9092 return read_prepared_logmsg(logmsg, a->prepared_log);
9094 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9095 return got_error_from_errno("asprintf");
9097 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9098 if (err)
9099 goto done;
9101 if (a->prepared_log) {
9102 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9103 if (err)
9104 goto done;
9105 } else if (a->merged_log) {
9106 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9107 if (err)
9108 goto done;
9111 initial_content_len = asprintf(&initial_content,
9112 "%s%s\n# changes to be committed on branch %s:\n",
9113 prepared_msg ? prepared_msg : "",
9114 merged_msg ? merged_msg : "", a->branch_name);
9115 if (initial_content_len == -1) {
9116 err = got_error_from_errno("asprintf");
9117 goto done;
9120 if (write(fd, initial_content, initial_content_len) == -1) {
9121 err = got_error_from_errno2("write", a->logmsg_path);
9122 goto done;
9125 TAILQ_FOREACH(pe, commitable_paths, entry) {
9126 struct got_commitable *ct = pe->data;
9127 dprintf(fd, "# %c %s\n",
9128 got_commitable_get_status(ct),
9129 got_commitable_get_path(ct));
9132 if (diff_path) {
9133 dprintf(fd, "# detailed changes can be viewed in %s\n",
9134 diff_path);
9137 if (close(fd) == -1) {
9138 err = got_error_from_errno2("close", a->logmsg_path);
9139 goto done;
9141 fd = -1;
9143 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9144 initial_content_len, a->prepared_log ? 0 : 1);
9145 done:
9146 free(initial_content);
9147 free(template);
9148 free(prepared_msg);
9149 free(merged_msg);
9151 if (fd != -1 && close(fd) == -1 && err == NULL)
9152 err = got_error_from_errno2("close", a->logmsg_path);
9153 if (err) {
9154 free(*logmsg);
9155 *logmsg = NULL;
9157 return err;
9160 static const struct got_error *
9161 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9162 const char *type, int has_content)
9164 const struct got_error *err = NULL;
9165 char *logmsg = NULL;
9167 err = got_object_commit_get_logmsg(&logmsg, commit);
9168 if (err)
9169 return err;
9171 if (fprintf(f, "%s# log message of %s commit %s:%s",
9172 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9173 err = got_ferror(f, GOT_ERR_IO);
9175 free(logmsg);
9176 return err;
9180 * Lookup "logmsg" references of backed-out and cherrypicked commits
9181 * belonging to the current work tree. If found, and the worktree has
9182 * at least one modified file that was changed in the referenced commit,
9183 * add its log message to a new temporary file at *logmsg_path.
9184 * Add all refs found to matched_refs to be scheduled for removal on
9185 * successful commit.
9187 static const struct got_error *
9188 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9189 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9190 struct got_repository *repo)
9192 const struct got_error *err;
9193 struct got_commit_object *commit = NULL;
9194 struct got_object_id *id = NULL;
9195 struct got_reflist_head refs;
9196 struct got_reflist_entry *re, *re_match;
9197 FILE *f = NULL;
9198 char *uuidstr = NULL;
9199 int added_logmsg = 0;
9201 TAILQ_INIT(&refs);
9203 *logmsg_path = NULL;
9205 err = got_worktree_get_uuid(&uuidstr, worktree);
9206 if (err)
9207 goto done;
9209 err = got_ref_list(&refs, repo, "refs/got/worktree",
9210 got_ref_cmp_by_name, repo);
9211 if (err)
9212 goto done;
9214 TAILQ_FOREACH(re, &refs, entry) {
9215 const char *refname, *type;
9216 struct wt_commitable_path_arg wcpa;
9217 int add_logmsg = 0;
9219 refname = got_ref_get_name(re->ref);
9221 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9222 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9223 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9224 type = "cherrypicked";
9225 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9226 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9227 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9228 type = "backed-out";
9229 } else
9230 continue;
9232 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9233 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9234 else
9235 continue;
9237 err = got_repo_match_object_id(&id, NULL, refname,
9238 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9239 if (err)
9240 goto done;
9242 err = got_object_open_as_commit(&commit, repo, id);
9243 if (err)
9244 goto done;
9246 wcpa.commit_paths = paths;
9247 wcpa.has_changes = &add_logmsg;
9249 err = commit_path_changed_in_worktree(&wcpa, id,
9250 worktree, repo);
9251 if (err)
9252 goto done;
9254 if (add_logmsg) {
9255 if (f == NULL) {
9256 err = got_opentemp_named(logmsg_path, &f,
9257 "got-commit-logmsg", "");
9258 if (err)
9259 goto done;
9261 err = cat_logmsg(f, commit, refname, type,
9262 added_logmsg);
9263 if (err)
9264 goto done;
9265 if (!added_logmsg)
9266 ++added_logmsg;
9268 err = got_reflist_entry_dup(&re_match, re);
9269 if (err)
9270 goto done;
9271 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9274 got_object_commit_close(commit);
9275 commit = NULL;
9276 free(id);
9277 id = NULL;
9280 done:
9281 free(id);
9282 free(uuidstr);
9283 got_ref_list_free(&refs);
9284 if (commit)
9285 got_object_commit_close(commit);
9286 if (f && fclose(f) == EOF && err == NULL)
9287 err = got_error_from_errno("fclose");
9288 if (!added_logmsg) {
9289 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9290 err = got_error_from_errno2("unlink", *logmsg_path);
9291 *logmsg_path = NULL;
9293 return err;
9296 static const struct got_error *
9297 cmd_commit(int argc, char *argv[])
9299 const struct got_error *error = NULL;
9300 struct got_worktree *worktree = NULL;
9301 struct got_repository *repo = NULL;
9302 char *cwd = NULL, *id_str = NULL;
9303 struct got_object_id *id = NULL;
9304 const char *logmsg = NULL;
9305 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9306 struct collect_commit_logmsg_arg cl_arg;
9307 const char *author = NULL;
9308 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9309 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9310 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9311 int show_diff = 1, commit_conflicts = 0;
9312 struct got_pathlist_head paths;
9313 struct got_reflist_head refs;
9314 struct got_reflist_entry *re;
9315 int *pack_fds = NULL;
9317 TAILQ_INIT(&refs);
9318 TAILQ_INIT(&paths);
9319 cl_arg.logmsg_path = NULL;
9321 #ifndef PROFILE
9322 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9323 "unveil", NULL) == -1)
9324 err(1, "pledge");
9325 #endif
9327 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9328 switch (ch) {
9329 case 'A':
9330 author = optarg;
9331 error = valid_author(author);
9332 if (error)
9333 return error;
9334 break;
9335 case 'C':
9336 commit_conflicts = 1;
9337 break;
9338 case 'F':
9339 if (logmsg != NULL)
9340 option_conflict('F', 'm');
9341 prepared_logmsg = realpath(optarg, NULL);
9342 if (prepared_logmsg == NULL)
9343 return got_error_from_errno2("realpath",
9344 optarg);
9345 break;
9346 case 'm':
9347 if (prepared_logmsg)
9348 option_conflict('m', 'F');
9349 logmsg = optarg;
9350 break;
9351 case 'N':
9352 non_interactive = 1;
9353 break;
9354 case 'n':
9355 show_diff = 0;
9356 break;
9357 case 'S':
9358 allow_bad_symlinks = 1;
9359 break;
9360 default:
9361 usage_commit();
9362 /* NOTREACHED */
9366 argc -= optind;
9367 argv += optind;
9369 cwd = getcwd(NULL, 0);
9370 if (cwd == NULL) {
9371 error = got_error_from_errno("getcwd");
9372 goto done;
9375 error = got_repo_pack_fds_open(&pack_fds);
9376 if (error != NULL)
9377 goto done;
9379 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9380 if (error) {
9381 if (error->code == GOT_ERR_NOT_WORKTREE)
9382 error = wrap_not_worktree_error(error, "commit", cwd);
9383 goto done;
9386 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9387 if (error)
9388 goto done;
9389 if (rebase_in_progress) {
9390 error = got_error(GOT_ERR_REBASING);
9391 goto done;
9394 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9395 worktree);
9396 if (error)
9397 goto done;
9399 error = get_gitconfig_path(&gitconfig_path);
9400 if (error)
9401 goto done;
9402 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9403 gitconfig_path, pack_fds);
9404 if (error != NULL)
9405 goto done;
9407 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9408 if (error)
9409 goto done;
9410 if (merge_in_progress) {
9411 error = got_error(GOT_ERR_MERGE_BUSY);
9412 goto done;
9415 error = get_author(&committer, repo, worktree);
9416 if (error)
9417 goto done;
9419 if (author == NULL)
9420 author = committer;
9422 if (logmsg == NULL || strlen(logmsg) == 0) {
9423 error = get_editor(&editor);
9424 if (error)
9425 goto done;
9426 if (unveil(editor, "x") != 0) {
9427 error = got_error_from_errno2("unveil", editor);
9428 goto done;
9432 error = apply_unveil(got_repo_get_path(repo), 0,
9433 got_worktree_get_root_path(worktree));
9434 if (error)
9435 goto done;
9437 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9438 if (error)
9439 goto done;
9441 if (prepared_logmsg == NULL) {
9442 error = lookup_logmsg_ref(&merged_logmsg,
9443 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9444 if (error)
9445 goto done;
9448 cl_arg.editor = editor;
9449 cl_arg.cmdline_log = logmsg;
9450 cl_arg.prepared_log = prepared_logmsg;
9451 cl_arg.merged_log = merged_logmsg;
9452 cl_arg.non_interactive = non_interactive;
9453 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9454 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9455 if (!histedit_in_progress) {
9456 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9457 error = got_error(GOT_ERR_COMMIT_BRANCH);
9458 goto done;
9460 cl_arg.branch_name += 11;
9462 cl_arg.repo_path = got_repo_get_path(repo);
9463 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9464 allow_bad_symlinks, show_diff, commit_conflicts,
9465 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9466 if (error) {
9467 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9468 cl_arg.logmsg_path != NULL)
9469 preserve_logmsg = 1;
9470 goto done;
9473 error = got_object_id_str(&id_str, id);
9474 if (error)
9475 goto done;
9476 printf("Created commit %s\n", id_str);
9478 TAILQ_FOREACH(re, &refs, entry) {
9479 error = got_ref_delete(re->ref, repo);
9480 if (error)
9481 goto done;
9484 done:
9485 if (preserve_logmsg) {
9486 fprintf(stderr, "%s: log message preserved in %s\n",
9487 getprogname(), cl_arg.logmsg_path);
9488 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9489 error == NULL)
9490 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9491 free(cl_arg.logmsg_path);
9492 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9493 error = got_error_from_errno2("unlink", merged_logmsg);
9494 free(merged_logmsg);
9495 if (repo) {
9496 const struct got_error *close_err = got_repo_close(repo);
9497 if (error == NULL)
9498 error = close_err;
9500 if (worktree)
9501 got_worktree_close(worktree);
9502 if (pack_fds) {
9503 const struct got_error *pack_err =
9504 got_repo_pack_fds_close(pack_fds);
9505 if (error == NULL)
9506 error = pack_err;
9508 got_ref_list_free(&refs);
9509 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9510 free(cwd);
9511 free(id_str);
9512 free(gitconfig_path);
9513 free(editor);
9514 free(committer);
9515 free(prepared_logmsg);
9516 return error;
9519 __dead static void
9520 usage_send(void)
9522 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9523 "[-r repository-path] [-t tag] [remote-repository]\n",
9524 getprogname());
9525 exit(1);
9528 static void
9529 print_load_info(int print_colored, int print_found, int print_trees,
9530 int ncolored, int nfound, int ntrees)
9532 if (print_colored) {
9533 printf("%d commit%s colored", ncolored,
9534 ncolored == 1 ? "" : "s");
9536 if (print_found) {
9537 printf("%s%d object%s found",
9538 ncolored > 0 ? "; " : "",
9539 nfound, nfound == 1 ? "" : "s");
9541 if (print_trees) {
9542 printf("; %d tree%s scanned", ntrees,
9543 ntrees == 1 ? "" : "s");
9547 struct got_send_progress_arg {
9548 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9549 int verbosity;
9550 int last_ncolored;
9551 int last_nfound;
9552 int last_ntrees;
9553 int loading_done;
9554 int last_ncommits;
9555 int last_nobj_total;
9556 int last_p_deltify;
9557 int last_p_written;
9558 int last_p_sent;
9559 int printed_something;
9560 int sent_something;
9561 struct got_pathlist_head *delete_branches;
9564 static const struct got_error *
9565 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9566 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9567 int nobj_written, off_t bytes_sent, const char *refname,
9568 const char *errmsg, int success)
9570 struct got_send_progress_arg *a = arg;
9571 char scaled_packsize[FMT_SCALED_STRSIZE];
9572 char scaled_sent[FMT_SCALED_STRSIZE];
9573 int p_deltify = 0, p_written = 0, p_sent = 0;
9574 int print_colored = 0, print_found = 0, print_trees = 0;
9575 int print_searching = 0, print_total = 0;
9576 int print_deltify = 0, print_written = 0, print_sent = 0;
9578 if (a->verbosity < 0)
9579 return NULL;
9581 if (refname) {
9582 const char *status = success ? "accepted" : "rejected";
9584 if (success) {
9585 struct got_pathlist_entry *pe;
9586 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9587 const char *branchname = pe->path;
9588 if (got_path_cmp(branchname, refname,
9589 strlen(branchname), strlen(refname)) == 0) {
9590 status = "deleted";
9591 a->sent_something = 1;
9592 break;
9597 if (a->printed_something)
9598 putchar('\n');
9599 printf("Server has %s %s", status, refname);
9600 if (errmsg)
9601 printf(": %s", errmsg);
9602 a->printed_something = 1;
9603 return NULL;
9606 if (a->last_ncolored != ncolored) {
9607 print_colored = 1;
9608 a->last_ncolored = ncolored;
9611 if (a->last_nfound != nfound) {
9612 print_colored = 1;
9613 print_found = 1;
9614 a->last_nfound = nfound;
9617 if (a->last_ntrees != ntrees) {
9618 print_colored = 1;
9619 print_found = 1;
9620 print_trees = 1;
9621 a->last_ntrees = ntrees;
9624 if ((print_colored || print_found || print_trees) &&
9625 !a->loading_done) {
9626 printf("\r");
9627 print_load_info(print_colored, print_found, print_trees,
9628 ncolored, nfound, ntrees);
9629 a->printed_something = 1;
9630 fflush(stdout);
9631 return NULL;
9632 } else if (!a->loading_done) {
9633 printf("\r");
9634 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9635 printf("\n");
9636 a->loading_done = 1;
9639 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9640 return got_error_from_errno("fmt_scaled");
9641 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9642 return got_error_from_errno("fmt_scaled");
9644 if (a->last_ncommits != ncommits) {
9645 print_searching = 1;
9646 a->last_ncommits = ncommits;
9649 if (a->last_nobj_total != nobj_total) {
9650 print_searching = 1;
9651 print_total = 1;
9652 a->last_nobj_total = nobj_total;
9655 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9656 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9657 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9658 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9659 return got_error(GOT_ERR_NO_SPACE);
9662 if (nobj_deltify > 0 || nobj_written > 0) {
9663 if (nobj_deltify > 0) {
9664 p_deltify = (nobj_deltify * 100) / nobj_total;
9665 if (p_deltify != a->last_p_deltify) {
9666 a->last_p_deltify = p_deltify;
9667 print_searching = 1;
9668 print_total = 1;
9669 print_deltify = 1;
9672 if (nobj_written > 0) {
9673 p_written = (nobj_written * 100) / nobj_total;
9674 if (p_written != a->last_p_written) {
9675 a->last_p_written = p_written;
9676 print_searching = 1;
9677 print_total = 1;
9678 print_deltify = 1;
9679 print_written = 1;
9684 if (bytes_sent > 0) {
9685 p_sent = (bytes_sent * 100) / packfile_size;
9686 if (p_sent != a->last_p_sent) {
9687 a->last_p_sent = p_sent;
9688 print_searching = 1;
9689 print_total = 1;
9690 print_deltify = 1;
9691 print_written = 1;
9692 print_sent = 1;
9694 a->sent_something = 1;
9697 if (print_searching || print_total || print_deltify || print_written ||
9698 print_sent)
9699 printf("\r");
9700 if (print_searching)
9701 printf("packing %d reference%s", ncommits,
9702 ncommits == 1 ? "" : "s");
9703 if (print_total)
9704 printf("; %d object%s", nobj_total,
9705 nobj_total == 1 ? "" : "s");
9706 if (print_deltify)
9707 printf("; deltify: %d%%", p_deltify);
9708 if (print_sent)
9709 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9710 scaled_packsize, p_sent);
9711 else if (print_written)
9712 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9713 scaled_packsize, p_written);
9714 if (print_searching || print_total || print_deltify ||
9715 print_written || print_sent) {
9716 a->printed_something = 1;
9717 fflush(stdout);
9719 return NULL;
9722 static const struct got_error *
9723 cmd_send(int argc, char *argv[])
9725 const struct got_error *error = NULL;
9726 char *cwd = NULL, *repo_path = NULL;
9727 const char *remote_name;
9728 char *proto = NULL, *host = NULL, *port = NULL;
9729 char *repo_name = NULL, *server_path = NULL;
9730 const struct got_remote_repo *remotes;
9731 struct got_remote_repo *remote = NULL;
9732 int nremotes, nbranches = 0, ndelete_branches = 0;
9733 struct got_repository *repo = NULL;
9734 struct got_worktree *worktree = NULL;
9735 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9736 struct got_pathlist_head branches;
9737 struct got_pathlist_head tags;
9738 struct got_reflist_head all_branches;
9739 struct got_reflist_head all_tags;
9740 struct got_pathlist_head delete_args;
9741 struct got_pathlist_head delete_branches;
9742 struct got_reflist_entry *re;
9743 struct got_pathlist_entry *pe;
9744 int i, ch, sendfd = -1, sendstatus;
9745 pid_t sendpid = -1;
9746 struct got_send_progress_arg spa;
9747 int verbosity = 0, overwrite_refs = 0;
9748 int send_all_branches = 0, send_all_tags = 0;
9749 struct got_reference *ref = NULL;
9750 int *pack_fds = NULL;
9752 TAILQ_INIT(&branches);
9753 TAILQ_INIT(&tags);
9754 TAILQ_INIT(&all_branches);
9755 TAILQ_INIT(&all_tags);
9756 TAILQ_INIT(&delete_args);
9757 TAILQ_INIT(&delete_branches);
9759 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9760 switch (ch) {
9761 case 'a':
9762 send_all_branches = 1;
9763 break;
9764 case 'b':
9765 error = got_pathlist_append(&branches, optarg, NULL);
9766 if (error)
9767 return error;
9768 nbranches++;
9769 break;
9770 case 'd':
9771 error = got_pathlist_append(&delete_args, optarg, NULL);
9772 if (error)
9773 return error;
9774 break;
9775 case 'f':
9776 overwrite_refs = 1;
9777 break;
9778 case 'q':
9779 verbosity = -1;
9780 break;
9781 case 'r':
9782 repo_path = realpath(optarg, NULL);
9783 if (repo_path == NULL)
9784 return got_error_from_errno2("realpath",
9785 optarg);
9786 got_path_strip_trailing_slashes(repo_path);
9787 break;
9788 case 'T':
9789 send_all_tags = 1;
9790 break;
9791 case 't':
9792 error = got_pathlist_append(&tags, optarg, NULL);
9793 if (error)
9794 return error;
9795 break;
9796 case 'v':
9797 if (verbosity < 0)
9798 verbosity = 0;
9799 else if (verbosity < 3)
9800 verbosity++;
9801 break;
9802 default:
9803 usage_send();
9804 /* NOTREACHED */
9807 argc -= optind;
9808 argv += optind;
9810 if (send_all_branches && !TAILQ_EMPTY(&branches))
9811 option_conflict('a', 'b');
9812 if (send_all_tags && !TAILQ_EMPTY(&tags))
9813 option_conflict('T', 't');
9816 if (argc == 0)
9817 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9818 else if (argc == 1)
9819 remote_name = argv[0];
9820 else
9821 usage_send();
9823 cwd = getcwd(NULL, 0);
9824 if (cwd == NULL) {
9825 error = got_error_from_errno("getcwd");
9826 goto done;
9829 error = got_repo_pack_fds_open(&pack_fds);
9830 if (error != NULL)
9831 goto done;
9833 if (repo_path == NULL) {
9834 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9835 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9836 goto done;
9837 else
9838 error = NULL;
9839 if (worktree) {
9840 repo_path =
9841 strdup(got_worktree_get_repo_path(worktree));
9842 if (repo_path == NULL)
9843 error = got_error_from_errno("strdup");
9844 if (error)
9845 goto done;
9846 } else {
9847 repo_path = strdup(cwd);
9848 if (repo_path == NULL) {
9849 error = got_error_from_errno("strdup");
9850 goto done;
9855 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9856 if (error)
9857 goto done;
9859 if (worktree) {
9860 worktree_conf = got_worktree_get_gotconfig(worktree);
9861 if (worktree_conf) {
9862 got_gotconfig_get_remotes(&nremotes, &remotes,
9863 worktree_conf);
9864 for (i = 0; i < nremotes; i++) {
9865 if (strcmp(remotes[i].name, remote_name) == 0) {
9866 error = got_repo_remote_repo_dup(&remote,
9867 &remotes[i]);
9868 if (error)
9869 goto done;
9870 break;
9875 if (remote == NULL) {
9876 repo_conf = got_repo_get_gotconfig(repo);
9877 if (repo_conf) {
9878 got_gotconfig_get_remotes(&nremotes, &remotes,
9879 repo_conf);
9880 for (i = 0; i < nremotes; i++) {
9881 if (strcmp(remotes[i].name, remote_name) == 0) {
9882 error = got_repo_remote_repo_dup(&remote,
9883 &remotes[i]);
9884 if (error)
9885 goto done;
9886 break;
9891 if (remote == NULL) {
9892 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9893 for (i = 0; i < nremotes; i++) {
9894 if (strcmp(remotes[i].name, remote_name) == 0) {
9895 error = got_repo_remote_repo_dup(&remote,
9896 &remotes[i]);
9897 if (error)
9898 goto done;
9899 break;
9903 if (remote == NULL) {
9904 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9905 goto done;
9908 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9909 &repo_name, remote->send_url);
9910 if (error)
9911 goto done;
9913 if (strcmp(proto, "git") == 0) {
9914 #ifndef PROFILE
9915 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9916 "sendfd dns inet unveil", NULL) == -1)
9917 err(1, "pledge");
9918 #endif
9919 } else if (strcmp(proto, "git+ssh") == 0 ||
9920 strcmp(proto, "ssh") == 0) {
9921 #ifndef PROFILE
9922 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9923 "sendfd unveil", NULL) == -1)
9924 err(1, "pledge");
9925 #endif
9926 } else if (strcmp(proto, "http") == 0 ||
9927 strcmp(proto, "git+http") == 0) {
9928 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9929 goto done;
9930 } else {
9931 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9932 goto done;
9935 error = got_dial_apply_unveil(proto);
9936 if (error)
9937 goto done;
9939 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9940 if (error)
9941 goto done;
9943 if (send_all_branches) {
9944 error = got_ref_list(&all_branches, repo, "refs/heads",
9945 got_ref_cmp_by_name, NULL);
9946 if (error)
9947 goto done;
9948 TAILQ_FOREACH(re, &all_branches, entry) {
9949 const char *branchname = got_ref_get_name(re->ref);
9950 error = got_pathlist_append(&branches,
9951 branchname, NULL);
9952 if (error)
9953 goto done;
9954 nbranches++;
9956 } else if (nbranches == 0) {
9957 for (i = 0; i < remote->nsend_branches; i++) {
9958 error = got_pathlist_append(&branches,
9959 remote->send_branches[i], NULL);
9960 if (error)
9961 goto done;
9965 if (send_all_tags) {
9966 error = got_ref_list(&all_tags, repo, "refs/tags",
9967 got_ref_cmp_by_name, NULL);
9968 if (error)
9969 goto done;
9970 TAILQ_FOREACH(re, &all_tags, entry) {
9971 const char *tagname = got_ref_get_name(re->ref);
9972 error = got_pathlist_append(&tags,
9973 tagname, NULL);
9974 if (error)
9975 goto done;
9980 * To prevent accidents only branches in refs/heads/ can be deleted
9981 * with 'got send -d'.
9982 * Deleting anything else requires local repository access or Git.
9984 TAILQ_FOREACH(pe, &delete_args, entry) {
9985 const char *branchname = pe->path;
9986 char *s;
9987 struct got_pathlist_entry *new;
9988 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9989 s = strdup(branchname);
9990 if (s == NULL) {
9991 error = got_error_from_errno("strdup");
9992 goto done;
9994 } else {
9995 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9996 error = got_error_from_errno("asprintf");
9997 goto done;
10000 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10001 if (error || new == NULL /* duplicate */)
10002 free(s);
10003 if (error)
10004 goto done;
10005 ndelete_branches++;
10008 if (nbranches == 0 && ndelete_branches == 0) {
10009 struct got_reference *head_ref;
10010 if (worktree)
10011 error = got_ref_open(&head_ref, repo,
10012 got_worktree_get_head_ref_name(worktree), 0);
10013 else
10014 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10015 if (error)
10016 goto done;
10017 if (got_ref_is_symbolic(head_ref)) {
10018 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10019 got_ref_close(head_ref);
10020 if (error)
10021 goto done;
10022 } else
10023 ref = head_ref;
10024 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10025 NULL);
10026 if (error)
10027 goto done;
10028 nbranches++;
10031 if (worktree) {
10032 /* Release work tree lock. */
10033 got_worktree_close(worktree);
10034 worktree = NULL;
10037 if (verbosity >= 0) {
10038 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10039 remote->name, proto, host,
10040 port ? ":" : "", port ? port : "",
10041 *server_path == '/' ? "" : "/", server_path);
10044 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10045 server_path, verbosity);
10046 if (error)
10047 goto done;
10049 memset(&spa, 0, sizeof(spa));
10050 spa.last_scaled_packsize[0] = '\0';
10051 spa.last_p_deltify = -1;
10052 spa.last_p_written = -1;
10053 spa.verbosity = verbosity;
10054 spa.delete_branches = &delete_branches;
10055 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10056 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10057 check_cancelled, NULL);
10058 if (spa.printed_something)
10059 putchar('\n');
10060 if (error)
10061 goto done;
10062 if (!spa.sent_something && verbosity >= 0)
10063 printf("Already up-to-date\n");
10064 done:
10065 if (sendpid > 0) {
10066 if (kill(sendpid, SIGTERM) == -1)
10067 error = got_error_from_errno("kill");
10068 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10069 error = got_error_from_errno("waitpid");
10071 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10072 error = got_error_from_errno("close");
10073 if (repo) {
10074 const struct got_error *close_err = got_repo_close(repo);
10075 if (error == NULL)
10076 error = close_err;
10078 if (worktree)
10079 got_worktree_close(worktree);
10080 if (pack_fds) {
10081 const struct got_error *pack_err =
10082 got_repo_pack_fds_close(pack_fds);
10083 if (error == NULL)
10084 error = pack_err;
10086 if (ref)
10087 got_ref_close(ref);
10088 got_repo_free_remote_repo_data(remote);
10089 free(remote);
10090 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10091 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10092 got_ref_list_free(&all_branches);
10093 got_ref_list_free(&all_tags);
10094 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10095 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10096 free(cwd);
10097 free(repo_path);
10098 free(proto);
10099 free(host);
10100 free(port);
10101 free(server_path);
10102 free(repo_name);
10103 return error;
10107 * Print and if delete is set delete all ref_prefix references.
10108 * If wanted_ref is not NULL, only print or delete this reference.
10110 static const struct got_error *
10111 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10112 const char *wanted_ref, int delete, struct got_worktree *worktree,
10113 struct got_repository *repo)
10115 const struct got_error *err;
10116 struct got_pathlist_head paths;
10117 struct got_reflist_head refs;
10118 struct got_reflist_entry *re;
10119 struct got_reflist_object_id_map *refs_idmap = NULL;
10120 struct got_commit_object *commit = NULL;
10121 struct got_object_id *id = NULL;
10122 const char *header_prefix;
10123 char *uuidstr = NULL;
10124 int found = 0;
10126 TAILQ_INIT(&refs);
10127 TAILQ_INIT(&paths);
10129 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10130 if (err)
10131 goto done;
10133 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10134 if (err)
10135 goto done;
10137 if (worktree != NULL) {
10138 err = got_worktree_get_uuid(&uuidstr, worktree);
10139 if (err)
10140 goto done;
10143 if (wanted_ref) {
10144 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10145 wanted_ref += 11;
10148 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10149 header_prefix = "backout";
10150 else
10151 header_prefix = "cherrypick";
10153 TAILQ_FOREACH(re, &refs, entry) {
10154 const char *refname, *wt;
10156 refname = got_ref_get_name(re->ref);
10158 err = check_cancelled(NULL);
10159 if (err)
10160 goto done;
10162 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10163 refname += prefix_len + 1; /* skip '-' delimiter */
10164 else
10165 continue;
10167 wt = refname;
10169 if (worktree == NULL || strncmp(refname, uuidstr,
10170 GOT_WORKTREE_UUID_STRLEN) == 0)
10171 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10172 else
10173 continue;
10175 err = got_repo_match_object_id(&id, NULL, refname,
10176 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10177 if (err)
10178 goto done;
10180 err = got_object_open_as_commit(&commit, repo, id);
10181 if (err)
10182 goto done;
10184 if (wanted_ref)
10185 found = strncmp(wanted_ref, refname,
10186 strlen(wanted_ref)) == 0;
10187 if (wanted_ref && !found) {
10188 struct got_reflist_head *ci_refs;
10190 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10191 id);
10193 if (ci_refs) {
10194 char *refs_str = NULL;
10195 char const *r = NULL;
10197 err = build_refs_str(&refs_str, ci_refs, id,
10198 repo, 1);
10199 if (err)
10200 goto done;
10202 r = refs_str;
10203 while (r) {
10204 if (strncmp(r, wanted_ref,
10205 strlen(wanted_ref)) == 0) {
10206 found = 1;
10207 break;
10209 r = strchr(r, ' ');
10210 if (r)
10211 ++r;
10213 free(refs_str);
10217 if (wanted_ref == NULL || found) {
10218 if (delete) {
10219 err = got_ref_delete(re->ref, repo);
10220 if (err)
10221 goto done;
10222 printf("Deleted: ");
10223 err = print_commit_oneline(commit, id, repo,
10224 refs_idmap);
10225 } else {
10227 * Print paths modified by commit to help
10228 * associate commits with worktree changes.
10230 err = get_changed_paths(&paths, commit,
10231 repo, NULL);
10232 if (err)
10233 goto done;
10235 err = print_commit(commit, id, repo, NULL,
10236 &paths, NULL, 0, 0, refs_idmap, NULL,
10237 header_prefix);
10238 got_pathlist_free(&paths,
10239 GOT_PATHLIST_FREE_ALL);
10241 if (worktree == NULL)
10242 printf("work tree: %.*s\n\n",
10243 GOT_WORKTREE_UUID_STRLEN, wt);
10245 if (err || found)
10246 goto done;
10249 got_object_commit_close(commit);
10250 commit = NULL;
10251 free(id);
10252 id = NULL;
10255 if (wanted_ref != NULL && !found)
10256 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10258 done:
10259 free(id);
10260 free(uuidstr);
10261 got_ref_list_free(&refs);
10262 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10263 if (refs_idmap)
10264 got_reflist_object_id_map_free(refs_idmap);
10265 if (commit)
10266 got_object_commit_close(commit);
10267 return err;
10271 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10272 * identified by id for log messages to prepopulate the editor on commit.
10274 static const struct got_error *
10275 logmsg_ref(struct got_object_id *id, const char *prefix,
10276 struct got_worktree *worktree, struct got_repository *repo)
10278 const struct got_error *err = NULL;
10279 char *idstr, *ref = NULL, *refname = NULL;
10280 int histedit_in_progress;
10281 int rebase_in_progress, merge_in_progress;
10284 * Silenty refuse to create merge reference if any histedit, merge,
10285 * or rebase operation is in progress.
10287 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10288 worktree);
10289 if (err)
10290 return err;
10291 if (histedit_in_progress)
10292 return NULL;
10294 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10295 if (err)
10296 return err;
10297 if (rebase_in_progress)
10298 return NULL;
10300 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10301 repo);
10302 if (err)
10303 return err;
10304 if (merge_in_progress)
10305 return NULL;
10307 err = got_object_id_str(&idstr, id);
10308 if (err)
10309 return err;
10311 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10312 if (err)
10313 goto done;
10315 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10316 err = got_error_from_errno("asprintf");
10317 goto done;
10320 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10321 -1, repo);
10322 done:
10323 free(ref);
10324 free(idstr);
10325 free(refname);
10326 return err;
10329 __dead static void
10330 usage_cherrypick(void)
10332 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10333 getprogname());
10334 exit(1);
10337 static const struct got_error *
10338 cmd_cherrypick(int argc, char *argv[])
10340 const struct got_error *error = NULL;
10341 struct got_worktree *worktree = NULL;
10342 struct got_repository *repo = NULL;
10343 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10344 struct got_object_id *commit_id = NULL;
10345 struct got_commit_object *commit = NULL;
10346 struct got_object_qid *pid;
10347 int ch, list_refs = 0, remove_refs = 0;
10348 struct got_update_progress_arg upa;
10349 int *pack_fds = NULL;
10351 #ifndef PROFILE
10352 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10353 "unveil", NULL) == -1)
10354 err(1, "pledge");
10355 #endif
10357 while ((ch = getopt(argc, argv, "lX")) != -1) {
10358 switch (ch) {
10359 case 'l':
10360 list_refs = 1;
10361 break;
10362 case 'X':
10363 remove_refs = 1;
10364 break;
10365 default:
10366 usage_cherrypick();
10367 /* NOTREACHED */
10371 argc -= optind;
10372 argv += optind;
10374 if (list_refs || remove_refs) {
10375 if (argc != 0 && argc != 1)
10376 usage_cherrypick();
10377 } else if (argc != 1)
10378 usage_cherrypick();
10379 if (list_refs && remove_refs)
10380 option_conflict('l', 'X');
10382 cwd = getcwd(NULL, 0);
10383 if (cwd == NULL) {
10384 error = got_error_from_errno("getcwd");
10385 goto done;
10388 error = got_repo_pack_fds_open(&pack_fds);
10389 if (error != NULL)
10390 goto done;
10392 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10393 if (error) {
10394 if (list_refs || remove_refs) {
10395 if (error->code != GOT_ERR_NOT_WORKTREE)
10396 goto done;
10397 } else {
10398 if (error->code == GOT_ERR_NOT_WORKTREE)
10399 error = wrap_not_worktree_error(error,
10400 "cherrypick", cwd);
10401 goto done;
10405 error = got_repo_open(&repo,
10406 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10407 NULL, pack_fds);
10408 if (error != NULL)
10409 goto done;
10411 error = apply_unveil(got_repo_get_path(repo), 0,
10412 worktree ? got_worktree_get_root_path(worktree) : NULL);
10413 if (error)
10414 goto done;
10416 if (list_refs || remove_refs) {
10417 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10418 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10419 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10420 goto done;
10423 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10424 if (error != NULL)
10425 goto done;
10427 error = got_repo_match_object_id(&commit_id, NULL,
10428 keyword_idstr != NULL ? keyword_idstr : argv[0],
10429 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10430 if (error)
10431 goto done;
10432 error = got_object_id_str(&commit_id_str, commit_id);
10433 if (error)
10434 goto done;
10436 error = got_object_open_as_commit(&commit, repo, commit_id);
10437 if (error)
10438 goto done;
10439 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10440 memset(&upa, 0, sizeof(upa));
10441 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10442 commit_id, repo, update_progress, &upa, check_cancelled,
10443 NULL);
10444 if (error != NULL)
10445 goto done;
10447 if (upa.did_something) {
10448 error = logmsg_ref(commit_id,
10449 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10450 if (error)
10451 goto done;
10452 printf("Merged commit %s\n", commit_id_str);
10454 print_merge_progress_stats(&upa);
10455 done:
10456 free(cwd);
10457 free(keyword_idstr);
10458 if (commit)
10459 got_object_commit_close(commit);
10460 free(commit_id_str);
10461 if (worktree)
10462 got_worktree_close(worktree);
10463 if (repo) {
10464 const struct got_error *close_err = got_repo_close(repo);
10465 if (error == NULL)
10466 error = close_err;
10468 if (pack_fds) {
10469 const struct got_error *pack_err =
10470 got_repo_pack_fds_close(pack_fds);
10471 if (error == NULL)
10472 error = pack_err;
10475 return error;
10478 __dead static void
10479 usage_backout(void)
10481 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10482 exit(1);
10485 static const struct got_error *
10486 cmd_backout(int argc, char *argv[])
10488 const struct got_error *error = NULL;
10489 struct got_worktree *worktree = NULL;
10490 struct got_repository *repo = NULL;
10491 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10492 struct got_object_id *commit_id = NULL;
10493 struct got_commit_object *commit = NULL;
10494 struct got_object_qid *pid;
10495 int ch, list_refs = 0, remove_refs = 0;
10496 struct got_update_progress_arg upa;
10497 int *pack_fds = NULL;
10499 #ifndef PROFILE
10500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10501 "unveil", NULL) == -1)
10502 err(1, "pledge");
10503 #endif
10505 while ((ch = getopt(argc, argv, "lX")) != -1) {
10506 switch (ch) {
10507 case 'l':
10508 list_refs = 1;
10509 break;
10510 case 'X':
10511 remove_refs = 1;
10512 break;
10513 default:
10514 usage_backout();
10515 /* NOTREACHED */
10519 argc -= optind;
10520 argv += optind;
10522 if (list_refs || remove_refs) {
10523 if (argc != 0 && argc != 1)
10524 usage_backout();
10525 } else if (argc != 1)
10526 usage_backout();
10527 if (list_refs && remove_refs)
10528 option_conflict('l', 'X');
10530 cwd = getcwd(NULL, 0);
10531 if (cwd == NULL) {
10532 error = got_error_from_errno("getcwd");
10533 goto done;
10536 error = got_repo_pack_fds_open(&pack_fds);
10537 if (error != NULL)
10538 goto done;
10540 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10541 if (error) {
10542 if (list_refs || remove_refs) {
10543 if (error->code != GOT_ERR_NOT_WORKTREE)
10544 goto done;
10545 } else {
10546 if (error->code == GOT_ERR_NOT_WORKTREE)
10547 error = wrap_not_worktree_error(error,
10548 "backout", cwd);
10549 goto done;
10553 error = got_repo_open(&repo,
10554 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10555 NULL, pack_fds);
10556 if (error != NULL)
10557 goto done;
10559 error = apply_unveil(got_repo_get_path(repo), 0,
10560 worktree ? got_worktree_get_root_path(worktree) : NULL);
10561 if (error)
10562 goto done;
10564 if (list_refs || remove_refs) {
10565 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10566 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10567 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10568 goto done;
10571 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10572 if (error != NULL)
10573 goto done;
10575 error = got_repo_match_object_id(&commit_id, NULL,
10576 keyword_idstr != NULL ? keyword_idstr : argv[0],
10577 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10578 if (error)
10579 goto done;
10580 error = got_object_id_str(&commit_id_str, commit_id);
10581 if (error)
10582 goto done;
10584 error = got_object_open_as_commit(&commit, repo, commit_id);
10585 if (error)
10586 goto done;
10587 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10588 if (pid == NULL) {
10589 error = got_error(GOT_ERR_ROOT_COMMIT);
10590 goto done;
10593 memset(&upa, 0, sizeof(upa));
10594 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10595 repo, update_progress, &upa, check_cancelled, NULL);
10596 if (error != NULL)
10597 goto done;
10599 if (upa.did_something) {
10600 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10601 worktree, repo);
10602 if (error)
10603 goto done;
10604 printf("Backed out commit %s\n", commit_id_str);
10606 print_merge_progress_stats(&upa);
10607 done:
10608 free(cwd);
10609 free(keyword_idstr);
10610 if (commit)
10611 got_object_commit_close(commit);
10612 free(commit_id_str);
10613 if (worktree)
10614 got_worktree_close(worktree);
10615 if (repo) {
10616 const struct got_error *close_err = got_repo_close(repo);
10617 if (error == NULL)
10618 error = close_err;
10620 if (pack_fds) {
10621 const struct got_error *pack_err =
10622 got_repo_pack_fds_close(pack_fds);
10623 if (error == NULL)
10624 error = pack_err;
10626 return error;
10629 __dead static void
10630 usage_rebase(void)
10632 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10633 exit(1);
10636 static void
10637 trim_logmsg(char *logmsg, int limit)
10639 char *nl;
10640 size_t len;
10642 len = strlen(logmsg);
10643 if (len > limit)
10644 len = limit;
10645 logmsg[len] = '\0';
10646 nl = strchr(logmsg, '\n');
10647 if (nl)
10648 *nl = '\0';
10651 static const struct got_error *
10652 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10654 const struct got_error *err;
10655 char *logmsg0 = NULL;
10656 const char *s;
10658 err = got_object_commit_get_logmsg(&logmsg0, commit);
10659 if (err)
10660 return err;
10662 s = logmsg0;
10663 while (isspace((unsigned char)s[0]))
10664 s++;
10666 *logmsg = strdup(s);
10667 if (*logmsg == NULL) {
10668 err = got_error_from_errno("strdup");
10669 goto done;
10672 trim_logmsg(*logmsg, limit);
10673 done:
10674 free(logmsg0);
10675 return err;
10678 static const struct got_error *
10679 show_rebase_merge_conflict(struct got_object_id *id,
10680 struct got_repository *repo)
10682 const struct got_error *err;
10683 struct got_commit_object *commit = NULL;
10684 char *id_str = NULL, *logmsg = NULL;
10686 err = got_object_open_as_commit(&commit, repo, id);
10687 if (err)
10688 return err;
10690 err = got_object_id_str(&id_str, id);
10691 if (err)
10692 goto done;
10694 id_str[12] = '\0';
10696 err = get_short_logmsg(&logmsg, 42, commit);
10697 if (err)
10698 goto done;
10700 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10701 done:
10702 free(id_str);
10703 got_object_commit_close(commit);
10704 free(logmsg);
10705 return err;
10708 static const struct got_error *
10709 show_rebase_progress(struct got_commit_object *commit,
10710 struct got_object_id *old_id, struct got_object_id *new_id)
10712 const struct got_error *err;
10713 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10715 err = got_object_id_str(&old_id_str, old_id);
10716 if (err)
10717 goto done;
10719 if (new_id) {
10720 err = got_object_id_str(&new_id_str, new_id);
10721 if (err)
10722 goto done;
10725 old_id_str[12] = '\0';
10726 if (new_id_str)
10727 new_id_str[12] = '\0';
10729 err = get_short_logmsg(&logmsg, 42, commit);
10730 if (err)
10731 goto done;
10733 printf("%s -> %s: %s\n", old_id_str,
10734 new_id_str ? new_id_str : "no-op change", logmsg);
10735 done:
10736 free(old_id_str);
10737 free(new_id_str);
10738 free(logmsg);
10739 return err;
10742 static const struct got_error *
10743 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10744 struct got_reference *branch, struct got_reference *tmp_branch,
10745 struct got_repository *repo, int create_backup)
10747 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10748 return got_worktree_rebase_complete(worktree, fileindex,
10749 tmp_branch, branch, repo, create_backup);
10752 static const struct got_error *
10753 rebase_commit(struct got_pathlist_head *merged_paths,
10754 struct got_worktree *worktree, struct got_fileindex *fileindex,
10755 struct got_reference *tmp_branch, const char *committer,
10756 struct got_object_id *commit_id, int allow_conflict,
10757 struct got_repository *repo)
10759 const struct got_error *error;
10760 struct got_commit_object *commit;
10761 struct got_object_id *new_commit_id;
10763 error = got_object_open_as_commit(&commit, repo, commit_id);
10764 if (error)
10765 return error;
10767 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10768 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10769 allow_conflict, repo);
10770 if (error) {
10771 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10772 goto done;
10773 error = show_rebase_progress(commit, commit_id, NULL);
10774 } else {
10775 error = show_rebase_progress(commit, commit_id, new_commit_id);
10776 free(new_commit_id);
10778 done:
10779 got_object_commit_close(commit);
10780 return error;
10783 struct check_path_prefix_arg {
10784 const char *path_prefix;
10785 size_t len;
10786 int errcode;
10789 static const struct got_error *
10790 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10791 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10792 struct got_object_id *id1, struct got_object_id *id2,
10793 const char *path1, const char *path2,
10794 mode_t mode1, mode_t mode2, struct got_repository *repo)
10796 struct check_path_prefix_arg *a = arg;
10798 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10799 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10800 return got_error(a->errcode);
10802 return NULL;
10805 static const struct got_error *
10806 check_path_prefix(struct got_object_id *parent_id,
10807 struct got_object_id *commit_id, const char *path_prefix,
10808 int errcode, struct got_repository *repo)
10810 const struct got_error *err;
10811 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10812 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10813 struct check_path_prefix_arg cpp_arg;
10815 if (got_path_is_root_dir(path_prefix))
10816 return NULL;
10818 err = got_object_open_as_commit(&commit, repo, commit_id);
10819 if (err)
10820 goto done;
10822 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10823 if (err)
10824 goto done;
10826 err = got_object_open_as_tree(&tree1, repo,
10827 got_object_commit_get_tree_id(parent_commit));
10828 if (err)
10829 goto done;
10831 err = got_object_open_as_tree(&tree2, repo,
10832 got_object_commit_get_tree_id(commit));
10833 if (err)
10834 goto done;
10836 cpp_arg.path_prefix = path_prefix;
10837 while (cpp_arg.path_prefix[0] == '/')
10838 cpp_arg.path_prefix++;
10839 cpp_arg.len = strlen(cpp_arg.path_prefix);
10840 cpp_arg.errcode = errcode;
10841 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10842 check_path_prefix_in_diff, &cpp_arg, 0);
10843 done:
10844 if (tree1)
10845 got_object_tree_close(tree1);
10846 if (tree2)
10847 got_object_tree_close(tree2);
10848 if (commit)
10849 got_object_commit_close(commit);
10850 if (parent_commit)
10851 got_object_commit_close(parent_commit);
10852 return err;
10855 static const struct got_error *
10856 collect_commits(struct got_object_id_queue *commits,
10857 struct got_object_id *initial_commit_id,
10858 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10859 const char *path_prefix, int path_prefix_errcode,
10860 struct got_repository *repo)
10862 const struct got_error *err = NULL;
10863 struct got_commit_graph *graph = NULL;
10864 struct got_object_id parent_id, commit_id;
10865 struct got_object_qid *qid;
10867 err = got_commit_graph_open(&graph, "/", 1);
10868 if (err)
10869 return err;
10871 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10872 check_cancelled, NULL);
10873 if (err)
10874 goto done;
10876 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10877 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10878 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10879 check_cancelled, NULL);
10880 if (err) {
10881 if (err->code == GOT_ERR_ITER_COMPLETED) {
10882 err = got_error_msg(GOT_ERR_ANCESTRY,
10883 "ran out of commits to rebase before "
10884 "youngest common ancestor commit has "
10885 "been reached?!?");
10887 goto done;
10888 } else {
10889 err = check_path_prefix(&parent_id, &commit_id,
10890 path_prefix, path_prefix_errcode, repo);
10891 if (err)
10892 goto done;
10894 err = got_object_qid_alloc(&qid, &commit_id);
10895 if (err)
10896 goto done;
10897 STAILQ_INSERT_HEAD(commits, qid, entry);
10899 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10902 done:
10903 got_commit_graph_close(graph);
10904 return err;
10907 static const struct got_error *
10908 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10910 const struct got_error *err = NULL;
10911 time_t committer_time;
10912 struct tm tm;
10913 char datebuf[11]; /* YYYY-MM-DD + NUL */
10914 char *author0 = NULL, *author, *smallerthan;
10915 char *logmsg0 = NULL, *logmsg, *newline;
10917 committer_time = got_object_commit_get_committer_time(commit);
10918 if (gmtime_r(&committer_time, &tm) == NULL)
10919 return got_error_from_errno("gmtime_r");
10920 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10921 return got_error(GOT_ERR_NO_SPACE);
10923 author0 = strdup(got_object_commit_get_author(commit));
10924 if (author0 == NULL)
10925 return got_error_from_errno("strdup");
10926 author = author0;
10927 smallerthan = strchr(author, '<');
10928 if (smallerthan && smallerthan[1] != '\0')
10929 author = smallerthan + 1;
10930 author[strcspn(author, "@>")] = '\0';
10932 err = got_object_commit_get_logmsg(&logmsg0, commit);
10933 if (err)
10934 goto done;
10935 logmsg = logmsg0;
10936 while (*logmsg == '\n')
10937 logmsg++;
10938 newline = strchr(logmsg, '\n');
10939 if (newline)
10940 *newline = '\0';
10942 if (asprintf(brief_str, "%s %s %s",
10943 datebuf, author, logmsg) == -1)
10944 err = got_error_from_errno("asprintf");
10945 done:
10946 free(author0);
10947 free(logmsg0);
10948 return err;
10951 static const struct got_error *
10952 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10953 struct got_repository *repo)
10955 const struct got_error *err;
10956 char *id_str;
10958 err = got_object_id_str(&id_str, id);
10959 if (err)
10960 return err;
10962 err = got_ref_delete(ref, repo);
10963 if (err)
10964 goto done;
10966 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10967 done:
10968 free(id_str);
10969 return err;
10972 static const struct got_error *
10973 print_backup_ref(const char *branch_name, const char *new_id_str,
10974 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10975 struct got_reflist_object_id_map *refs_idmap,
10976 struct got_repository *repo)
10978 const struct got_error *err = NULL;
10979 struct got_reflist_head *refs;
10980 char *refs_str = NULL;
10981 struct got_object_id *new_commit_id = NULL;
10982 struct got_commit_object *new_commit = NULL;
10983 char *new_commit_brief_str = NULL;
10984 struct got_object_id *yca_id = NULL;
10985 struct got_commit_object *yca_commit = NULL;
10986 char *yca_id_str = NULL, *yca_brief_str = NULL;
10987 char *custom_refs_str;
10989 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10990 return got_error_from_errno("asprintf");
10992 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10993 0, 0, refs_idmap, custom_refs_str, NULL);
10994 if (err)
10995 goto done;
10997 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10998 if (err)
10999 goto done;
11001 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11002 if (refs) {
11003 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11004 if (err)
11005 goto done;
11008 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11009 if (err)
11010 goto done;
11012 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11013 if (err)
11014 goto done;
11016 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11017 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11018 if (err)
11019 goto done;
11021 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11022 refs_str ? " (" : "", refs_str ? refs_str : "",
11023 refs_str ? ")" : "", new_commit_brief_str);
11024 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11025 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11026 free(refs_str);
11027 refs_str = NULL;
11029 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11030 if (err)
11031 goto done;
11033 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11034 if (err)
11035 goto done;
11037 err = got_object_id_str(&yca_id_str, yca_id);
11038 if (err)
11039 goto done;
11041 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11042 if (refs) {
11043 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11044 if (err)
11045 goto done;
11047 printf("history forked at %s%s%s%s\n %s\n",
11048 yca_id_str,
11049 refs_str ? " (" : "", refs_str ? refs_str : "",
11050 refs_str ? ")" : "", yca_brief_str);
11052 done:
11053 free(custom_refs_str);
11054 free(new_commit_id);
11055 free(refs_str);
11056 free(yca_id);
11057 free(yca_id_str);
11058 free(yca_brief_str);
11059 if (new_commit)
11060 got_object_commit_close(new_commit);
11061 if (yca_commit)
11062 got_object_commit_close(yca_commit);
11064 return err;
11067 static const struct got_error *
11068 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11069 struct got_repository *repo)
11071 const struct got_error *err;
11072 struct got_reflist_head refs;
11073 struct got_reflist_entry *re;
11074 char *uuidstr = NULL;
11075 static char msg[160];
11077 TAILQ_INIT(&refs);
11079 err = got_worktree_get_uuid(&uuidstr, worktree);
11080 if (err)
11081 goto done;
11083 err = got_ref_list(&refs, repo, "refs/got/worktree",
11084 got_ref_cmp_by_name, repo);
11085 if (err)
11086 goto done;
11088 TAILQ_FOREACH(re, &refs, entry) {
11089 const char *cmd, *refname, *type;
11091 refname = got_ref_get_name(re->ref);
11093 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11094 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11095 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11096 cmd = "cherrypick";
11097 type = "cherrypicked";
11098 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11099 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11100 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11101 cmd = "backout";
11102 type = "backed-out";
11103 } else
11104 continue;
11106 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11107 continue;
11109 snprintf(msg, sizeof(msg),
11110 "work tree has references created by %s commits which "
11111 "must be removed with 'got %s -X' before running the %s "
11112 "command", type, cmd, caller);
11113 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11114 goto done;
11117 done:
11118 free(uuidstr);
11119 got_ref_list_free(&refs);
11120 return err;
11123 static const struct got_error *
11124 process_backup_refs(const char *backup_ref_prefix,
11125 const char *wanted_branch_name,
11126 int delete, struct got_repository *repo)
11128 const struct got_error *err;
11129 struct got_reflist_head refs, backup_refs;
11130 struct got_reflist_entry *re;
11131 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11132 struct got_object_id *old_commit_id = NULL;
11133 char *branch_name = NULL;
11134 struct got_commit_object *old_commit = NULL;
11135 struct got_reflist_object_id_map *refs_idmap = NULL;
11136 int wanted_branch_found = 0;
11138 TAILQ_INIT(&refs);
11139 TAILQ_INIT(&backup_refs);
11141 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11142 if (err)
11143 return err;
11145 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11146 if (err)
11147 goto done;
11149 if (wanted_branch_name) {
11150 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11151 wanted_branch_name += 11;
11154 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11155 got_ref_cmp_by_commit_timestamp_descending, repo);
11156 if (err)
11157 goto done;
11159 TAILQ_FOREACH(re, &backup_refs, entry) {
11160 const char *refname = got_ref_get_name(re->ref);
11161 char *slash;
11163 err = check_cancelled(NULL);
11164 if (err)
11165 break;
11167 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11168 if (err)
11169 break;
11171 err = got_object_open_as_commit(&old_commit, repo,
11172 old_commit_id);
11173 if (err)
11174 break;
11176 if (strncmp(backup_ref_prefix, refname,
11177 backup_ref_prefix_len) == 0)
11178 refname += backup_ref_prefix_len;
11180 while (refname[0] == '/')
11181 refname++;
11183 branch_name = strdup(refname);
11184 if (branch_name == NULL) {
11185 err = got_error_from_errno("strdup");
11186 break;
11188 slash = strrchr(branch_name, '/');
11189 if (slash) {
11190 *slash = '\0';
11191 refname += strlen(branch_name) + 1;
11194 if (wanted_branch_name == NULL ||
11195 strcmp(wanted_branch_name, branch_name) == 0) {
11196 wanted_branch_found = 1;
11197 if (delete) {
11198 err = delete_backup_ref(re->ref,
11199 old_commit_id, repo);
11200 } else {
11201 err = print_backup_ref(branch_name, refname,
11202 old_commit_id, old_commit, refs_idmap,
11203 repo);
11205 if (err)
11206 break;
11209 free(old_commit_id);
11210 old_commit_id = NULL;
11211 free(branch_name);
11212 branch_name = NULL;
11213 got_object_commit_close(old_commit);
11214 old_commit = NULL;
11217 if (wanted_branch_name && !wanted_branch_found) {
11218 err = got_error_fmt(GOT_ERR_NOT_REF,
11219 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11221 done:
11222 if (refs_idmap)
11223 got_reflist_object_id_map_free(refs_idmap);
11224 got_ref_list_free(&refs);
11225 got_ref_list_free(&backup_refs);
11226 free(old_commit_id);
11227 free(branch_name);
11228 if (old_commit)
11229 got_object_commit_close(old_commit);
11230 return err;
11233 static const struct got_error *
11234 abort_progress(void *arg, unsigned char status, const char *path)
11237 * Unversioned files should not clutter progress output when
11238 * an operation is aborted.
11240 if (status == GOT_STATUS_UNVERSIONED)
11241 return NULL;
11243 return update_progress(arg, status, path);
11246 static const struct got_error *
11247 find_merge_commit_yca(struct got_object_id **new_yca_id,
11248 struct got_object_id *branch_head_commit_id,
11249 struct got_object_id *yca_id,
11250 struct got_object_id *base_commit_id,
11251 struct got_repository *repo)
11253 const struct got_error *err = NULL;
11254 struct got_commit_graph *graph = NULL;
11255 struct got_commit_object *commit = NULL;
11257 *new_yca_id = NULL;
11259 err = got_commit_graph_open(&graph, "/", 1);
11260 if (err)
11261 return err;
11263 err = got_commit_graph_bfsort(graph, base_commit_id,
11264 repo, check_cancelled, NULL);
11265 if (err)
11266 goto done;
11268 for (;;) {
11269 struct got_object_id id;
11271 err = got_commit_graph_iter_next(&id, graph, repo,
11272 check_cancelled, NULL);
11273 if (err) {
11274 if (err->code == GOT_ERR_ITER_COMPLETED)
11275 err = NULL;
11276 break;
11279 err = got_object_open_as_commit(&commit, repo, &id);
11280 if (err)
11281 break;
11283 if (got_object_commit_get_nparents(commit) > 1) {
11284 /* Search for a better YCA using toposort. */
11285 err = got_commit_graph_find_youngest_common_ancestor(
11286 new_yca_id, base_commit_id, branch_head_commit_id,
11287 0, 1, repo, check_cancelled, NULL);
11288 break;
11291 if (got_object_id_cmp(&id, yca_id) == 0)
11292 break;
11293 got_object_commit_close(commit);
11294 commit = NULL;
11296 done:
11297 got_commit_graph_close(graph);
11298 if (commit)
11299 got_object_commit_close(commit);
11300 return err;
11303 static const struct got_error *
11304 cmd_rebase(int argc, char *argv[])
11306 const struct got_error *error = NULL;
11307 struct got_worktree *worktree = NULL;
11308 struct got_repository *repo = NULL;
11309 struct got_fileindex *fileindex = NULL;
11310 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11311 struct got_reference *branch = NULL;
11312 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11313 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11314 struct got_object_id *resume_commit_id = NULL;
11315 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11316 struct got_object_id *head_commit_id = NULL;
11317 struct got_reference *head_ref = NULL;
11318 struct got_commit_object *commit = NULL;
11319 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11320 int histedit_in_progress = 0, merge_in_progress = 0;
11321 int create_backup = 1, list_backups = 0, delete_backups = 0;
11322 int allow_conflict = 0;
11323 struct got_object_id_queue commits;
11324 struct got_pathlist_head merged_paths;
11325 const struct got_object_id_queue *parent_ids;
11326 struct got_object_qid *qid, *pid;
11327 struct got_update_progress_arg upa;
11328 int *pack_fds = NULL;
11330 STAILQ_INIT(&commits);
11331 TAILQ_INIT(&merged_paths);
11332 memset(&upa, 0, sizeof(upa));
11334 #ifndef PROFILE
11335 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11336 "unveil", NULL) == -1)
11337 err(1, "pledge");
11338 #endif
11340 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11341 switch (ch) {
11342 case 'a':
11343 abort_rebase = 1;
11344 break;
11345 case 'C':
11346 allow_conflict = 1;
11347 break;
11348 case 'c':
11349 continue_rebase = 1;
11350 break;
11351 case 'l':
11352 list_backups = 1;
11353 break;
11354 case 'X':
11355 delete_backups = 1;
11356 break;
11357 default:
11358 usage_rebase();
11359 /* NOTREACHED */
11363 argc -= optind;
11364 argv += optind;
11366 if (list_backups) {
11367 if (abort_rebase)
11368 option_conflict('l', 'a');
11369 if (allow_conflict)
11370 option_conflict('l', 'C');
11371 if (continue_rebase)
11372 option_conflict('l', 'c');
11373 if (delete_backups)
11374 option_conflict('l', 'X');
11375 if (argc != 0 && argc != 1)
11376 usage_rebase();
11377 } else if (delete_backups) {
11378 if (abort_rebase)
11379 option_conflict('X', 'a');
11380 if (allow_conflict)
11381 option_conflict('X', 'C');
11382 if (continue_rebase)
11383 option_conflict('X', 'c');
11384 if (list_backups)
11385 option_conflict('l', 'X');
11386 if (argc != 0 && argc != 1)
11387 usage_rebase();
11388 } else if (allow_conflict) {
11389 if (abort_rebase)
11390 option_conflict('C', 'a');
11391 if (!continue_rebase)
11392 errx(1, "-C option requires -c");
11393 } else {
11394 if (abort_rebase && continue_rebase)
11395 usage_rebase();
11396 else if (abort_rebase || continue_rebase) {
11397 if (argc != 0)
11398 usage_rebase();
11399 } else if (argc != 1)
11400 usage_rebase();
11403 cwd = getcwd(NULL, 0);
11404 if (cwd == NULL) {
11405 error = got_error_from_errno("getcwd");
11406 goto done;
11409 error = got_repo_pack_fds_open(&pack_fds);
11410 if (error != NULL)
11411 goto done;
11413 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11414 if (error) {
11415 if (list_backups || delete_backups) {
11416 if (error->code != GOT_ERR_NOT_WORKTREE)
11417 goto done;
11418 } else {
11419 if (error->code == GOT_ERR_NOT_WORKTREE)
11420 error = wrap_not_worktree_error(error,
11421 "rebase", cwd);
11422 goto done;
11426 error = get_gitconfig_path(&gitconfig_path);
11427 if (error)
11428 goto done;
11429 error = got_repo_open(&repo,
11430 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11431 gitconfig_path, pack_fds);
11432 if (error != NULL)
11433 goto done;
11435 if (worktree != NULL && !list_backups && !delete_backups) {
11436 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11437 if (error)
11438 goto done;
11441 error = get_author(&committer, repo, worktree);
11442 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11443 goto done;
11445 error = apply_unveil(got_repo_get_path(repo), 0,
11446 worktree ? got_worktree_get_root_path(worktree) : NULL);
11447 if (error)
11448 goto done;
11450 if (list_backups || delete_backups) {
11451 error = process_backup_refs(
11452 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11453 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11454 goto done; /* nothing else to do */
11457 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11458 worktree);
11459 if (error)
11460 goto done;
11461 if (histedit_in_progress) {
11462 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11463 goto done;
11466 error = got_worktree_merge_in_progress(&merge_in_progress,
11467 worktree, repo);
11468 if (error)
11469 goto done;
11470 if (merge_in_progress) {
11471 error = got_error(GOT_ERR_MERGE_BUSY);
11472 goto done;
11475 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11476 if (error)
11477 goto done;
11479 if (abort_rebase) {
11480 if (!rebase_in_progress) {
11481 error = got_error(GOT_ERR_NOT_REBASING);
11482 goto done;
11484 error = got_worktree_rebase_continue(&resume_commit_id,
11485 &new_base_branch, &tmp_branch, &branch, &fileindex,
11486 worktree, repo);
11487 if (error)
11488 goto done;
11489 printf("Switching work tree to %s\n",
11490 got_ref_get_symref_target(new_base_branch));
11491 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11492 new_base_branch, abort_progress, &upa);
11493 if (error)
11494 goto done;
11495 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11496 print_merge_progress_stats(&upa);
11497 goto done; /* nothing else to do */
11500 if (continue_rebase) {
11501 if (!rebase_in_progress) {
11502 error = got_error(GOT_ERR_NOT_REBASING);
11503 goto done;
11505 error = got_worktree_rebase_continue(&resume_commit_id,
11506 &new_base_branch, &tmp_branch, &branch, &fileindex,
11507 worktree, repo);
11508 if (error)
11509 goto done;
11511 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11512 committer, resume_commit_id, allow_conflict, repo);
11513 if (error)
11514 goto done;
11516 yca_id = got_object_id_dup(resume_commit_id);
11517 if (yca_id == NULL) {
11518 error = got_error_from_errno("got_object_id_dup");
11519 goto done;
11521 } else {
11522 error = got_ref_open(&branch, repo, argv[0], 0);
11523 if (error != NULL)
11524 goto done;
11525 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11526 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11527 "will not rebase a branch which lives outside "
11528 "the \"refs/heads/\" reference namespace");
11529 goto done;
11533 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11534 if (error)
11535 goto done;
11537 if (!continue_rebase) {
11538 struct got_object_id *base_commit_id;
11540 error = got_ref_open(&head_ref, repo,
11541 got_worktree_get_head_ref_name(worktree), 0);
11542 if (error)
11543 goto done;
11544 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11545 if (error)
11546 goto done;
11547 base_commit_id = got_worktree_get_base_commit_id(worktree);
11548 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11549 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11550 goto done;
11553 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11554 base_commit_id, branch_head_commit_id, 1, 0,
11555 repo, check_cancelled, NULL);
11556 if (error) {
11557 if (error->code == GOT_ERR_ANCESTRY) {
11558 error = got_error_msg(GOT_ERR_ANCESTRY,
11559 "specified branch shares no common "
11560 "ancestry with work tree's branch");
11562 goto done;
11566 * If a merge commit appears between the new base branch tip
11567 * and a YCA found via first-parent traversal then we might
11568 * find a better YCA using topologically sorted commits.
11570 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11571 struct got_object_id *better_yca_id;
11572 error = find_merge_commit_yca(&better_yca_id,
11573 branch_head_commit_id, yca_id,
11574 base_commit_id, repo);
11575 if (error)
11576 goto done;
11577 if (better_yca_id) {
11578 free(yca_id);
11579 yca_id = better_yca_id;
11583 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11584 struct got_pathlist_head paths;
11585 printf("%s is already based on %s\n",
11586 got_ref_get_name(branch),
11587 got_worktree_get_head_ref_name(worktree));
11588 error = switch_head_ref(branch, branch_head_commit_id,
11589 worktree, repo);
11590 if (error)
11591 goto done;
11592 error = got_worktree_set_base_commit_id(worktree, repo,
11593 branch_head_commit_id);
11594 if (error)
11595 goto done;
11596 TAILQ_INIT(&paths);
11597 error = got_pathlist_append(&paths, "", NULL);
11598 if (error)
11599 goto done;
11600 error = got_worktree_checkout_files(worktree,
11601 &paths, repo, update_progress, &upa,
11602 check_cancelled, NULL);
11603 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11604 if (error)
11605 goto done;
11606 if (upa.did_something) {
11607 char *id_str;
11608 error = got_object_id_str(&id_str,
11609 branch_head_commit_id);
11610 if (error)
11611 goto done;
11612 printf("Updated to %s: %s\n",
11613 got_worktree_get_head_ref_name(worktree),
11614 id_str);
11615 free(id_str);
11616 } else
11617 printf("Already up-to-date\n");
11618 print_update_progress_stats(&upa);
11619 goto done;
11623 commit_id = branch_head_commit_id;
11624 error = got_object_open_as_commit(&commit, repo, commit_id);
11625 if (error)
11626 goto done;
11628 parent_ids = got_object_commit_get_parent_ids(commit);
11629 pid = STAILQ_FIRST(parent_ids);
11630 if (pid) {
11631 error = collect_commits(&commits, commit_id, &pid->id,
11632 yca_id, got_worktree_get_path_prefix(worktree),
11633 GOT_ERR_REBASE_PATH, repo);
11634 if (error)
11635 goto done;
11638 got_object_commit_close(commit);
11639 commit = NULL;
11641 if (!continue_rebase) {
11642 error = got_worktree_rebase_prepare(&new_base_branch,
11643 &tmp_branch, &fileindex, worktree, branch, repo);
11644 if (error)
11645 goto done;
11648 if (STAILQ_EMPTY(&commits)) {
11649 if (continue_rebase) {
11650 error = rebase_complete(worktree, fileindex,
11651 branch, tmp_branch, repo, create_backup);
11652 goto done;
11653 } else {
11654 /* Fast-forward the reference of the branch. */
11655 struct got_object_id *new_head_commit_id;
11656 char *id_str;
11657 error = got_ref_resolve(&new_head_commit_id, repo,
11658 new_base_branch);
11659 if (error)
11660 goto done;
11661 error = got_object_id_str(&id_str, new_head_commit_id);
11662 if (error)
11663 goto done;
11664 printf("Forwarding %s to commit %s\n",
11665 got_ref_get_name(branch), id_str);
11666 free(id_str);
11667 error = got_ref_change_ref(branch,
11668 new_head_commit_id);
11669 if (error)
11670 goto done;
11671 /* No backup needed since objects did not change. */
11672 create_backup = 0;
11676 pid = NULL;
11677 STAILQ_FOREACH(qid, &commits, entry) {
11679 commit_id = &qid->id;
11680 parent_id = pid ? &pid->id : yca_id;
11681 pid = qid;
11683 memset(&upa, 0, sizeof(upa));
11684 error = got_worktree_rebase_merge_files(&merged_paths,
11685 worktree, fileindex, parent_id, commit_id, repo,
11686 update_progress, &upa, check_cancelled, NULL);
11687 if (error)
11688 goto done;
11690 print_merge_progress_stats(&upa);
11691 if (upa.conflicts > 0 || upa.missing > 0 ||
11692 upa.not_deleted > 0 || upa.unversioned > 0) {
11693 if (upa.conflicts > 0) {
11694 error = show_rebase_merge_conflict(&qid->id,
11695 repo);
11696 if (error)
11697 goto done;
11699 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11700 break;
11703 error = rebase_commit(&merged_paths, worktree, fileindex,
11704 tmp_branch, committer, commit_id, 0, repo);
11705 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11706 if (error)
11707 goto done;
11710 if (upa.conflicts > 0 || upa.missing > 0 ||
11711 upa.not_deleted > 0 || upa.unversioned > 0) {
11712 error = got_worktree_rebase_postpone(worktree, fileindex);
11713 if (error)
11714 goto done;
11715 if (upa.conflicts > 0 && upa.missing == 0 &&
11716 upa.not_deleted == 0 && upa.unversioned == 0) {
11717 error = got_error_msg(GOT_ERR_CONFLICTS,
11718 "conflicts must be resolved before rebasing "
11719 "can continue");
11720 } else if (upa.conflicts > 0) {
11721 error = got_error_msg(GOT_ERR_CONFLICTS,
11722 "conflicts must be resolved before rebasing "
11723 "can continue; changes destined for some "
11724 "files were not yet merged and should be "
11725 "merged manually if required before the "
11726 "rebase operation is continued");
11727 } else {
11728 error = got_error_msg(GOT_ERR_CONFLICTS,
11729 "changes destined for some files were not "
11730 "yet merged and should be merged manually "
11731 "if required before the rebase operation "
11732 "is continued");
11734 } else
11735 error = rebase_complete(worktree, fileindex, branch,
11736 tmp_branch, repo, create_backup);
11737 done:
11738 free(cwd);
11739 free(committer);
11740 free(gitconfig_path);
11741 got_object_id_queue_free(&commits);
11742 free(branch_head_commit_id);
11743 free(resume_commit_id);
11744 free(head_commit_id);
11745 free(yca_id);
11746 if (commit)
11747 got_object_commit_close(commit);
11748 if (branch)
11749 got_ref_close(branch);
11750 if (new_base_branch)
11751 got_ref_close(new_base_branch);
11752 if (tmp_branch)
11753 got_ref_close(tmp_branch);
11754 if (head_ref)
11755 got_ref_close(head_ref);
11756 if (worktree)
11757 got_worktree_close(worktree);
11758 if (repo) {
11759 const struct got_error *close_err = got_repo_close(repo);
11760 if (error == NULL)
11761 error = close_err;
11763 if (pack_fds) {
11764 const struct got_error *pack_err =
11765 got_repo_pack_fds_close(pack_fds);
11766 if (error == NULL)
11767 error = pack_err;
11769 return error;
11772 __dead static void
11773 usage_histedit(void)
11775 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11776 "[branch]\n", getprogname());
11777 exit(1);
11780 #define GOT_HISTEDIT_PICK 'p'
11781 #define GOT_HISTEDIT_EDIT 'e'
11782 #define GOT_HISTEDIT_FOLD 'f'
11783 #define GOT_HISTEDIT_DROP 'd'
11784 #define GOT_HISTEDIT_MESG 'm'
11786 static const struct got_histedit_cmd {
11787 unsigned char code;
11788 const char *name;
11789 const char *desc;
11790 } got_histedit_cmds[] = {
11791 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11792 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11793 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11794 "be used" },
11795 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11796 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11799 struct got_histedit_list_entry {
11800 TAILQ_ENTRY(got_histedit_list_entry) entry;
11801 struct got_object_id *commit_id;
11802 const struct got_histedit_cmd *cmd;
11803 char *logmsg;
11805 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11807 static const struct got_error *
11808 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11809 FILE *f, struct got_repository *repo)
11811 const struct got_error *err = NULL;
11812 char *logmsg = NULL, *id_str = NULL;
11813 struct got_commit_object *commit = NULL;
11814 int n;
11816 err = got_object_open_as_commit(&commit, repo, commit_id);
11817 if (err)
11818 goto done;
11820 err = get_short_logmsg(&logmsg, 34, commit);
11821 if (err)
11822 goto done;
11824 err = got_object_id_str(&id_str, commit_id);
11825 if (err)
11826 goto done;
11828 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11829 if (n < 0)
11830 err = got_ferror(f, GOT_ERR_IO);
11831 done:
11832 if (commit)
11833 got_object_commit_close(commit);
11834 free(id_str);
11835 free(logmsg);
11836 return err;
11839 static const struct got_error *
11840 histedit_write_commit_list(struct got_object_id_queue *commits,
11841 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11842 int edit_only, struct got_repository *repo)
11844 const struct got_error *err = NULL;
11845 struct got_object_qid *qid;
11846 const char *histedit_cmd = NULL;
11848 if (STAILQ_EMPTY(commits))
11849 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11851 STAILQ_FOREACH(qid, commits, entry) {
11852 histedit_cmd = got_histedit_cmds[0].name;
11853 if (drop_only)
11854 histedit_cmd = "drop";
11855 else if (edit_only)
11856 histedit_cmd = "edit";
11857 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11858 histedit_cmd = "fold";
11859 else if (edit_logmsg_only)
11860 histedit_cmd = "mesg";
11861 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11862 if (err)
11863 break;
11866 return err;
11869 static const struct got_error *
11870 write_cmd_list(FILE *f, const char *branch_name,
11871 struct got_object_id_queue *commits)
11873 const struct got_error *err = NULL;
11874 size_t i;
11875 int n;
11876 char *id_str;
11877 struct got_object_qid *qid;
11879 qid = STAILQ_FIRST(commits);
11880 err = got_object_id_str(&id_str, &qid->id);
11881 if (err)
11882 return err;
11884 n = fprintf(f,
11885 "# Editing the history of branch '%s' starting at\n"
11886 "# commit %s\n"
11887 "# Commits will be processed in order from top to "
11888 "bottom of this file.\n", branch_name, id_str);
11889 if (n < 0) {
11890 err = got_ferror(f, GOT_ERR_IO);
11891 goto done;
11894 n = fprintf(f, "# Available histedit commands:\n");
11895 if (n < 0) {
11896 err = got_ferror(f, GOT_ERR_IO);
11897 goto done;
11900 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11901 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11902 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11903 cmd->desc);
11904 if (n < 0) {
11905 err = got_ferror(f, GOT_ERR_IO);
11906 break;
11909 done:
11910 free(id_str);
11911 return err;
11914 static const struct got_error *
11915 histedit_syntax_error(int lineno)
11917 static char msg[42];
11918 int ret;
11920 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11921 lineno);
11922 if (ret < 0 || (size_t)ret >= sizeof(msg))
11923 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11925 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11928 static const struct got_error *
11929 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11930 char *logmsg, struct got_repository *repo)
11932 const struct got_error *err;
11933 struct got_commit_object *folded_commit = NULL;
11934 char *id_str, *folded_logmsg = NULL;
11936 err = got_object_id_str(&id_str, hle->commit_id);
11937 if (err)
11938 return err;
11940 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11941 if (err)
11942 goto done;
11944 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11945 if (err)
11946 goto done;
11947 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11948 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11949 folded_logmsg) == -1) {
11950 err = got_error_from_errno("asprintf");
11952 done:
11953 if (folded_commit)
11954 got_object_commit_close(folded_commit);
11955 free(id_str);
11956 free(folded_logmsg);
11957 return err;
11960 static struct got_histedit_list_entry *
11961 get_folded_commits(struct got_histedit_list_entry *hle)
11963 struct got_histedit_list_entry *prev, *folded = NULL;
11965 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11966 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11967 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11968 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11969 folded = prev;
11970 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11973 return folded;
11976 static const struct got_error *
11977 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11978 const char *editor, struct got_repository *repo)
11980 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11981 char *logmsg = NULL, *new_msg = NULL;
11982 const struct got_error *err = NULL;
11983 struct got_commit_object *commit = NULL;
11984 int logmsg_len;
11985 int fd = -1;
11986 struct got_histedit_list_entry *folded = NULL;
11988 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11989 if (err)
11990 return err;
11992 folded = get_folded_commits(hle);
11993 if (folded) {
11994 while (folded != hle) {
11995 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11996 folded = TAILQ_NEXT(folded, entry);
11997 continue;
11999 err = append_folded_commit_msg(&new_msg, folded,
12000 logmsg, repo);
12001 if (err)
12002 goto done;
12003 free(logmsg);
12004 logmsg = new_msg;
12005 folded = TAILQ_NEXT(folded, entry);
12009 err = got_object_id_str(&id_str, hle->commit_id);
12010 if (err)
12011 goto done;
12012 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12013 if (err)
12014 goto done;
12015 logmsg_len = asprintf(&new_msg,
12016 "%s\n# original log message of commit %s: %s",
12017 logmsg ? logmsg : "", id_str, orig_logmsg);
12018 if (logmsg_len == -1) {
12019 err = got_error_from_errno("asprintf");
12020 goto done;
12022 free(logmsg);
12023 logmsg = new_msg;
12025 err = got_object_id_str(&id_str, hle->commit_id);
12026 if (err)
12027 goto done;
12029 err = got_opentemp_named_fd(&logmsg_path, &fd,
12030 GOT_TMPDIR_STR "/got-logmsg", "");
12031 if (err)
12032 goto done;
12034 if (write(fd, logmsg, logmsg_len) == -1) {
12035 err = got_error_from_errno2("write", logmsg_path);
12036 goto done;
12038 if (close(fd) == -1) {
12039 err = got_error_from_errno2("close", logmsg_path);
12040 goto done;
12042 fd = -1;
12044 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12045 logmsg_len, 0);
12046 if (err) {
12047 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12048 goto done;
12049 err = NULL;
12050 hle->logmsg = strdup(new_msg);
12051 if (hle->logmsg == NULL)
12052 err = got_error_from_errno("strdup");
12054 done:
12055 if (fd != -1 && close(fd) == -1 && err == NULL)
12056 err = got_error_from_errno2("close", logmsg_path);
12057 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12058 err = got_error_from_errno2("unlink", logmsg_path);
12059 free(logmsg_path);
12060 free(logmsg);
12061 free(orig_logmsg);
12062 if (commit)
12063 got_object_commit_close(commit);
12064 return err;
12067 static const struct got_error *
12068 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12069 FILE *f, struct got_repository *repo)
12071 const struct got_error *err = NULL;
12072 char *line = NULL, *p, *end;
12073 size_t i, linesize = 0;
12074 ssize_t linelen;
12075 int lineno = 0;
12076 const struct got_histedit_cmd *cmd;
12077 struct got_object_id *commit_id = NULL;
12078 struct got_histedit_list_entry *hle = NULL;
12080 for (;;) {
12081 linelen = getline(&line, &linesize, f);
12082 if (linelen == -1) {
12083 const struct got_error *getline_err;
12084 if (feof(f))
12085 break;
12086 getline_err = got_error_from_errno("getline");
12087 err = got_ferror(f, getline_err->code);
12088 break;
12090 lineno++;
12091 p = line;
12092 while (isspace((unsigned char)p[0]))
12093 p++;
12094 if (p[0] == '#' || p[0] == '\0')
12095 continue;
12096 cmd = NULL;
12097 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12098 cmd = &got_histedit_cmds[i];
12099 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12100 isspace((unsigned char)p[strlen(cmd->name)])) {
12101 p += strlen(cmd->name);
12102 break;
12104 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12105 p++;
12106 break;
12109 if (i == nitems(got_histedit_cmds)) {
12110 err = histedit_syntax_error(lineno);
12111 break;
12113 while (isspace((unsigned char)p[0]))
12114 p++;
12115 end = p;
12116 while (end[0] && !isspace((unsigned char)end[0]))
12117 end++;
12118 *end = '\0';
12119 err = got_object_resolve_id_str(&commit_id, repo, p);
12120 if (err) {
12121 /* override error code */
12122 err = histedit_syntax_error(lineno);
12123 break;
12125 hle = malloc(sizeof(*hle));
12126 if (hle == NULL) {
12127 err = got_error_from_errno("malloc");
12128 break;
12130 hle->cmd = cmd;
12131 hle->commit_id = commit_id;
12132 hle->logmsg = NULL;
12133 commit_id = NULL;
12134 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12137 free(line);
12138 free(commit_id);
12139 return err;
12142 static const struct got_error *
12143 histedit_check_script(struct got_histedit_list *histedit_cmds,
12144 struct got_object_id_queue *commits, struct got_repository *repo)
12146 const struct got_error *err = NULL;
12147 struct got_object_qid *qid;
12148 struct got_histedit_list_entry *hle;
12149 static char msg[92];
12150 char *id_str;
12152 if (TAILQ_EMPTY(histedit_cmds))
12153 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12154 "histedit script contains no commands");
12155 if (STAILQ_EMPTY(commits))
12156 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12158 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12159 struct got_histedit_list_entry *hle2;
12160 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12161 if (hle == hle2)
12162 continue;
12163 if (got_object_id_cmp(hle->commit_id,
12164 hle2->commit_id) != 0)
12165 continue;
12166 err = got_object_id_str(&id_str, hle->commit_id);
12167 if (err)
12168 return err;
12169 snprintf(msg, sizeof(msg), "commit %s is listed "
12170 "more than once in histedit script", id_str);
12171 free(id_str);
12172 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12176 STAILQ_FOREACH(qid, commits, entry) {
12177 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12178 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12179 break;
12181 if (hle == NULL) {
12182 err = got_object_id_str(&id_str, &qid->id);
12183 if (err)
12184 return err;
12185 snprintf(msg, sizeof(msg),
12186 "commit %s missing from histedit script", id_str);
12187 free(id_str);
12188 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12192 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12193 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12194 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12195 "last commit in histedit script cannot be folded");
12197 return NULL;
12200 static const struct got_error *
12201 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12202 const char *editor, const char *path,
12203 struct got_object_id_queue *commits, struct got_repository *repo)
12205 const struct got_error *err = NULL;
12206 struct stat st, st2;
12207 struct timespec timeout;
12208 FILE *f = NULL;
12210 if (stat(path, &st) == -1) {
12211 err = got_error_from_errno2("stat", path);
12212 goto done;
12215 if (spawn_editor(editor, path) == -1) {
12216 err = got_error_from_errno("failed spawning editor");
12217 goto done;
12220 timeout.tv_sec = 0;
12221 timeout.tv_nsec = 1;
12222 nanosleep(&timeout, NULL);
12224 if (stat(path, &st2) == -1) {
12225 err = got_error_from_errno2("stat", path);
12226 goto done;
12229 if (st.st_size == st2.st_size &&
12230 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12231 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12232 "no changes made to histedit script, aborting");
12233 goto done;
12236 f = fopen(path, "re");
12237 if (f == NULL) {
12238 err = got_error_from_errno("fopen");
12239 goto done;
12241 err = histedit_parse_list(histedit_cmds, f, repo);
12242 if (err)
12243 goto done;
12245 err = histedit_check_script(histedit_cmds, commits, repo);
12246 done:
12247 if (f && fclose(f) == EOF && err == NULL)
12248 err = got_error_from_errno("fclose");
12249 return err;
12252 static const struct got_error *
12253 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12254 struct got_object_id_queue *, const char *, const char *, const char *,
12255 struct got_repository *);
12257 static const struct got_error *
12258 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12259 struct got_object_id_queue *commits, const char *branch_name,
12260 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12261 const char *editor, struct got_repository *repo)
12263 const struct got_error *err;
12264 FILE *f = NULL;
12265 char *path = NULL;
12267 err = got_opentemp_named(&path, &f, "got-histedit", "");
12268 if (err)
12269 return err;
12271 err = write_cmd_list(f, branch_name, commits);
12272 if (err)
12273 goto done;
12275 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12276 fold_only, drop_only, edit_only, repo);
12277 if (err)
12278 goto done;
12280 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12281 rewind(f);
12282 err = histedit_parse_list(histedit_cmds, f, repo);
12283 } else {
12284 if (fclose(f) == EOF) {
12285 err = got_error_from_errno("fclose");
12286 goto done;
12288 f = NULL;
12289 err = histedit_run_editor(histedit_cmds, editor, path,
12290 commits, repo);
12291 if (err) {
12292 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12293 err->code != GOT_ERR_HISTEDIT_CMD)
12294 goto done;
12295 err = histedit_edit_list_retry(histedit_cmds, err,
12296 commits, editor, path, branch_name, repo);
12299 done:
12300 if (f && fclose(f) == EOF && err == NULL)
12301 err = got_error_from_errno("fclose");
12302 if (path && unlink(path) != 0 && err == NULL)
12303 err = got_error_from_errno2("unlink", path);
12304 free(path);
12305 return err;
12308 static const struct got_error *
12309 histedit_save_list(struct got_histedit_list *histedit_cmds,
12310 struct got_worktree *worktree, struct got_repository *repo)
12312 const struct got_error *err = NULL;
12313 char *path = NULL;
12314 FILE *f = NULL;
12315 struct got_histedit_list_entry *hle;
12317 err = got_worktree_get_histedit_script_path(&path, worktree);
12318 if (err)
12319 return err;
12321 f = fopen(path, "we");
12322 if (f == NULL) {
12323 err = got_error_from_errno2("fopen", path);
12324 goto done;
12326 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12327 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12328 repo);
12329 if (err)
12330 break;
12332 done:
12333 if (f && fclose(f) == EOF && err == NULL)
12334 err = got_error_from_errno("fclose");
12335 free(path);
12336 return err;
12339 static void
12340 histedit_free_list(struct got_histedit_list *histedit_cmds)
12342 struct got_histedit_list_entry *hle;
12344 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12345 TAILQ_REMOVE(histedit_cmds, hle, entry);
12346 free(hle);
12350 static const struct got_error *
12351 histedit_load_list(struct got_histedit_list *histedit_cmds,
12352 const char *path, struct got_repository *repo)
12354 const struct got_error *err = NULL;
12355 FILE *f = NULL;
12357 f = fopen(path, "re");
12358 if (f == NULL) {
12359 err = got_error_from_errno2("fopen", path);
12360 goto done;
12363 err = histedit_parse_list(histedit_cmds, f, repo);
12364 done:
12365 if (f && fclose(f) == EOF && err == NULL)
12366 err = got_error_from_errno("fclose");
12367 return err;
12370 static const struct got_error *
12371 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12372 const struct got_error *edit_err, struct got_object_id_queue *commits,
12373 const char *editor, const char *path, const char *branch_name,
12374 struct got_repository *repo)
12376 const struct got_error *err = NULL, *prev_err = edit_err;
12377 int resp = ' ';
12379 while (resp != 'c' && resp != 'r' && resp != 'a') {
12380 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12381 "or (a)bort: ", getprogname(), prev_err->msg);
12382 resp = getchar();
12383 if (resp == '\n')
12384 resp = getchar();
12385 if (resp == 'c') {
12386 histedit_free_list(histedit_cmds);
12387 err = histedit_run_editor(histedit_cmds, editor, path,
12388 commits, repo);
12389 if (err) {
12390 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12391 err->code != GOT_ERR_HISTEDIT_CMD)
12392 break;
12393 prev_err = err;
12394 resp = ' ';
12395 continue;
12397 break;
12398 } else if (resp == 'r') {
12399 histedit_free_list(histedit_cmds);
12400 err = histedit_edit_script(histedit_cmds,
12401 commits, branch_name, 0, 0, 0, 0, editor, repo);
12402 if (err) {
12403 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12404 err->code != GOT_ERR_HISTEDIT_CMD)
12405 break;
12406 prev_err = err;
12407 resp = ' ';
12408 continue;
12410 break;
12411 } else if (resp == 'a') {
12412 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12413 break;
12414 } else
12415 printf("invalid response '%c'\n", resp);
12418 return err;
12421 static const struct got_error *
12422 histedit_complete(struct got_worktree *worktree,
12423 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12424 struct got_reference *branch, struct got_repository *repo)
12426 printf("Switching work tree to %s\n",
12427 got_ref_get_symref_target(branch));
12428 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12429 branch, repo);
12432 static const struct got_error *
12433 show_histedit_progress(struct got_commit_object *commit,
12434 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12436 const struct got_error *err;
12437 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12439 err = got_object_id_str(&old_id_str, hle->commit_id);
12440 if (err)
12441 goto done;
12443 if (new_id) {
12444 err = got_object_id_str(&new_id_str, new_id);
12445 if (err)
12446 goto done;
12449 old_id_str[12] = '\0';
12450 if (new_id_str)
12451 new_id_str[12] = '\0';
12453 if (hle->logmsg) {
12454 logmsg = strdup(hle->logmsg);
12455 if (logmsg == NULL) {
12456 err = got_error_from_errno("strdup");
12457 goto done;
12459 trim_logmsg(logmsg, 42);
12460 } else {
12461 err = get_short_logmsg(&logmsg, 42, commit);
12462 if (err)
12463 goto done;
12466 switch (hle->cmd->code) {
12467 case GOT_HISTEDIT_PICK:
12468 case GOT_HISTEDIT_EDIT:
12469 case GOT_HISTEDIT_MESG:
12470 printf("%s -> %s: %s\n", old_id_str,
12471 new_id_str ? new_id_str : "no-op change", logmsg);
12472 break;
12473 case GOT_HISTEDIT_DROP:
12474 case GOT_HISTEDIT_FOLD:
12475 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12476 logmsg);
12477 break;
12478 default:
12479 break;
12481 done:
12482 free(old_id_str);
12483 free(new_id_str);
12484 return err;
12487 static const struct got_error *
12488 histedit_commit(struct got_pathlist_head *merged_paths,
12489 struct got_worktree *worktree, struct got_fileindex *fileindex,
12490 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12491 const char *committer, int allow_conflict, const char *editor,
12492 struct got_repository *repo)
12494 const struct got_error *err;
12495 struct got_commit_object *commit;
12496 struct got_object_id *new_commit_id;
12498 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12499 && hle->logmsg == NULL) {
12500 err = histedit_edit_logmsg(hle, editor, repo);
12501 if (err)
12502 return err;
12505 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12506 if (err)
12507 return err;
12509 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12510 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12511 hle->logmsg, allow_conflict, repo);
12512 if (err) {
12513 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12514 goto done;
12515 err = show_histedit_progress(commit, hle, NULL);
12516 } else {
12517 err = show_histedit_progress(commit, hle, new_commit_id);
12518 free(new_commit_id);
12520 done:
12521 got_object_commit_close(commit);
12522 return err;
12525 static const struct got_error *
12526 histedit_skip_commit(struct got_histedit_list_entry *hle,
12527 struct got_worktree *worktree, struct got_repository *repo)
12529 const struct got_error *error;
12530 struct got_commit_object *commit;
12532 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12533 repo);
12534 if (error)
12535 return error;
12537 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12538 if (error)
12539 return error;
12541 error = show_histedit_progress(commit, hle, NULL);
12542 got_object_commit_close(commit);
12543 return error;
12546 static const struct got_error *
12547 check_local_changes(void *arg, unsigned char status,
12548 unsigned char staged_status, const char *path,
12549 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12550 struct got_object_id *commit_id, int dirfd, const char *de_name)
12552 int *have_local_changes = arg;
12554 switch (status) {
12555 case GOT_STATUS_ADD:
12556 case GOT_STATUS_DELETE:
12557 case GOT_STATUS_MODIFY:
12558 case GOT_STATUS_CONFLICT:
12559 *have_local_changes = 1;
12560 return got_error(GOT_ERR_CANCELLED);
12561 default:
12562 break;
12565 switch (staged_status) {
12566 case GOT_STATUS_ADD:
12567 case GOT_STATUS_DELETE:
12568 case GOT_STATUS_MODIFY:
12569 *have_local_changes = 1;
12570 return got_error(GOT_ERR_CANCELLED);
12571 default:
12572 break;
12575 return NULL;
12578 static const struct got_error *
12579 cmd_histedit(int argc, char *argv[])
12581 const struct got_error *error = NULL;
12582 struct got_worktree *worktree = NULL;
12583 struct got_fileindex *fileindex = NULL;
12584 struct got_repository *repo = NULL;
12585 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12586 struct got_reference *branch = NULL;
12587 struct got_reference *tmp_branch = NULL;
12588 struct got_object_id *resume_commit_id = NULL;
12589 struct got_object_id *base_commit_id = NULL;
12590 struct got_object_id *head_commit_id = NULL;
12591 struct got_commit_object *commit = NULL;
12592 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12593 struct got_update_progress_arg upa;
12594 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12595 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12596 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12597 const char *edit_script_path = NULL;
12598 char *editor = NULL;
12599 struct got_object_id_queue commits;
12600 struct got_pathlist_head merged_paths;
12601 const struct got_object_id_queue *parent_ids;
12602 struct got_object_qid *pid;
12603 struct got_histedit_list histedit_cmds;
12604 struct got_histedit_list_entry *hle;
12605 int *pack_fds = NULL;
12607 STAILQ_INIT(&commits);
12608 TAILQ_INIT(&histedit_cmds);
12609 TAILQ_INIT(&merged_paths);
12610 memset(&upa, 0, sizeof(upa));
12612 #ifndef PROFILE
12613 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12614 "unveil", NULL) == -1)
12615 err(1, "pledge");
12616 #endif
12618 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12619 switch (ch) {
12620 case 'a':
12621 abort_edit = 1;
12622 break;
12623 case 'C':
12624 allow_conflict = 1;
12625 break;
12626 case 'c':
12627 continue_edit = 1;
12628 break;
12629 case 'd':
12630 drop_only = 1;
12631 break;
12632 case 'e':
12633 edit_only = 1;
12634 break;
12635 case 'F':
12636 edit_script_path = optarg;
12637 break;
12638 case 'f':
12639 fold_only = 1;
12640 break;
12641 case 'l':
12642 list_backups = 1;
12643 break;
12644 case 'm':
12645 edit_logmsg_only = 1;
12646 break;
12647 case 'X':
12648 delete_backups = 1;
12649 break;
12650 default:
12651 usage_histedit();
12652 /* NOTREACHED */
12656 argc -= optind;
12657 argv += optind;
12659 if (abort_edit && allow_conflict)
12660 option_conflict('a', 'C');
12661 if (abort_edit && continue_edit)
12662 option_conflict('a', 'c');
12663 if (edit_script_path && allow_conflict)
12664 option_conflict('F', 'C');
12665 if (edit_script_path && edit_logmsg_only)
12666 option_conflict('F', 'm');
12667 if (abort_edit && edit_logmsg_only)
12668 option_conflict('a', 'm');
12669 if (edit_logmsg_only && allow_conflict)
12670 option_conflict('m', 'C');
12671 if (continue_edit && edit_logmsg_only)
12672 option_conflict('c', 'm');
12673 if (abort_edit && fold_only)
12674 option_conflict('a', 'f');
12675 if (fold_only && allow_conflict)
12676 option_conflict('f', 'C');
12677 if (continue_edit && fold_only)
12678 option_conflict('c', 'f');
12679 if (fold_only && edit_logmsg_only)
12680 option_conflict('f', 'm');
12681 if (edit_script_path && fold_only)
12682 option_conflict('F', 'f');
12683 if (abort_edit && edit_only)
12684 option_conflict('a', 'e');
12685 if (continue_edit && edit_only)
12686 option_conflict('c', 'e');
12687 if (edit_only && edit_logmsg_only)
12688 option_conflict('e', 'm');
12689 if (edit_script_path && edit_only)
12690 option_conflict('F', 'e');
12691 if (fold_only && edit_only)
12692 option_conflict('f', 'e');
12693 if (drop_only && abort_edit)
12694 option_conflict('d', 'a');
12695 if (drop_only && allow_conflict)
12696 option_conflict('d', 'C');
12697 if (drop_only && continue_edit)
12698 option_conflict('d', 'c');
12699 if (drop_only && edit_logmsg_only)
12700 option_conflict('d', 'm');
12701 if (drop_only && edit_only)
12702 option_conflict('d', 'e');
12703 if (drop_only && edit_script_path)
12704 option_conflict('d', 'F');
12705 if (drop_only && fold_only)
12706 option_conflict('d', 'f');
12707 if (list_backups) {
12708 if (abort_edit)
12709 option_conflict('l', 'a');
12710 if (allow_conflict)
12711 option_conflict('l', 'C');
12712 if (continue_edit)
12713 option_conflict('l', 'c');
12714 if (edit_script_path)
12715 option_conflict('l', 'F');
12716 if (edit_logmsg_only)
12717 option_conflict('l', 'm');
12718 if (drop_only)
12719 option_conflict('l', 'd');
12720 if (fold_only)
12721 option_conflict('l', 'f');
12722 if (edit_only)
12723 option_conflict('l', 'e');
12724 if (delete_backups)
12725 option_conflict('l', 'X');
12726 if (argc != 0 && argc != 1)
12727 usage_histedit();
12728 } else if (delete_backups) {
12729 if (abort_edit)
12730 option_conflict('X', 'a');
12731 if (allow_conflict)
12732 option_conflict('X', 'C');
12733 if (continue_edit)
12734 option_conflict('X', 'c');
12735 if (drop_only)
12736 option_conflict('X', 'd');
12737 if (edit_script_path)
12738 option_conflict('X', 'F');
12739 if (edit_logmsg_only)
12740 option_conflict('X', 'm');
12741 if (fold_only)
12742 option_conflict('X', 'f');
12743 if (edit_only)
12744 option_conflict('X', 'e');
12745 if (list_backups)
12746 option_conflict('X', 'l');
12747 if (argc != 0 && argc != 1)
12748 usage_histedit();
12749 } else if (allow_conflict && !continue_edit)
12750 errx(1, "-C option requires -c");
12751 else if (argc != 0)
12752 usage_histedit();
12754 cwd = getcwd(NULL, 0);
12755 if (cwd == NULL) {
12756 error = got_error_from_errno("getcwd");
12757 goto done;
12760 error = got_repo_pack_fds_open(&pack_fds);
12761 if (error != NULL)
12762 goto done;
12764 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12765 if (error) {
12766 if (list_backups || delete_backups) {
12767 if (error->code != GOT_ERR_NOT_WORKTREE)
12768 goto done;
12769 } else {
12770 if (error->code == GOT_ERR_NOT_WORKTREE)
12771 error = wrap_not_worktree_error(error,
12772 "histedit", cwd);
12773 goto done;
12777 if (list_backups || delete_backups) {
12778 error = got_repo_open(&repo,
12779 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12780 NULL, pack_fds);
12781 if (error != NULL)
12782 goto done;
12783 error = apply_unveil(got_repo_get_path(repo), 0,
12784 worktree ? got_worktree_get_root_path(worktree) : NULL);
12785 if (error)
12786 goto done;
12787 error = process_backup_refs(
12788 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12789 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12790 goto done; /* nothing else to do */
12791 } else {
12792 error = get_gitconfig_path(&gitconfig_path);
12793 if (error)
12794 goto done;
12795 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12796 gitconfig_path, pack_fds);
12797 if (error != NULL)
12798 goto done;
12799 error = get_editor(&editor);
12800 if (error)
12801 goto done;
12802 if (unveil(editor, "x") != 0) {
12803 error = got_error_from_errno2("unveil", editor);
12804 goto done;
12806 if (edit_script_path) {
12807 if (unveil(edit_script_path, "r") != 0) {
12808 error = got_error_from_errno2("unveil",
12809 edit_script_path);
12810 goto done;
12813 error = apply_unveil(got_repo_get_path(repo), 0,
12814 got_worktree_get_root_path(worktree));
12815 if (error)
12816 goto done;
12819 if (worktree != NULL && !list_backups && !delete_backups) {
12820 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12821 if (error)
12822 goto done;
12825 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12826 if (error)
12827 goto done;
12828 if (rebase_in_progress) {
12829 error = got_error(GOT_ERR_REBASING);
12830 goto done;
12833 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12834 repo);
12835 if (error)
12836 goto done;
12837 if (merge_in_progress) {
12838 error = got_error(GOT_ERR_MERGE_BUSY);
12839 goto done;
12842 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12843 if (error)
12844 goto done;
12846 if (edit_in_progress && edit_logmsg_only) {
12847 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12848 "histedit operation is in progress in this "
12849 "work tree and must be continued or aborted "
12850 "before the -m option can be used");
12851 goto done;
12853 if (edit_in_progress && drop_only) {
12854 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12855 "histedit operation is in progress in this "
12856 "work tree and must be continued or aborted "
12857 "before the -d option can be used");
12858 goto done;
12860 if (edit_in_progress && fold_only) {
12861 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12862 "histedit operation is in progress in this "
12863 "work tree and must be continued or aborted "
12864 "before the -f option can be used");
12865 goto done;
12867 if (edit_in_progress && edit_only) {
12868 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12869 "histedit operation is in progress in this "
12870 "work tree and must be continued or aborted "
12871 "before the -e option can be used");
12872 goto done;
12875 if (edit_in_progress && abort_edit) {
12876 error = got_worktree_histedit_continue(&resume_commit_id,
12877 &tmp_branch, &branch, &base_commit_id, &fileindex,
12878 worktree, repo);
12879 if (error)
12880 goto done;
12881 printf("Switching work tree to %s\n",
12882 got_ref_get_symref_target(branch));
12883 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12884 branch, base_commit_id, abort_progress, &upa);
12885 if (error)
12886 goto done;
12887 printf("Histedit of %s aborted\n",
12888 got_ref_get_symref_target(branch));
12889 print_merge_progress_stats(&upa);
12890 goto done; /* nothing else to do */
12891 } else if (abort_edit) {
12892 error = got_error(GOT_ERR_NOT_HISTEDIT);
12893 goto done;
12896 error = get_author(&committer, repo, worktree);
12897 if (error)
12898 goto done;
12900 if (continue_edit) {
12901 char *path;
12903 if (!edit_in_progress) {
12904 error = got_error(GOT_ERR_NOT_HISTEDIT);
12905 goto done;
12908 error = got_worktree_get_histedit_script_path(&path, worktree);
12909 if (error)
12910 goto done;
12912 error = histedit_load_list(&histedit_cmds, path, repo);
12913 free(path);
12914 if (error)
12915 goto done;
12917 error = got_worktree_histedit_continue(&resume_commit_id,
12918 &tmp_branch, &branch, &base_commit_id, &fileindex,
12919 worktree, repo);
12920 if (error)
12921 goto done;
12923 error = got_ref_resolve(&head_commit_id, repo, branch);
12924 if (error)
12925 goto done;
12927 error = got_object_open_as_commit(&commit, repo,
12928 head_commit_id);
12929 if (error)
12930 goto done;
12931 parent_ids = got_object_commit_get_parent_ids(commit);
12932 pid = STAILQ_FIRST(parent_ids);
12933 if (pid == NULL) {
12934 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12935 goto done;
12937 error = collect_commits(&commits, head_commit_id, &pid->id,
12938 base_commit_id, got_worktree_get_path_prefix(worktree),
12939 GOT_ERR_HISTEDIT_PATH, repo);
12940 got_object_commit_close(commit);
12941 commit = NULL;
12942 if (error)
12943 goto done;
12944 } else {
12945 if (edit_in_progress) {
12946 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12947 goto done;
12950 error = got_ref_open(&branch, repo,
12951 got_worktree_get_head_ref_name(worktree), 0);
12952 if (error != NULL)
12953 goto done;
12955 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12956 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12957 "will not edit commit history of a branch outside "
12958 "the \"refs/heads/\" reference namespace");
12959 goto done;
12962 error = got_ref_resolve(&head_commit_id, repo, branch);
12963 got_ref_close(branch);
12964 branch = NULL;
12965 if (error)
12966 goto done;
12968 error = got_object_open_as_commit(&commit, repo,
12969 head_commit_id);
12970 if (error)
12971 goto done;
12972 parent_ids = got_object_commit_get_parent_ids(commit);
12973 pid = STAILQ_FIRST(parent_ids);
12974 if (pid == NULL) {
12975 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12976 goto done;
12978 error = collect_commits(&commits, head_commit_id, &pid->id,
12979 got_worktree_get_base_commit_id(worktree),
12980 got_worktree_get_path_prefix(worktree),
12981 GOT_ERR_HISTEDIT_PATH, repo);
12982 got_object_commit_close(commit);
12983 commit = NULL;
12984 if (error)
12985 goto done;
12987 if (STAILQ_EMPTY(&commits)) {
12988 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12989 goto done;
12992 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12993 &base_commit_id, &fileindex, worktree, repo);
12994 if (error)
12995 goto done;
12997 if (edit_script_path) {
12998 error = histedit_load_list(&histedit_cmds,
12999 edit_script_path, repo);
13000 if (error) {
13001 got_worktree_histedit_abort(worktree, fileindex,
13002 repo, branch, base_commit_id,
13003 abort_progress, &upa);
13004 print_merge_progress_stats(&upa);
13005 goto done;
13007 } else {
13008 const char *branch_name;
13009 branch_name = got_ref_get_symref_target(branch);
13010 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13011 branch_name += 11;
13012 error = histedit_edit_script(&histedit_cmds, &commits,
13013 branch_name, edit_logmsg_only, fold_only,
13014 drop_only, edit_only, editor, repo);
13015 if (error) {
13016 got_worktree_histedit_abort(worktree, fileindex,
13017 repo, branch, base_commit_id,
13018 abort_progress, &upa);
13019 print_merge_progress_stats(&upa);
13020 goto done;
13025 error = histedit_save_list(&histedit_cmds, worktree,
13026 repo);
13027 if (error) {
13028 got_worktree_histedit_abort(worktree, fileindex,
13029 repo, branch, base_commit_id,
13030 abort_progress, &upa);
13031 print_merge_progress_stats(&upa);
13032 goto done;
13037 error = histedit_check_script(&histedit_cmds, &commits, repo);
13038 if (error)
13039 goto done;
13041 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13042 if (resume_commit_id) {
13043 if (got_object_id_cmp(hle->commit_id,
13044 resume_commit_id) != 0)
13045 continue;
13047 resume_commit_id = NULL;
13048 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13049 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13050 error = histedit_skip_commit(hle, worktree,
13051 repo);
13052 if (error)
13053 goto done;
13054 } else {
13055 struct got_pathlist_head paths;
13056 int have_changes = 0;
13058 TAILQ_INIT(&paths);
13059 error = got_pathlist_append(&paths, "", NULL);
13060 if (error)
13061 goto done;
13062 error = got_worktree_status(worktree, &paths,
13063 repo, 0, check_local_changes, &have_changes,
13064 check_cancelled, NULL);
13065 got_pathlist_free(&paths,
13066 GOT_PATHLIST_FREE_NONE);
13067 if (error) {
13068 if (error->code != GOT_ERR_CANCELLED)
13069 goto done;
13070 if (sigint_received || sigpipe_received)
13071 goto done;
13073 if (have_changes) {
13074 error = histedit_commit(NULL, worktree,
13075 fileindex, tmp_branch, hle,
13076 committer, allow_conflict, editor, repo);
13077 if (error)
13078 goto done;
13079 } else {
13080 error = got_object_open_as_commit(
13081 &commit, repo, hle->commit_id);
13082 if (error)
13083 goto done;
13084 error = show_histedit_progress(commit,
13085 hle, NULL);
13086 got_object_commit_close(commit);
13087 commit = NULL;
13088 if (error)
13089 goto done;
13092 continue;
13095 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13096 error = histedit_skip_commit(hle, worktree, repo);
13097 if (error)
13098 goto done;
13099 continue;
13101 error = got_object_open_as_commit(&commit, repo,
13102 hle->commit_id);
13103 if (error)
13104 goto done;
13105 parent_ids = got_object_commit_get_parent_ids(commit);
13106 pid = STAILQ_FIRST(parent_ids);
13108 error = got_worktree_histedit_merge_files(&merged_paths,
13109 worktree, fileindex, &pid->id, hle->commit_id, repo,
13110 update_progress, &upa, check_cancelled, NULL);
13111 if (error)
13112 goto done;
13113 got_object_commit_close(commit);
13114 commit = NULL;
13116 print_merge_progress_stats(&upa);
13117 if (upa.conflicts > 0 || upa.missing > 0 ||
13118 upa.not_deleted > 0 || upa.unversioned > 0) {
13119 if (upa.conflicts > 0) {
13120 error = show_rebase_merge_conflict(
13121 hle->commit_id, repo);
13122 if (error)
13123 goto done;
13125 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13126 break;
13129 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13130 char *id_str;
13131 error = got_object_id_str(&id_str, hle->commit_id);
13132 if (error)
13133 goto done;
13134 printf("Stopping histedit for amending commit %s\n",
13135 id_str);
13136 free(id_str);
13137 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13138 error = got_worktree_histedit_postpone(worktree,
13139 fileindex);
13140 goto done;
13141 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13142 error = histedit_skip_commit(hle, worktree, repo);
13143 if (error)
13144 goto done;
13145 continue;
13146 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13147 error = histedit_edit_logmsg(hle, editor, repo);
13148 if (error)
13149 goto done;
13152 error = histedit_commit(&merged_paths, worktree, fileindex,
13153 tmp_branch, hle, committer, allow_conflict, editor, repo);
13154 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13155 if (error)
13156 goto done;
13159 if (upa.conflicts > 0 || upa.missing > 0 ||
13160 upa.not_deleted > 0 || upa.unversioned > 0) {
13161 error = got_worktree_histedit_postpone(worktree, fileindex);
13162 if (error)
13163 goto done;
13164 if (upa.conflicts > 0 && upa.missing == 0 &&
13165 upa.not_deleted == 0 && upa.unversioned == 0) {
13166 error = got_error_msg(GOT_ERR_CONFLICTS,
13167 "conflicts must be resolved before histedit "
13168 "can continue");
13169 } else if (upa.conflicts > 0) {
13170 error = got_error_msg(GOT_ERR_CONFLICTS,
13171 "conflicts must be resolved before histedit "
13172 "can continue; changes destined for some "
13173 "files were not yet merged and should be "
13174 "merged manually if required before the "
13175 "histedit operation is continued");
13176 } else {
13177 error = got_error_msg(GOT_ERR_CONFLICTS,
13178 "changes destined for some files were not "
13179 "yet merged and should be merged manually "
13180 "if required before the histedit operation "
13181 "is continued");
13183 } else
13184 error = histedit_complete(worktree, fileindex, tmp_branch,
13185 branch, repo);
13186 done:
13187 free(cwd);
13188 free(editor);
13189 free(committer);
13190 free(gitconfig_path);
13191 got_object_id_queue_free(&commits);
13192 histedit_free_list(&histedit_cmds);
13193 free(head_commit_id);
13194 free(base_commit_id);
13195 free(resume_commit_id);
13196 if (commit)
13197 got_object_commit_close(commit);
13198 if (branch)
13199 got_ref_close(branch);
13200 if (tmp_branch)
13201 got_ref_close(tmp_branch);
13202 if (worktree)
13203 got_worktree_close(worktree);
13204 if (repo) {
13205 const struct got_error *close_err = got_repo_close(repo);
13206 if (error == NULL)
13207 error = close_err;
13209 if (pack_fds) {
13210 const struct got_error *pack_err =
13211 got_repo_pack_fds_close(pack_fds);
13212 if (error == NULL)
13213 error = pack_err;
13215 return error;
13218 __dead static void
13219 usage_integrate(void)
13221 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13222 exit(1);
13225 static const struct got_error *
13226 cmd_integrate(int argc, char *argv[])
13228 const struct got_error *error = NULL;
13229 struct got_repository *repo = NULL;
13230 struct got_worktree *worktree = NULL;
13231 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13232 const char *branch_arg = NULL;
13233 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13234 struct got_fileindex *fileindex = NULL;
13235 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13236 int ch;
13237 struct got_update_progress_arg upa;
13238 int *pack_fds = NULL;
13240 #ifndef PROFILE
13241 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13242 "unveil", NULL) == -1)
13243 err(1, "pledge");
13244 #endif
13246 while ((ch = getopt(argc, argv, "")) != -1) {
13247 switch (ch) {
13248 default:
13249 usage_integrate();
13250 /* NOTREACHED */
13254 argc -= optind;
13255 argv += optind;
13257 if (argc != 1)
13258 usage_integrate();
13259 branch_arg = argv[0];
13261 cwd = getcwd(NULL, 0);
13262 if (cwd == NULL) {
13263 error = got_error_from_errno("getcwd");
13264 goto done;
13267 error = got_repo_pack_fds_open(&pack_fds);
13268 if (error != NULL)
13269 goto done;
13271 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13272 if (error) {
13273 if (error->code == GOT_ERR_NOT_WORKTREE)
13274 error = wrap_not_worktree_error(error, "integrate",
13275 cwd);
13276 goto done;
13279 error = check_rebase_or_histedit_in_progress(worktree);
13280 if (error)
13281 goto done;
13283 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13284 NULL, pack_fds);
13285 if (error != NULL)
13286 goto done;
13288 error = apply_unveil(got_repo_get_path(repo), 0,
13289 got_worktree_get_root_path(worktree));
13290 if (error)
13291 goto done;
13293 error = check_merge_in_progress(worktree, repo);
13294 if (error)
13295 goto done;
13297 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13298 error = got_error_from_errno("asprintf");
13299 goto done;
13302 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13303 &base_branch_ref, worktree, refname, repo);
13304 if (error)
13305 goto done;
13307 refname = strdup(got_ref_get_name(branch_ref));
13308 if (refname == NULL) {
13309 error = got_error_from_errno("strdup");
13310 got_worktree_integrate_abort(worktree, fileindex, repo,
13311 branch_ref, base_branch_ref);
13312 goto done;
13314 base_refname = strdup(got_ref_get_name(base_branch_ref));
13315 if (base_refname == NULL) {
13316 error = got_error_from_errno("strdup");
13317 got_worktree_integrate_abort(worktree, fileindex, repo,
13318 branch_ref, base_branch_ref);
13319 goto done;
13321 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13322 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13323 got_worktree_integrate_abort(worktree, fileindex, repo,
13324 branch_ref, base_branch_ref);
13325 goto done;
13328 error = got_ref_resolve(&commit_id, repo, branch_ref);
13329 if (error)
13330 goto done;
13332 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13333 if (error)
13334 goto done;
13336 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13337 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13338 "specified branch has already been integrated");
13339 got_worktree_integrate_abort(worktree, fileindex, repo,
13340 branch_ref, base_branch_ref);
13341 goto done;
13344 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13345 if (error) {
13346 if (error->code == GOT_ERR_ANCESTRY)
13347 error = got_error(GOT_ERR_REBASE_REQUIRED);
13348 got_worktree_integrate_abort(worktree, fileindex, repo,
13349 branch_ref, base_branch_ref);
13350 goto done;
13353 memset(&upa, 0, sizeof(upa));
13354 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13355 branch_ref, base_branch_ref, update_progress, &upa,
13356 check_cancelled, NULL);
13357 if (error)
13358 goto done;
13360 printf("Integrated %s into %s\n", refname, base_refname);
13361 print_update_progress_stats(&upa);
13362 done:
13363 if (repo) {
13364 const struct got_error *close_err = got_repo_close(repo);
13365 if (error == NULL)
13366 error = close_err;
13368 if (worktree)
13369 got_worktree_close(worktree);
13370 if (pack_fds) {
13371 const struct got_error *pack_err =
13372 got_repo_pack_fds_close(pack_fds);
13373 if (error == NULL)
13374 error = pack_err;
13376 free(cwd);
13377 free(base_commit_id);
13378 free(commit_id);
13379 free(refname);
13380 free(base_refname);
13381 return error;
13384 __dead static void
13385 usage_merge(void)
13387 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13388 exit(1);
13391 static const struct got_error *
13392 cmd_merge(int argc, char *argv[])
13394 const struct got_error *error = NULL;
13395 struct got_worktree *worktree = NULL;
13396 struct got_repository *repo = NULL;
13397 struct got_fileindex *fileindex = NULL;
13398 char *cwd = NULL, *id_str = NULL, *author = NULL;
13399 char *gitconfig_path = NULL;
13400 struct got_reference *branch = NULL, *wt_branch = NULL;
13401 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13402 struct got_object_id *wt_branch_tip = NULL;
13403 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13404 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13405 struct got_update_progress_arg upa;
13406 struct got_object_id *merge_commit_id = NULL;
13407 char *branch_name = NULL;
13408 int *pack_fds = NULL;
13410 memset(&upa, 0, sizeof(upa));
13412 #ifndef PROFILE
13413 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13414 "unveil", NULL) == -1)
13415 err(1, "pledge");
13416 #endif
13418 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13419 switch (ch) {
13420 case 'a':
13421 abort_merge = 1;
13422 break;
13423 case 'C':
13424 allow_conflict = 1;
13425 break;
13426 case 'c':
13427 continue_merge = 1;
13428 break;
13429 case 'M':
13430 prefer_fast_forward = 0;
13431 break;
13432 case 'n':
13433 interrupt_merge = 1;
13434 break;
13435 default:
13436 usage_merge();
13437 /* NOTREACHED */
13441 argc -= optind;
13442 argv += optind;
13444 if (abort_merge) {
13445 if (continue_merge)
13446 option_conflict('a', 'c');
13447 if (!prefer_fast_forward)
13448 option_conflict('a', 'M');
13449 if (interrupt_merge)
13450 option_conflict('a', 'n');
13451 } else if (continue_merge) {
13452 if (!prefer_fast_forward)
13453 option_conflict('c', 'M');
13454 if (interrupt_merge)
13455 option_conflict('c', 'n');
13457 if (allow_conflict) {
13458 if (!continue_merge)
13459 errx(1, "-C option requires -c");
13461 if (abort_merge || continue_merge) {
13462 if (argc != 0)
13463 usage_merge();
13464 } else if (argc != 1)
13465 usage_merge();
13467 cwd = getcwd(NULL, 0);
13468 if (cwd == NULL) {
13469 error = got_error_from_errno("getcwd");
13470 goto done;
13473 error = got_repo_pack_fds_open(&pack_fds);
13474 if (error != NULL)
13475 goto done;
13477 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13478 if (error) {
13479 if (error->code == GOT_ERR_NOT_WORKTREE)
13480 error = wrap_not_worktree_error(error,
13481 "merge", cwd);
13482 goto done;
13485 error = get_gitconfig_path(&gitconfig_path);
13486 if (error)
13487 goto done;
13488 error = got_repo_open(&repo,
13489 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13490 gitconfig_path, pack_fds);
13491 if (error != NULL)
13492 goto done;
13494 if (worktree != NULL) {
13495 error = worktree_has_logmsg_ref("merge", worktree, repo);
13496 if (error)
13497 goto done;
13500 error = apply_unveil(got_repo_get_path(repo), 0,
13501 worktree ? got_worktree_get_root_path(worktree) : NULL);
13502 if (error)
13503 goto done;
13505 error = check_rebase_or_histedit_in_progress(worktree);
13506 if (error)
13507 goto done;
13509 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13510 repo);
13511 if (error)
13512 goto done;
13514 if (merge_in_progress && !(abort_merge || continue_merge)) {
13515 error = got_error(GOT_ERR_MERGE_BUSY);
13516 goto done;
13519 if (!merge_in_progress && (abort_merge || continue_merge)) {
13520 error = got_error(GOT_ERR_NOT_MERGING);
13521 goto done;
13524 if (abort_merge) {
13525 error = got_worktree_merge_continue(&branch_name,
13526 &branch_tip, &fileindex, worktree, repo);
13527 if (error)
13528 goto done;
13529 error = got_worktree_merge_abort(worktree, fileindex, repo,
13530 abort_progress, &upa);
13531 if (error)
13532 goto done;
13533 printf("Merge of %s aborted\n", branch_name);
13534 goto done; /* nothing else to do */
13537 if (strncmp(got_worktree_get_head_ref_name(worktree),
13538 "refs/heads/", 11) != 0) {
13539 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13540 "work tree's current branch %s is outside the "
13541 "\"refs/heads/\" reference namespace; "
13542 "update -b required",
13543 got_worktree_get_head_ref_name(worktree));
13544 goto done;
13547 error = get_author(&author, repo, worktree);
13548 if (error)
13549 goto done;
13551 error = got_ref_open(&wt_branch, repo,
13552 got_worktree_get_head_ref_name(worktree), 0);
13553 if (error)
13554 goto done;
13555 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13556 if (error)
13557 goto done;
13559 if (continue_merge) {
13560 struct got_object_id *base_commit_id;
13561 base_commit_id = got_worktree_get_base_commit_id(worktree);
13562 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13563 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13564 goto done;
13566 error = got_worktree_merge_continue(&branch_name,
13567 &branch_tip, &fileindex, worktree, repo);
13568 if (error)
13569 goto done;
13570 } else {
13571 error = got_ref_open(&branch, repo, argv[0], 0);
13572 if (error != NULL)
13573 goto done;
13574 branch_name = strdup(got_ref_get_name(branch));
13575 if (branch_name == NULL) {
13576 error = got_error_from_errno("strdup");
13577 goto done;
13579 error = got_ref_resolve(&branch_tip, repo, branch);
13580 if (error)
13581 goto done;
13584 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13585 wt_branch_tip, branch_tip, 0, 0, repo,
13586 check_cancelled, NULL);
13587 if (error && error->code != GOT_ERR_ANCESTRY)
13588 goto done;
13590 if (!continue_merge) {
13591 error = check_path_prefix(wt_branch_tip, branch_tip,
13592 got_worktree_get_path_prefix(worktree),
13593 GOT_ERR_MERGE_PATH, repo);
13594 if (error)
13595 goto done;
13596 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13597 if (error)
13598 goto done;
13599 if (prefer_fast_forward && yca_id &&
13600 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13601 struct got_pathlist_head paths;
13602 if (interrupt_merge) {
13603 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13604 "there are no changes to merge since %s "
13605 "is already based on %s; merge cannot be "
13606 "interrupted for amending; -n",
13607 branch_name, got_ref_get_name(wt_branch));
13608 goto done;
13610 printf("Forwarding %s to %s\n",
13611 got_ref_get_name(wt_branch), branch_name);
13612 error = got_ref_change_ref(wt_branch, branch_tip);
13613 if (error)
13614 goto done;
13615 error = got_ref_write(wt_branch, repo);
13616 if (error)
13617 goto done;
13618 error = got_worktree_set_base_commit_id(worktree, repo,
13619 branch_tip);
13620 if (error)
13621 goto done;
13622 TAILQ_INIT(&paths);
13623 error = got_pathlist_append(&paths, "", NULL);
13624 if (error)
13625 goto done;
13626 error = got_worktree_checkout_files(worktree,
13627 &paths, repo, update_progress, &upa,
13628 check_cancelled, NULL);
13629 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13630 if (error)
13631 goto done;
13632 if (upa.did_something) {
13633 char *id_str;
13634 error = got_object_id_str(&id_str, branch_tip);
13635 if (error)
13636 goto done;
13637 printf("Updated to commit %s\n", id_str);
13638 free(id_str);
13639 } else
13640 printf("Already up-to-date\n");
13641 print_update_progress_stats(&upa);
13642 goto done;
13644 error = got_worktree_merge_write_refs(worktree, branch, repo);
13645 if (error)
13646 goto done;
13648 error = got_worktree_merge_branch(worktree, fileindex,
13649 yca_id, branch_tip, repo, update_progress, &upa,
13650 check_cancelled, NULL);
13651 if (error)
13652 goto done;
13653 print_merge_progress_stats(&upa);
13654 if (!upa.did_something) {
13655 error = got_worktree_merge_abort(worktree, fileindex,
13656 repo, abort_progress, &upa);
13657 if (error)
13658 goto done;
13659 printf("Already up-to-date\n");
13660 goto done;
13664 if (interrupt_merge) {
13665 error = got_worktree_merge_postpone(worktree, fileindex);
13666 if (error)
13667 goto done;
13668 printf("Merge of %s interrupted on request\n", branch_name);
13669 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13670 upa.not_deleted > 0 || upa.unversioned > 0) {
13671 error = got_worktree_merge_postpone(worktree, fileindex);
13672 if (error)
13673 goto done;
13674 if (upa.conflicts > 0 && upa.missing == 0 &&
13675 upa.not_deleted == 0 && upa.unversioned == 0) {
13676 error = got_error_msg(GOT_ERR_CONFLICTS,
13677 "conflicts must be resolved before merging "
13678 "can continue");
13679 } else if (upa.conflicts > 0) {
13680 error = got_error_msg(GOT_ERR_CONFLICTS,
13681 "conflicts must be resolved before merging "
13682 "can continue; changes destined for some "
13683 "files were not yet merged and "
13684 "should be merged manually if required before the "
13685 "merge operation is continued");
13686 } else {
13687 error = got_error_msg(GOT_ERR_CONFLICTS,
13688 "changes destined for some "
13689 "files were not yet merged and should be "
13690 "merged manually if required before the "
13691 "merge operation is continued");
13693 goto done;
13694 } else {
13695 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13696 fileindex, author, NULL, 1, branch_tip, branch_name,
13697 allow_conflict, repo, continue_merge ? print_status : NULL,
13698 NULL);
13699 if (error)
13700 goto done;
13701 error = got_worktree_merge_complete(worktree, fileindex, repo);
13702 if (error)
13703 goto done;
13704 error = got_object_id_str(&id_str, merge_commit_id);
13705 if (error)
13706 goto done;
13707 printf("Merged %s into %s: %s\n", branch_name,
13708 got_worktree_get_head_ref_name(worktree),
13709 id_str);
13712 done:
13713 free(gitconfig_path);
13714 free(id_str);
13715 free(merge_commit_id);
13716 free(author);
13717 free(branch_tip);
13718 free(branch_name);
13719 free(yca_id);
13720 if (branch)
13721 got_ref_close(branch);
13722 if (wt_branch)
13723 got_ref_close(wt_branch);
13724 if (worktree)
13725 got_worktree_close(worktree);
13726 if (repo) {
13727 const struct got_error *close_err = got_repo_close(repo);
13728 if (error == NULL)
13729 error = close_err;
13731 if (pack_fds) {
13732 const struct got_error *pack_err =
13733 got_repo_pack_fds_close(pack_fds);
13734 if (error == NULL)
13735 error = pack_err;
13737 return error;
13740 __dead static void
13741 usage_stage(void)
13743 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13744 "[path ...]\n", getprogname());
13745 exit(1);
13748 static const struct got_error *
13749 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13750 const char *path, struct got_object_id *blob_id,
13751 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13752 int dirfd, const char *de_name)
13754 const struct got_error *err = NULL;
13755 char *id_str = NULL;
13757 if (staged_status != GOT_STATUS_ADD &&
13758 staged_status != GOT_STATUS_MODIFY &&
13759 staged_status != GOT_STATUS_DELETE)
13760 return NULL;
13762 if (staged_status == GOT_STATUS_ADD ||
13763 staged_status == GOT_STATUS_MODIFY)
13764 err = got_object_id_str(&id_str, staged_blob_id);
13765 else
13766 err = got_object_id_str(&id_str, blob_id);
13767 if (err)
13768 return err;
13770 printf("%s %c %s\n", id_str, staged_status, path);
13771 free(id_str);
13772 return NULL;
13775 static const struct got_error *
13776 cmd_stage(int argc, char *argv[])
13778 const struct got_error *error = NULL;
13779 struct got_repository *repo = NULL;
13780 struct got_worktree *worktree = NULL;
13781 char *cwd = NULL;
13782 struct got_pathlist_head paths;
13783 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13784 FILE *patch_script_file = NULL;
13785 const char *patch_script_path = NULL;
13786 struct choose_patch_arg cpa;
13787 int *pack_fds = NULL;
13789 TAILQ_INIT(&paths);
13791 #ifndef PROFILE
13792 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13793 "unveil", NULL) == -1)
13794 err(1, "pledge");
13795 #endif
13797 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13798 switch (ch) {
13799 case 'F':
13800 patch_script_path = optarg;
13801 break;
13802 case 'l':
13803 list_stage = 1;
13804 break;
13805 case 'p':
13806 pflag = 1;
13807 break;
13808 case 'S':
13809 allow_bad_symlinks = 1;
13810 break;
13811 default:
13812 usage_stage();
13813 /* NOTREACHED */
13817 argc -= optind;
13818 argv += optind;
13820 if (list_stage && (pflag || patch_script_path))
13821 errx(1, "-l option cannot be used with other options");
13822 if (patch_script_path && !pflag)
13823 errx(1, "-F option can only be used together with -p option");
13825 cwd = getcwd(NULL, 0);
13826 if (cwd == NULL) {
13827 error = got_error_from_errno("getcwd");
13828 goto done;
13831 error = got_repo_pack_fds_open(&pack_fds);
13832 if (error != NULL)
13833 goto done;
13835 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13836 if (error) {
13837 if (error->code == GOT_ERR_NOT_WORKTREE)
13838 error = wrap_not_worktree_error(error, "stage", cwd);
13839 goto done;
13842 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13843 NULL, pack_fds);
13844 if (error != NULL)
13845 goto done;
13847 if (patch_script_path) {
13848 patch_script_file = fopen(patch_script_path, "re");
13849 if (patch_script_file == NULL) {
13850 error = got_error_from_errno2("fopen",
13851 patch_script_path);
13852 goto done;
13855 error = apply_unveil(got_repo_get_path(repo), 0,
13856 got_worktree_get_root_path(worktree));
13857 if (error)
13858 goto done;
13860 error = check_merge_in_progress(worktree, repo);
13861 if (error)
13862 goto done;
13864 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13865 if (error)
13866 goto done;
13868 if (list_stage)
13869 error = got_worktree_status(worktree, &paths, repo, 0,
13870 print_stage, NULL, check_cancelled, NULL);
13871 else {
13872 cpa.patch_script_file = patch_script_file;
13873 cpa.action = "stage";
13874 error = got_worktree_stage(worktree, &paths,
13875 pflag ? NULL : print_status, NULL,
13876 pflag ? choose_patch : NULL, &cpa,
13877 allow_bad_symlinks, repo);
13879 done:
13880 if (patch_script_file && fclose(patch_script_file) == EOF &&
13881 error == NULL)
13882 error = got_error_from_errno2("fclose", patch_script_path);
13883 if (repo) {
13884 const struct got_error *close_err = got_repo_close(repo);
13885 if (error == NULL)
13886 error = close_err;
13888 if (worktree)
13889 got_worktree_close(worktree);
13890 if (pack_fds) {
13891 const struct got_error *pack_err =
13892 got_repo_pack_fds_close(pack_fds);
13893 if (error == NULL)
13894 error = pack_err;
13896 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13897 free(cwd);
13898 return error;
13901 __dead static void
13902 usage_unstage(void)
13904 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13905 "[path ...]\n", getprogname());
13906 exit(1);
13910 static const struct got_error *
13911 cmd_unstage(int argc, char *argv[])
13913 const struct got_error *error = NULL;
13914 struct got_repository *repo = NULL;
13915 struct got_worktree *worktree = NULL;
13916 char *cwd = NULL;
13917 struct got_pathlist_head paths;
13918 int ch, pflag = 0;
13919 struct got_update_progress_arg upa;
13920 FILE *patch_script_file = NULL;
13921 const char *patch_script_path = NULL;
13922 struct choose_patch_arg cpa;
13923 int *pack_fds = NULL;
13925 TAILQ_INIT(&paths);
13927 #ifndef PROFILE
13928 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13929 "unveil", NULL) == -1)
13930 err(1, "pledge");
13931 #endif
13933 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13934 switch (ch) {
13935 case 'F':
13936 patch_script_path = optarg;
13937 break;
13938 case 'p':
13939 pflag = 1;
13940 break;
13941 default:
13942 usage_unstage();
13943 /* NOTREACHED */
13947 argc -= optind;
13948 argv += optind;
13950 if (patch_script_path && !pflag)
13951 errx(1, "-F option can only be used together with -p option");
13953 cwd = getcwd(NULL, 0);
13954 if (cwd == NULL) {
13955 error = got_error_from_errno("getcwd");
13956 goto done;
13959 error = got_repo_pack_fds_open(&pack_fds);
13960 if (error != NULL)
13961 goto done;
13963 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13964 if (error) {
13965 if (error->code == GOT_ERR_NOT_WORKTREE)
13966 error = wrap_not_worktree_error(error, "unstage", cwd);
13967 goto done;
13970 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13971 NULL, pack_fds);
13972 if (error != NULL)
13973 goto done;
13975 if (patch_script_path) {
13976 patch_script_file = fopen(patch_script_path, "re");
13977 if (patch_script_file == NULL) {
13978 error = got_error_from_errno2("fopen",
13979 patch_script_path);
13980 goto done;
13984 error = apply_unveil(got_repo_get_path(repo), 0,
13985 got_worktree_get_root_path(worktree));
13986 if (error)
13987 goto done;
13989 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13990 if (error)
13991 goto done;
13993 cpa.patch_script_file = patch_script_file;
13994 cpa.action = "unstage";
13995 memset(&upa, 0, sizeof(upa));
13996 error = got_worktree_unstage(worktree, &paths, update_progress,
13997 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13998 if (!error)
13999 print_merge_progress_stats(&upa);
14000 done:
14001 if (patch_script_file && fclose(patch_script_file) == EOF &&
14002 error == NULL)
14003 error = got_error_from_errno2("fclose", patch_script_path);
14004 if (repo) {
14005 const struct got_error *close_err = got_repo_close(repo);
14006 if (error == NULL)
14007 error = close_err;
14009 if (worktree)
14010 got_worktree_close(worktree);
14011 if (pack_fds) {
14012 const struct got_error *pack_err =
14013 got_repo_pack_fds_close(pack_fds);
14014 if (error == NULL)
14015 error = pack_err;
14017 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14018 free(cwd);
14019 return error;
14022 __dead static void
14023 usage_cat(void)
14025 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14026 "arg ...\n", getprogname());
14027 exit(1);
14030 static const struct got_error *
14031 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14033 const struct got_error *err;
14034 struct got_blob_object *blob;
14035 int fd = -1;
14037 fd = got_opentempfd();
14038 if (fd == -1)
14039 return got_error_from_errno("got_opentempfd");
14041 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14042 if (err)
14043 goto done;
14045 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14046 done:
14047 if (fd != -1 && close(fd) == -1 && err == NULL)
14048 err = got_error_from_errno("close");
14049 if (blob)
14050 got_object_blob_close(blob);
14051 return err;
14054 static const struct got_error *
14055 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14057 const struct got_error *err;
14058 struct got_tree_object *tree;
14059 int nentries, i;
14061 err = got_object_open_as_tree(&tree, repo, id);
14062 if (err)
14063 return err;
14065 nentries = got_object_tree_get_nentries(tree);
14066 for (i = 0; i < nentries; i++) {
14067 struct got_tree_entry *te;
14068 char *id_str;
14069 if (sigint_received || sigpipe_received)
14070 break;
14071 te = got_object_tree_get_entry(tree, i);
14072 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14073 if (err)
14074 break;
14075 fprintf(outfile, "%s %.7o %s\n", id_str,
14076 got_tree_entry_get_mode(te),
14077 got_tree_entry_get_name(te));
14078 free(id_str);
14081 got_object_tree_close(tree);
14082 return err;
14085 static const struct got_error *
14086 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14088 const struct got_error *err;
14089 struct got_commit_object *commit;
14090 const struct got_object_id_queue *parent_ids;
14091 struct got_object_qid *pid;
14092 char *id_str = NULL;
14093 const char *logmsg = NULL;
14094 char gmtoff[6];
14096 err = got_object_open_as_commit(&commit, repo, id);
14097 if (err)
14098 return err;
14100 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14101 if (err)
14102 goto done;
14104 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14105 parent_ids = got_object_commit_get_parent_ids(commit);
14106 fprintf(outfile, "numparents %d\n",
14107 got_object_commit_get_nparents(commit));
14108 STAILQ_FOREACH(pid, parent_ids, entry) {
14109 char *pid_str;
14110 err = got_object_id_str(&pid_str, &pid->id);
14111 if (err)
14112 goto done;
14113 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14114 free(pid_str);
14116 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14117 got_object_commit_get_author_gmtoff(commit));
14118 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14119 got_object_commit_get_author(commit),
14120 (long long)got_object_commit_get_author_time(commit),
14121 gmtoff);
14123 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14124 got_object_commit_get_committer_gmtoff(commit));
14125 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14126 got_object_commit_get_committer(commit),
14127 (long long)got_object_commit_get_committer_time(commit),
14128 gmtoff);
14130 logmsg = got_object_commit_get_logmsg_raw(commit);
14131 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14132 fprintf(outfile, "%s", logmsg);
14133 done:
14134 free(id_str);
14135 got_object_commit_close(commit);
14136 return err;
14139 static const struct got_error *
14140 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14142 const struct got_error *err;
14143 struct got_tag_object *tag;
14144 char *id_str = NULL;
14145 const char *tagmsg = NULL;
14146 char gmtoff[6];
14148 err = got_object_open_as_tag(&tag, repo, id);
14149 if (err)
14150 return err;
14152 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14153 if (err)
14154 goto done;
14156 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14158 switch (got_object_tag_get_object_type(tag)) {
14159 case GOT_OBJ_TYPE_BLOB:
14160 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14161 GOT_OBJ_LABEL_BLOB);
14162 break;
14163 case GOT_OBJ_TYPE_TREE:
14164 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14165 GOT_OBJ_LABEL_TREE);
14166 break;
14167 case GOT_OBJ_TYPE_COMMIT:
14168 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14169 GOT_OBJ_LABEL_COMMIT);
14170 break;
14171 case GOT_OBJ_TYPE_TAG:
14172 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14173 GOT_OBJ_LABEL_TAG);
14174 break;
14175 default:
14176 break;
14179 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14180 got_object_tag_get_name(tag));
14182 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14183 got_object_tag_get_tagger_gmtoff(tag));
14184 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14185 got_object_tag_get_tagger(tag),
14186 (long long)got_object_tag_get_tagger_time(tag),
14187 gmtoff);
14189 tagmsg = got_object_tag_get_message(tag);
14190 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14191 fprintf(outfile, "%s", tagmsg);
14192 done:
14193 free(id_str);
14194 got_object_tag_close(tag);
14195 return err;
14198 static const struct got_error *
14199 cmd_cat(int argc, char *argv[])
14201 const struct got_error *error;
14202 struct got_repository *repo = NULL;
14203 struct got_worktree *worktree = NULL;
14204 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14205 char *keyword_idstr = NULL;
14206 const char *commit_id_str = NULL;
14207 struct got_object_id *id = NULL, *commit_id = NULL;
14208 struct got_commit_object *commit = NULL;
14209 int ch, obj_type, i, force_path = 0;
14210 struct got_reflist_head refs;
14211 int *pack_fds = NULL;
14213 TAILQ_INIT(&refs);
14215 #ifndef PROFILE
14216 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14217 NULL) == -1)
14218 err(1, "pledge");
14219 #endif
14221 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14222 switch (ch) {
14223 case 'c':
14224 commit_id_str = optarg;
14225 break;
14226 case 'P':
14227 force_path = 1;
14228 break;
14229 case 'r':
14230 repo_path = realpath(optarg, NULL);
14231 if (repo_path == NULL)
14232 return got_error_from_errno2("realpath",
14233 optarg);
14234 got_path_strip_trailing_slashes(repo_path);
14235 break;
14236 default:
14237 usage_cat();
14238 /* NOTREACHED */
14242 argc -= optind;
14243 argv += optind;
14245 cwd = getcwd(NULL, 0);
14246 if (cwd == NULL) {
14247 error = got_error_from_errno("getcwd");
14248 goto done;
14251 error = got_repo_pack_fds_open(&pack_fds);
14252 if (error != NULL)
14253 goto done;
14255 if (repo_path == NULL) {
14256 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14257 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14258 goto done;
14259 if (worktree) {
14260 repo_path = strdup(
14261 got_worktree_get_repo_path(worktree));
14262 if (repo_path == NULL) {
14263 error = got_error_from_errno("strdup");
14264 goto done;
14267 if (commit_id_str == NULL) {
14268 /* Release work tree lock. */
14269 got_worktree_close(worktree);
14270 worktree = NULL;
14275 if (repo_path == NULL) {
14276 repo_path = strdup(cwd);
14277 if (repo_path == NULL)
14278 return got_error_from_errno("strdup");
14281 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14282 free(repo_path);
14283 if (error != NULL)
14284 goto done;
14286 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14287 if (error)
14288 goto done;
14290 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14291 if (error)
14292 goto done;
14294 if (commit_id_str != NULL) {
14295 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14296 repo, worktree);
14297 if (error != NULL)
14298 goto done;
14299 if (keyword_idstr != NULL)
14300 commit_id_str = keyword_idstr;
14301 if (worktree != NULL) {
14302 got_worktree_close(worktree);
14303 worktree = NULL;
14305 } else
14306 commit_id_str = GOT_REF_HEAD;
14307 error = got_repo_match_object_id(&commit_id, NULL,
14308 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14309 if (error)
14310 goto done;
14312 error = got_object_open_as_commit(&commit, repo, commit_id);
14313 if (error)
14314 goto done;
14316 for (i = 0; i < argc; i++) {
14317 if (force_path) {
14318 error = got_object_id_by_path(&id, repo, commit,
14319 argv[i]);
14320 if (error)
14321 break;
14322 } else {
14323 error = got_repo_match_object_id(&id, &label, argv[i],
14324 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14325 repo);
14326 if (error) {
14327 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14328 error->code != GOT_ERR_NOT_REF)
14329 break;
14330 error = got_object_id_by_path(&id, repo,
14331 commit, argv[i]);
14332 if (error)
14333 break;
14337 error = got_object_get_type(&obj_type, repo, id);
14338 if (error)
14339 break;
14341 switch (obj_type) {
14342 case GOT_OBJ_TYPE_BLOB:
14343 error = cat_blob(id, repo, stdout);
14344 break;
14345 case GOT_OBJ_TYPE_TREE:
14346 error = cat_tree(id, repo, stdout);
14347 break;
14348 case GOT_OBJ_TYPE_COMMIT:
14349 error = cat_commit(id, repo, stdout);
14350 break;
14351 case GOT_OBJ_TYPE_TAG:
14352 error = cat_tag(id, repo, stdout);
14353 break;
14354 default:
14355 error = got_error(GOT_ERR_OBJ_TYPE);
14356 break;
14358 if (error)
14359 break;
14360 free(label);
14361 label = NULL;
14362 free(id);
14363 id = NULL;
14365 done:
14366 free(label);
14367 free(id);
14368 free(commit_id);
14369 free(keyword_idstr);
14370 if (commit)
14371 got_object_commit_close(commit);
14372 if (worktree)
14373 got_worktree_close(worktree);
14374 if (repo) {
14375 const struct got_error *close_err = got_repo_close(repo);
14376 if (error == NULL)
14377 error = close_err;
14379 if (pack_fds) {
14380 const struct got_error *pack_err =
14381 got_repo_pack_fds_close(pack_fds);
14382 if (error == NULL)
14383 error = pack_err;
14386 got_ref_list_free(&refs);
14387 return error;
14390 __dead static void
14391 usage_info(void)
14393 fprintf(stderr, "usage: %s info [path ...]\n",
14394 getprogname());
14395 exit(1);
14398 static const struct got_error *
14399 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14400 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14401 struct got_object_id *commit_id)
14403 const struct got_error *err = NULL;
14404 char *id_str = NULL;
14405 char datebuf[128];
14406 struct tm mytm, *tm;
14407 struct got_pathlist_head *paths = arg;
14408 struct got_pathlist_entry *pe;
14411 * Clear error indication from any of the path arguments which
14412 * would cause this file index entry to be displayed.
14414 TAILQ_FOREACH(pe, paths, entry) {
14415 if (got_path_cmp(path, pe->path, strlen(path),
14416 pe->path_len) == 0 ||
14417 got_path_is_child(path, pe->path, pe->path_len))
14418 pe->data = NULL; /* no error */
14421 printf(GOT_COMMIT_SEP_STR);
14422 if (S_ISLNK(mode))
14423 printf("symlink: %s\n", path);
14424 else if (S_ISREG(mode)) {
14425 printf("file: %s\n", path);
14426 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14427 } else if (S_ISDIR(mode))
14428 printf("directory: %s\n", path);
14429 else
14430 printf("something: %s\n", path);
14432 tm = localtime_r(&mtime, &mytm);
14433 if (tm == NULL)
14434 return NULL;
14435 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14436 return got_error(GOT_ERR_NO_SPACE);
14437 printf("timestamp: %s\n", datebuf);
14439 if (blob_id) {
14440 err = got_object_id_str(&id_str, blob_id);
14441 if (err)
14442 return err;
14443 printf("based on blob: %s\n", id_str);
14444 free(id_str);
14447 if (staged_blob_id) {
14448 err = got_object_id_str(&id_str, staged_blob_id);
14449 if (err)
14450 return err;
14451 printf("based on staged blob: %s\n", id_str);
14452 free(id_str);
14455 if (commit_id) {
14456 err = got_object_id_str(&id_str, commit_id);
14457 if (err)
14458 return err;
14459 printf("based on commit: %s\n", id_str);
14460 free(id_str);
14463 return NULL;
14466 static const struct got_error *
14467 cmd_info(int argc, char *argv[])
14469 const struct got_error *error = NULL;
14470 struct got_worktree *worktree = NULL;
14471 char *cwd = NULL, *id_str = NULL;
14472 struct got_pathlist_head paths;
14473 char *uuidstr = NULL;
14474 int ch, show_files = 0;
14476 TAILQ_INIT(&paths);
14478 #ifndef PROFILE
14479 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14480 NULL) == -1)
14481 err(1, "pledge");
14482 #endif
14484 while ((ch = getopt(argc, argv, "")) != -1) {
14485 switch (ch) {
14486 default:
14487 usage_info();
14488 /* NOTREACHED */
14492 argc -= optind;
14493 argv += optind;
14495 cwd = getcwd(NULL, 0);
14496 if (cwd == NULL) {
14497 error = got_error_from_errno("getcwd");
14498 goto done;
14501 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14502 if (error) {
14503 if (error->code == GOT_ERR_NOT_WORKTREE)
14504 error = wrap_not_worktree_error(error, "info", cwd);
14505 goto done;
14508 #ifndef PROFILE
14509 /* Remove "wpath cpath proc exec sendfd" promises. */
14510 if (pledge("stdio rpath flock unveil", NULL) == -1)
14511 err(1, "pledge");
14512 #endif
14513 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14514 if (error)
14515 goto done;
14517 if (argc >= 1) {
14518 error = get_worktree_paths_from_argv(&paths, argc, argv,
14519 worktree);
14520 if (error)
14521 goto done;
14522 show_files = 1;
14525 error = got_object_id_str(&id_str,
14526 got_worktree_get_base_commit_id(worktree));
14527 if (error)
14528 goto done;
14530 error = got_worktree_get_uuid(&uuidstr, worktree);
14531 if (error)
14532 goto done;
14534 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14535 printf("work tree base commit: %s\n", id_str);
14536 printf("work tree path prefix: %s\n",
14537 got_worktree_get_path_prefix(worktree));
14538 printf("work tree branch reference: %s\n",
14539 got_worktree_get_head_ref_name(worktree));
14540 printf("work tree UUID: %s\n", uuidstr);
14541 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14543 if (show_files) {
14544 struct got_pathlist_entry *pe;
14545 TAILQ_FOREACH(pe, &paths, entry) {
14546 if (pe->path_len == 0)
14547 continue;
14549 * Assume this path will fail. This will be corrected
14550 * in print_path_info() in case the path does suceeed.
14552 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14554 error = got_worktree_path_info(worktree, &paths,
14555 print_path_info, &paths, check_cancelled, NULL);
14556 if (error)
14557 goto done;
14558 TAILQ_FOREACH(pe, &paths, entry) {
14559 if (pe->data != NULL) {
14560 const struct got_error *perr;
14562 perr = pe->data;
14563 error = got_error_fmt(perr->code, "%s",
14564 pe->path);
14565 break;
14569 done:
14570 if (worktree)
14571 got_worktree_close(worktree);
14572 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14573 free(cwd);
14574 free(id_str);
14575 free(uuidstr);
14576 return error;